简体   繁体   中英

Android: AsyncTask RecyclerView error;

i've got a problem. I'm trying to retrieve data from my MySQL server with an AsyncTask.

public class HomeFragment extends Fragment {

// RecyclerView
RecyclerView recyclerView;
RecyclerView.Adapter rvAdapter;
RecyclerView.LayoutManager rvLayoutManger;
List<NewsData> news_list;



@Nullable
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.activity_home, null);

    // RecyclerView Setup
    recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view1);
    rvLayoutManger = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(rvLayoutManger);
    rvAdapter = new HomeRecyclerAdapter(getActivity(), news_list);
    recyclerView.setAdapter(rvAdapter);
    news_list = new ArrayList<>();

    load_data_from_server(0);

    return view;
}

private void load_data_from_server(int i) {
    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("here is my URL").build();
            try {
                Response response = client.newCall(request).execute();

                JSONArray array = new JSONArray(request.body().toString());

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

                    NewsData data = new NewsData(object.getInt("id"), object.getString("title"), object.getString("describtion"));
                    news_list.add(data);
                }

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

        @Override
        protected void onPostExecute(Void aVoid) {
            rvAdapter.notifyDataSetChanged();
        }
    };
    task.execute(id);
}



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

}

}

This is my Class that should retrieve the data and i wanna list it in an RecyclerView thats why i got this Adapter.

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

private Context context;
private List<NewsData> news_list;

public HomeRecyclerAdapter(Context context, List<NewsData> news_list) {
    this.context = context;
    this.news_list = news_list;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_cardviewhome, parent, false);

    return new ViewHolder(itemView);
}

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

    holder.title.setText(news_list.get(position).getTitle());

}

@Override
public int getItemCount() {

    return 0;
}


public class ViewHolder extends RecyclerView.ViewHolder{
    public TextView title;

    public ViewHolder(View itemView){
        super(itemView);
        title = (TextView) itemView.findViewById(R.id.title_cView);


    }
}

}

But after I run it i got this error

E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
              Process: com.example.andreundjulia.dbg_ahlhorn, PID: 25407
              java.lang.RuntimeException: An error occurred while executing doInBackground()
                  at android.os.AsyncTask$3.done(AsyncTask.java:309)
                  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                  at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                  at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
                  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                  at java.lang.Thread.run(Thread.java:818)
               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
                  at com.example.andreundjulia.dbg_ahlhorn.Fragments.HomeFragment$1.doInBackground(HomeFragment.java:73)
                  at com.example.andreundjulia.dbg_ahlhorn.Fragments.HomeFragment$1.doInBackground(HomeFragment.java:65)
                  at android.os.AsyncTask$2.call(AsyncTask.java:295)
                  at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
                  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
                  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
                  at java.lang.Thread.run(Thread.java:818) 

I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@9bd1046 time:652009764 V/FA: Screen exposed for less than 1000 ms. Event not sent. time: 248 V/FA: Activity paused, time: 1189877240 D/ViewRootImpl: #3 mView = null V/FA: Inactivity, disconnecting from the service Application terminated.

So I would like to know if someone of you guys could help me with this by the way here is my Getter/Setter Class.

        public class NewsData {

private int id;
private String title, describtion;

public int getId() {
    return id;
}

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

public NewsData(int id, String title, String describtion){
    this.id = id;

    this.title = title;
    this.describtion = describtion;
}

public String getTitle(){
    return title;
}

public void  setTitle(String title){
    this.title = title;
}

public String getDescribtion(){
    return describtion;
}

public void setDescribtion(String describtion) {
    this.describtion = describtion;
}

I hope someone could help me i stuck here for very long time and cant get me out alone :/

Thank you!

Add response not request :

Remove this:

JSONArray array = new JSONArray(request.body().toString());

With this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM