Yeahia Md Arif
Yeahia Md Arif

Reputation: 7936

Custom ListView with Asynctask not working in Fragment

My Fragment is not showing custom listview data. Asynctask is working properly but after sometime application is crashing with null pointer exception.

My fragment class code :

package com.example.y34h1a.androidlime.Fragment;

import android.app.ProgressDialog;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.example.y34h1a.androidlime.R;
import com.example.y34h1a.androidlime.adapter.FeedListAdapter;
import com.example.y34h1a.androidlime.data.FeedItem;
import com.example.y34h1a.androidlime.network.VolleySigleton;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

public class FragmentBoxOffice extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private VolleySigleton volleySigleton;
    private ImageLoader imageLoader;
    private RequestQueue requestQueue;
    private OnFragmentInteractionListener mListener;
    private static final String TAG = FragmentBoxOffice.class.getSimpleName();
    private ListView listView;
    private FeedListAdapter listAdapter;
    private ArrayList<FeedItem> feedItems;
    private String URL_FEED = "http://androidlime.com/wp-json/posts";
    private FeedItem feedItem = new FeedItem();


    // TODO: Rename and change types and number of parameters
    public static FragmentBoxOffice newInstance(String param1, String param2) {
        FragmentBoxOffice fragment = new FragmentBoxOffice();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }
    public FragmentBoxOffice() {
        // Required empty public constructor
        feedItems = new ArrayList<FeedItem>();
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View view =  inflater.inflate(R.layout.fragment_box_office, container, false);
        listView = (ListView) view.findViewById(R.id.fragmentList);
        new JSONAsyncTask().execute(URL_FEED);
        return view;
    }
    class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {

        ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(getActivity());
            dialog.setMessage("Loading...");
            dialog.show();
            dialog.setCancelable(false);
        }

        @Override
        protected Boolean doInBackground(String... urls) {
            for(String url : urls){
                try {
                    HttpClient client = new DefaultHttpClient();
                    HttpGet get = new HttpGet(url);
                    HttpResponse response = client.execute(get);
                    HttpEntity entity = response.getEntity();
                    String data = EntityUtils.toString(entity);
                    JSONArray jsonArray = new JSONArray(data);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject titleObj = jsonArray.getJSONObject(i);
                        String title = titleObj.getString("title");
                        feedItem.setStatus(title);
                        Log.i("arif", title);
                        //DATE
                        String date = titleObj.getString("date");
                        feedItem.setTimeStamp(date);
                        Log.i("arif", date);

                        //Author Name
                        JSONObject author = titleObj.getJSONObject("author");
                        String name = author.getString("name");
                        feedItem.setName(name);
                        Log.i("arif", name);

                        //Author Profile Pic
                        String profilePic = author.getString("avatar");
                        feedItem.setProfilePic(profilePic);
                        Log.i("arif", profilePic);

                        //Post thumbnail
                        JSONObject thumnailObj = titleObj.getJSONObject("featured_image");
                        String thumbnail = thumnailObj.getString("guid");
                        feedItem.setThumnail(thumbnail);
                        Log.i("arif", thumbnail);
                        feedItems.add(feedItem);
                    }
                    return true;

                    //------------------>>
                } catch (IOException e) {
                    Log.e("arif", "Parse Exception");
                } catch (JSONException e) {
                    Log.e("arif", "Parse Exception");
                }
            }
            return false;
        }


        protected void onPostExecute(Boolean result) {
            dialog.cancel();

            listAdapter = new FeedListAdapter(getActivity().getApplicationContext(),R.layout.feed_item,feedItems);
            listView.setAdapter(listAdapter);
            if(result == false)
               Log.i("arif","unable to featch data");

        }
    }


    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }

}

My Custom Adapter Class:

    package com.example.y34h1a.androidlime.adapter;


import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.y34h1a.androidlime.R;
import com.example.y34h1a.androidlime.data.FeedItem;

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

public class FeedListAdapter extends ArrayAdapter<FeedItem> {
    private LayoutInflater vi;
    private List<FeedItem> feedItems;
    int Resource;
    ViewHolder holder;

    public FeedListAdapter(Context context, int resource, ArrayList<FeedItem> feedItems) {
        super(context, resource, feedItems);
        this.feedItems = feedItems;
        Resource = resource;
    }


    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // convert view = design
        View v = convertView;
        if (v == null) {
            holder = new ViewHolder();
            v = ((Activity)getContext()).getLayoutInflater().inflate(R.layout.feed_item,null);
            holder.name = (TextView) v.findViewById(R.id.name);
            holder.status = (TextView) v.findViewById(R.id.txtStatusMsg);
            holder.time = (TextView) v.findViewById(R.id.timestamp);
            holder.url = (TextView) v.findViewById(R.id.txtUrl);
            holder.profilePic = (ImageView) v.findViewById(R.id.profilePic);
            holder.thumbnail = (ImageView) v.findViewById(R.id.thumbernail);
            v.setTag(holder);
        } else {
            holder = (ViewHolder) v.getTag();
        }

            v.setTag(holder);

        holder.name.setText(feedItems.get(position).getName());
        holder.status.setText(feedItems.get(position).getStatus());
        holder.time.setText(feedItems.get(position).getTimeStamp());
        holder.url.setText(feedItems.get(position).getUrl());
        holder.profilePic.setImageResource(R.drawable.ic_launcher);
        holder.profilePic.setImageResource(R.drawable.sample);
        return v;

    }

    static class ViewHolder {
        public TextView name;
        public TextView status;
        public TextView url;
        public TextView time;
        public ImageView profilePic;
        public ImageView thumbnail;

    }
}

The line where error showing is :

View v = ((Activity)getContext()).getLayoutInflater().inflate(R.layout.feed_item,null);'

Upvotes: 0

Views: 134

Answers (2)

justHooman
justHooman

Reputation: 3054

From your code, I think your error is more like ClassCastException, don't know why it's NPE, because

listAdapter = new FeedListAdapter(getActivity().getApplicationContext(),R.layout.feed_item,feedItems);

You pass a ApplicationContext then cast it to a Activity

v = ((Activity)getContext()).getLayoutInflater().inflate(R.layout.feed_item,null);

Try this may works:
in onPostExecute:

if (getActivity() != null) {
   listAdapter = new FeedListAdapter(getActivity().getApplicationContext(),R.layout.feed_item,feedItems);
   listView.setAdapter(listAdapter);
}

in getView:

v = LayoutInflater.from(parent.getContext()).inflate(R.layout.feed_item, parent, false);

Upvotes: 1

Thomas R.
Thomas R.

Reputation: 8073

Try:

v = (LayoutInflater.from(getContext()).inflate(R.layout.feed_item, parent, false);

Upvotes: 0

Related Questions