TWeeKeD TWeeKeD - 6 months ago 48
JSON Question

Null object reference in list view

I have a listview in a fragment that I am populating with information from a JSON call.

I am having an issue wetting up the listview in my fragment. My fragment only extends Fragment and I am assuming this may be where my issue is. the sample code I was working from to assist me with importing the json data was not using fragments so Im a little confused.

My error is:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference

at com.peekatu.Fcc4me.watchFragment$GetContacts.onPostExecute(watchFragment.java:192)
at com.peekatu.Fcc4me.watchFragment$GetContacts.onPostExecute(watchFragment.java:119)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)


Fragment

public class watchFragment extends Fragment {


private static final String TAG_DATA = "data";
private static final String TAG_TITLE = "title";
private static final String TAG_URL = "video_url";
private static final String TAG_IMAGE = "image";
public ListView lv;

private ProgressDialog pDialog;

// URL to get contacts JSON
private static String url = "/load.php";

// contacts JSONArray
JSONArray data = null;

// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList;

private WebView web_v;
// 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;


/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment watchFragment.
*/
// TODO: Rename and change types and number of parameters
public static watchFragment newInstance(String param1, String param2) {
watchFragment fragment = new watchFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public watchFragment() {
// Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}

}

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

View v= inflater.inflate(R.layout.fragment_watch, container, false);

//btn = (Button) v.findViewById(R.id.button1);
dataList = new ArrayList<HashMap<String, String>>();

ListView lv = (ListView) v.findViewById(R.id.listView1);


// Calling async task to get json
new GetVideos().execute();



return v;
}

private class GetVideos extends AsyncTask<Void, Void, Void> {

@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();

}

@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();

// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

Log.d("Response: ", "> " + jsonStr);

if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);

// Getting JSON Array node
data = jsonObj.getJSONArray(TAG_DATA);

// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject d = data.getJSONObject(i);

String title = d.getString(TAG_TITLE);
String image = d.getString(TAG_IMAGE);
String url = d.getString(TAG_URL);

// tmp hashmap for single contact
HashMap<String, String> data = new HashMap<String, String>();

// adding each child node to HashMap key => value
data.put(TAG_TITLE, title);
data.put(TAG_IMAGE, image);
data.put(TAG_URL, url);

// adding contact to contact list
dataList.add(data);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}

return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), dataList,
R.layout.list_item, new String[] { TAG_TITLE, TAG_IMAGE
}, new int[] { R.id.title,
R.id.image});

lv.setAdapter(adapter);
}
}
}


XML Layout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.peekatu.Fcc4me.watchFragment">

<!-- TODO: Update blank fragment layout -->

<VideoView
android:layout_width="wrap_content"
android:layout_height="225dp"
android:id="@+id/videoView"
android:layout_gravity="center_horizontal|top" />

<ListView
android:id="@+id/listView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/videoView" />

</RelativeLayout>


Line 192 is
lv.setAdapter(adapter);

Answer

The ListView lv is not initialized (you commented out that line in onCreateView):

//ListView lv = (ListView) v.findViewById(R.id.listView1);

you should uncomment it:

ListView lv = (ListView) v.findViewById(R.id.listView1);

EDIT: Ok, ok, I am sorry, you need to assign to the global lv variable instead of the local one, try this:

lv = (ListView) v.findViewById(R.id.listView1);

This should get you the correct view and make null exception dissapear...

Comments