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

时间:2017-03-01 06:16:06

标签: java android android-fragments

大家好,我正试图弄清楚如何解析JSON并显示recyclerViewcardview。我不明白为什么片段无法转换为上下文。以前有人遇到过这个错误吗?

错误从这里开始:

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

消息Gradle Build:

  

d:\新   文件夹\ DrawerWithSwipeTabs \程序\ SRC \主\ java中的\ com \ androidbelieve \ drawerwithswipetabs \ NewsFragment.java       错误:(94,51)错误:不兼容的类型:NewsFragment无法转换为Context       错误:(97,36)错误:不兼容的类型:NewsFragment无法转换为Context       错误:任务':app:compileDebugJavaWithJavac'执行失败。       编译失败;有关详细信息,请参阅编译器错误输出。

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(片段布局)

<?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(cardview布局)

<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>

2 个答案:

答案 0 :(得分:0)

使用

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

而不是

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

您无法使用this获取片段内的上下文。您必须使用getActivity()从片段的父活动中获取上下文。

答案 1 :(得分:0)

你的问题是这一行 -

gridLayoutManager = new GridLayoutManager(this, 2); // this refers to your current fragment
nAdapter = new newsAdapter(this,data_list); // same mistake

基本上,您不能将Fragment用作context。相反,您需要使用附加Fragment的活动。通过getActivity()的{​​{1}}方法获取您的活动。

我告诉你原因 - Fragment延伸ActivityContext没有。

最后,代码将是,

Fragment