我正在尝试使用Fragment填充列表视图。 但是当我运行它时app崩溃了。我从其他send获取 JSON 数据。我厌倦了将收到的数据添加到列表中然后更新它。有帮助吗?这是我的代码。
import android.app.ProgressDialog;
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.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.HashMap;
public class OneFragment extends Fragment {
public OneFragment() {
// Required empty public constructor
}
private ProgressDialog pDialog;
// JSON Node names
private static final String TAG_CONTACTS = "us";
private static final String TAG_NAME = "un";
private static final String TAG_EMAIL = "ui";
private static final String TAG = "JSON";
int portnumber = 3245;
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.fragment_one);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview = inflater.inflate(R.layout.fragment_one, container, false);
//View vew = inflater.inflate(R.layout.fragment_one, container, false);
new mparse().execute();
return rootview;
}
/* @Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
new mparse().execute();
}
*/
private class mparse extends AsyncTask<Void,Void,Void> {
private ProgressDialog pDialog = new ProgressDialog(getActivity());
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
DatagramSocket socket = null;
DatagramPacket p;
byte message[] = new byte[1000];
String jsonStr = "";
p = new DatagramPacket(message, message.length);
JSONObject jsonObj = null;
try {
Log.d(TAG, "about to create the socket");
socket = new DatagramSocket(portnumber);
if (socket == null)
Log.d("JSON", "Could not create socket");
socket.receive(p);
jsonStr = new String(p.getData());
Log.d(TAG, "the received string is" + jsonStr);
if (jsonStr != null) {
try {
jsonObj = new JSONObject(jsonStr);
Log.d(TAG, "inside the json");
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
// String id = c.getString(TAG_ID)
String name = c.getString(TAG_NAME);
Log.d(TAG, "value of user name is" + name);
String email = c.getString(TAG_EMAIL);
Log.d(TAG, "value of user id is " + email);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
//adding contact to contact list
Log.d(TAG, "the value of TAG_NAME " + TAG_NAME);
Log.d(TAG, "the value of TAG_EMAIL " + TAG_EMAIL);
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG, "inside JSON eception");
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (SocketException e) {
e.printStackTrace();
Log.d(TAG, "INside socketexception");
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG, "Inside the IOException");
}
return null;
}
@Override
protected void onPostExecute (Void arg) {
//super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListView mylistView = (ListView) getView().findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(
getActivity(), contactList,
R.layout.list_xml, new String[]{TAG_NAME, TAG_EMAIL,
}, new int[]{R.id.name,
R.id.email, R.id.mobile});
;
mylistView.setAdapter(adapter);
}
}
}
这是日志:
Process: com.example.kgj5kor.material, PID: 18196
java.lang.NullPointerException
at com.example.kgj5kor.material.OneFragment$mparse.onPostExecute(OneFragment.java:174)
at com.example.kgj5kor.material.OneFragment$mparse.onPostExecute(OneFragment.java:77)
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:157)
at android.app.ActivityThread.main(ActivityThread.java:5335)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
而不是在ListView
中创建onPostExecute()
对象,而是在onCreateView()
中创建并将其公开。将getView().findViewById
替换为rootview.findViewById
。
ListView mylistView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview = inflater.inflate(R.layout.fragment_one, container, false);
mylistView = (ListView) rootview.findViewById(R.id.list);
new mparse().execute();
return rootview;
}
按照Renan Bandeira的建议,在contactList
初始化您的onCreateView()
答案 1 :(得分:0)
永远不会初始化contactList
。用onCreateView()
方法初始化它,然后重试。
修改强>
我重写了课程以避免可能出现的问题。您有未初始化的属性,pDialog
在两个类中。另外,我将mparse
类的名称更改为Mparse
以使其正确符合惯例:
import android.app.ProgressDialog;
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.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.HashMap;
public class OneFragment extends Fragment {
public OneFragment() {
// Required empty public constructor
}
private ProgressDialog pDialog;
// JSON Node names
private static final String TAG_CONTACTS = "us";
private static final String TAG_NAME = "un";
private static final String TAG_EMAIL = "ui";
private static final String TAG = "JSON";
int portnumber = 3245;
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_one, container, false);
}
@Override public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
contactList = new ArrayList<>();
new Mparse().execute();
}
private class Mparse extends AsyncTask<Void,Void,Void> {
public Mparse() {
pDialog = new ProgressDialog(getActivity());
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
DatagramSocket socket = null;
DatagramPacket p;
byte message[] = new byte[1000];
String jsonStr = "";
p = new DatagramPacket(message, message.length);
JSONObject jsonObj = null;
try {
Log.d(TAG, "about to create the socket");
socket = new DatagramSocket(portnumber);
if (socket == null)
Log.d("JSON", "Could not create socket");
socket.receive(p);
jsonStr = new String(p.getData());
Log.d(TAG, "the received string is" + jsonStr);
if (jsonStr != null) {
try {
jsonObj = new JSONObject(jsonStr);
Log.d(TAG, "inside the json");
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
// String id = c.getString(TAG_ID)
String name = c.getString(TAG_NAME);
Log.d(TAG, "value of user name is" + name);
String email = c.getString(TAG_EMAIL);
Log.d(TAG, "value of user id is " + email);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
//adding contact to contact list
Log.d(TAG, "the value of TAG_NAME " + TAG_NAME);
Log.d(TAG, "the value of TAG_EMAIL " + TAG_EMAIL);
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG, "inside JSON eception");
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (SocketException e) {
e.printStackTrace();
Log.d(TAG, "INside socketexception");
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG, "Inside the IOException");
}
return null;
}
@Override
protected void onPostExecute (Void arg) {
super.onPostExecute(result);
//In case the Fragment isn't shown anymore.
if (!isAdded() || getView() == null) {
return;
}
// Dismiss the progress dialog
if (pDialog != null && pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListView mylistView = (ListView) getView().findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(
getActivity(), contactList,
R.layout.list_xml, new String[]{TAG_NAME, TAG_EMAIL,
}, new int[]{R.id.name,
R.id.email, R.id.mobile});
;
mylistView.setAdapter(adapter);
}
}
}