列表视图中的空对象引用
Null object reference in list view
我在一个片段中有一个列表视图,我正在用来自 JSON 调用的信息填充它。
我在润湿片段中的列表视图时遇到问题。我的片段只扩展了片段,我假设这可能是我的问题所在。我用来帮助我导入 json 数据的示例代码没有使用片段,所以我有点困惑。
我的错误是:
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.access0(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)
片段
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布局
<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>
第 192 行是 lv.setAdapter(adapter);
ListView lv 未初始化(您在 onCreateView 中注释掉了该行):
//ListView lv = (ListView) v.findViewById(R.id.listView1);
你应该取消注释:
ListView lv = (ListView) v.findViewById(R.id.listView1);
编辑:好的,好的,对不起,您需要分配给全局 lv 变量而不是本地变量,试试这个:
lv = (ListView) v.findViewById(R.id.listView1);
这应该能让您获得正确的视图并使空异常消失...
你应该做
lv = (ListView) v.findViewById(R.id.listView1);
而不是
ListView lv = (ListView) v.findViewById(R.id.listView1);
这样做是在定义另一个在该方法中可见的 lv
变量,但您真正想要的是为 lv
class 变量赋值。
我在一个片段中有一个列表视图,我正在用来自 JSON 调用的信息填充它。
我在润湿片段中的列表视图时遇到问题。我的片段只扩展了片段,我假设这可能是我的问题所在。我用来帮助我导入 json 数据的示例代码没有使用片段,所以我有点困惑。
我的错误是:
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.access0(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)
片段
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布局
<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>
第 192 行是 lv.setAdapter(adapter);
ListView lv 未初始化(您在 onCreateView 中注释掉了该行):
//ListView lv = (ListView) v.findViewById(R.id.listView1);
你应该取消注释:
ListView lv = (ListView) v.findViewById(R.id.listView1);
编辑:好的,好的,对不起,您需要分配给全局 lv 变量而不是本地变量,试试这个:
lv = (ListView) v.findViewById(R.id.listView1);
这应该能让您获得正确的视图并使空异常消失...
你应该做
lv = (ListView) v.findViewById(R.id.listView1);
而不是
ListView lv = (ListView) v.findViewById(R.id.listView1);
这样做是在定义另一个在该方法中可见的 lv
变量,但您真正想要的是为 lv
class 变量赋值。