java - Fragment.java 错误 :(94, 51) 错误:不兼容的类型:NewsFragment 无法转换为 Context

标签 java android android-fragments

大家好,我正在尝试弄清楚如何解析 JSON 并使用 recyclerViewcardview 进行显示。我不明白为什么 fragment 不能转换为上下文。以前有人遇到过这个错误吗?

错误从这里开始:

gridLayoutManager = new GridLayoutManager(this,2);
mRecyclerView.setLayoutManager(gridLayoutManager);
nAdapter = new newsAdapter(this,data_list);

消息 Gradle 构建:

D:\New folder\DrawerWithSwipeTabs\app\src\main\java\com\androidbelieve\drawerwithswipetabs\NewsFragment.java Error:(94, 51) error: incompatible types: NewsFragment cannot be converted to Context Error:(97, 36) error: incompatible types: NewsFragment cannot be converted to Context Error:Execution failed for task ':app:compileDebugJavaWithJavac'. Compilation failed; see the compiler error output for details.

NewsFragment.java

package com.androidbelieve.drawerwithswipetabs;

import android.app.LauncherActivity;
import android.graphics.Movie;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Ratan on 7/29/2015.
 */


public class NewsFragment extends Fragment {

    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private GridLayoutManager gridLayoutManager;
    private newsAdapter nAdapter;
    private List<listnews> data_list;


    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View view = inflater.inflate(R.layout.news_layout,container,false);
        mRecyclerView =(RecyclerView)view.findViewById(R.id.recyclerview);
        mRecyclerView.setHasFixedSize(true);


        data_list = new ArrayList<>();
        load_data_from_server(0);

        gridLayoutManager = new GridLayoutManager(this,2);
        mRecyclerView.setLayoutManager(gridLayoutManager);

        nAdapter = new newsAdapter(this,data_list);
        mRecyclerView.setAdapter(nAdapter);

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

                if(gridLayoutManager.findLastCompletelyVisibleItemPosition() == data_list.size()-1)
                {
                    load_data_from_server(data_list.get(data_list.size()-1).getId());
                }

            }
        });



        return view;



    }



    private void load_data_from_server(final int id)
    {
        AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() {
            @Override
            protected Void doInBackground(Integer... params) {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("http://192.168.107.1/ibmcoe_la/selected.php?id="+id)
                        .build();

                try{
                    Response response = client.newCall(request).execute();

                    JSONArray array = new JSONArray(response.body().string());

                    for(int i=0; i<array.length(); i++)
                    {
                        JSONObject object = array.getJSONObject(i);

                        listnews data = new listnews(object.getInt("news_id"),object.getString("path_image")
                                ,object.getString("news_title"),object.getString("news_image"),object.getString("news_description"));

                        data_list.add(data);
                    }



                }catch (IOException e){
                    e.printStackTrace();
                }catch (JSONException e){
                    System.out.println("End of content");
                }

                return null;
            }

            protected void onPostExecute(Void avoid){
                nAdapter.notifyDataSetChanged();
            }
        };

        task.execute(id);
    }

    @Override
    public String toString()
    {
        return "NewsFragment";
    }






}

newsAdapter.java

package com.androidbelieve.drawerwithswipetabs;

import android.content.Context;
import android.provider.ContactsContract;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by LENOVO on 20/2/2017.
 */


public class newsAdapter extends RecyclerView.Adapter<newsAdapter.ViewHolder> {



    private Context context;
    private List<listnews> my_data;

    public newsAdapter(Context context, List<listnews> my_data)
    {
        this.context = context;
        this.my_data = my_data;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycle_news,parent,false);

        return new ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        holder.description.setText(my_data.get(position).getImagedescription());
        Glide.with(context).load(my_data.get(position).getImagepath()).into(holder.dataimage);

    }

    @Override
    public int getItemCount() {
        return 0;
    }

    public static  class ViewHolder extends RecyclerView.ViewHolder {

        public TextView description;
        public TextView imagetitle;
        public ImageView dataimage;

        public ViewHolder(View itemView) {
            super(itemView);
            description = (TextView) itemView.findViewById(R.id.textView3);
            imagetitle = (TextView) itemView.findViewById(R.id.textView4);
            dataimage = (ImageView) itemView.findViewById(R.id.imageView4);

        }
    }




}

listnews.java

package com.androidbelieve.drawerwithswipetabs;

/**
 * Created by LENOVO on 21/2/2017.
 */

public class listnews {

    public int id;
    public String imagedescription, image, imagepath, imagetitle;

    public listnews(int id, String imagedescription, String image, String imagepath, String imagetitle) {
        this.id = id;
        this.imagedescription = imagedescription;
        this.image = image;
        this.imagepath = imagepath;
        this.imagetitle = imagetitle;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getImagedescription() {
        return imagedescription;
    }

    public void setImagedescription(String imagedescription) {
        this.imagedescription = imagedescription;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getImagepath() {
        return imagepath;
    }

    public void setImagepath(String imagepath) {
        this.imagepath = imagepath;
    }

    public String getImagetitle() {
        return imagetitle;
    }

    public void setImagetitle(String imagetitle) {
        this.imagetitle = imagetitle;
    }
}

recycle.news.xml( fragment 布局)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"


    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView

        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical"
        android:id="@+id/recyclerview"
        android:clickable="true"
        android:focusable="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">

    </android.support.v7.widget.RecyclerView>


</RelativeLayout>

recycle_news.xml(卡片 View 布局)

<android.support.v7.widget.CardView
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:android2="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="https://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/card_view"
    android:layout_width="match_parent"

    android2:layout_marginTop="5dp"
    android2:layout_marginLeft="5dp"
    android2:layout_marginRight="5dp"
    android2:layout_gravity="center|top"
    card_view:cardPreventCornerOverlap="false"
    card_view:cardCornerRadius="20dp"
    android2:layout_width="match_parent"
    android2:layout_height="wrap_content">

<FrameLayout
    android2:layout_width="match_parent"
    android2:layout_height="400dp"
    app:cardElevation="0dp"
    android2:background="@drawable/cardviewstring">



    <LinearLayout
        android2:orientation="vertical"
        android2:layout_width="380dp"
        android2:layout_height="match_parent"


        android2:weightSum="1"
        android2:layout_marginRight="20dp">

        <LinearLayout
            android2:orientation="vertical"
            android2:layout_width="match_parent"
            android2:layout_weight="1"
            android2:layout_height="250dp">

            <ImageView
                android2:layout_width="match_parent"
                android2:layout_height="match_parent"
                app:srcCompat="@mipmap/ic_launcher"
                android2:id="@+id/imageView4" />

        </LinearLayout>

        <LinearLayout
            android2:orientation="vertical"
            android2:layout_width="match_parent"
            android2:layout_height="wrap_content"
            android2:paddingTop="25dp">

            <ScrollView
                android2:layout_width="match_parent"
                android2:layout_height="84dp"
                android2:background="@drawable/screen_background_dark_transparent"
                android2:layout_marginLeft="3dp">

                <LinearLayout
                    android2:layout_width="match_parent"
                    android2:layout_height="wrap_content"
                    android2:orientation="vertical" >

                    <TextView
                        android2:text="TextView"
                        android2:layout_width="match_parent"
                        android2:layout_height="wrap_content"
                        android2:id="@+id/textView4" />

                    <TextView
                        android2:text="TextView"
                        android2:layout_width="match_parent"
                        android2:layout_height="35dp"
                        android2:id="@+id/textView3" />
                </LinearLayout>
            </ScrollView>

        </LinearLayout>

        <LinearLayout
            android2:orientation="vertical"
            android2:layout_marginTop="10dp"
            android2:layout_width="match_parent"
            android2:layout_height="42dp"
            android:layout_alignParentBottom="true">

            <LinearLayout
                android2:orientation="horizontal"
                android2:layout_width="match_parent"
                android2:layout_height="match_parent">

                <ImageView
                    android2:layout_width="wrap_content"
                    android2:layout_height="wrap_content"
                    app:srcCompat="@drawable/ic_share"
                    android2:id="@+id/imageView3"
                    android2:layout_weight="1" />

                <ImageView
                    android2:layout_width="wrap_content"
                    android2:layout_height="wrap_content"
                    app:srcCompat="@drawable/ic_like"
                    android2:id="@+id/imageView2"
                    android2:layout_weight="1" />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>

</FrameLayout>

</android.support.v7.widget.CardView>

最佳答案

使用

gridLayoutManager = new GridLayoutManager(getActivity(),2);
    mRecyclerView.setLayoutManager(gridLayoutManager);

而不是

gridLayoutManager = new GridLayoutManager(this,2);
        mRecyclerView.setLayoutManager(gridLayoutManager);

您不能使用 this 获取 fragment 内的上下文。您必须使用 getActivity() 从 fragment 的父 Activity 获取上下文。

关于java - Fragment.java 错误 :(94, 51) 错误:不兼容的类型:NewsFragment 无法转换为 Context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42524531/

相关文章:

java - 非法状态异常 : Cannot forward after response has been committed

android - 如何更改电源 Estimote 信标?

android - 为什么服务在启动设备android后不自动启动

Android Studio 无法解析符号 'TabLayout'

android - 为什么 ListFragment 在没有 ListView 标签的情况下工作?

java - Kotlin ViewPager2 : Class 'ScreenSlidePagerAdapter' is not abstract and does not implement base class member

c# - Cassandra get_range_slice

java - Gson 中的自定义 Java map 反序列化器

java - 无法显示字符串

android - 我可以每 1 小时自动开始 Activity 吗?