尝试使用JSON解析生成ExpandableListView获取错误,
我只是尝试将数据从JSON解析为单个子组,但失败了。任何人都解决它,这将对我有所帮助。将不胜感激。
项目包含无错误,但在部署后由仿真器强制关闭。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.Toast;
public class MainActivity extends Activity {
ExpandableListAdapter listAdapter;
ProgressDialog mProgressDialog;
ExpandableListView expListView;
List<String> listDataHeader;
ArrayList<HashMap<String, String>> arraylist;
HashMap<String, List<String>> listDataChild;
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
JSONArray contacts = null;
JSONObject jsonobject;
JSONArray jsonarray;
String [] str=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadJSON().execute();
// get the listview
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
// Listview Group click listener
expListView.setOnGroupClickListener(new OnGroupClickListener() {
@Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
// Toast.makeText(getApplicationContext(),
// "Group Clicked " + listDataHeader.get(groupPosition),
// Toast.LENGTH_SHORT).show();
return false;
}
});
// Listview Group expanded listener
expListView.setOnGroupExpandListener(new OnGroupExpandListener() {
@Override
public void onGroupExpand(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Expanded",
Toast.LENGTH_SHORT).show();
}
});
// Listview Group collasped listener
expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {
@Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Collapsed",
Toast.LENGTH_SHORT).show();
}
});
// Listview on child click listener
expListView.setOnChildClickListener(new OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
Toast.makeText(
getApplicationContext(),
listDataHeader.get(groupPosition)
+ " : "
+ listDataChild.get(
listDataHeader.get(groupPosition)).get(
childPosition), Toast.LENGTH_SHORT)
.show();
return false;
}
});
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Sharani Designs");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
@Override
protected Void doInBackground(Void... params)
{
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
jsonobject = JSONfunctions
.getJSONfromURL("http://api.androidhive.info/contacts/");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray(TAG_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);
str[i]=c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
}
catch (JSONException e) {
e.printStackTrace();
}
// TODO Auto-generated method stub
return null;
}
@Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
mProgressDialog.dismiss();
}
}
/*
* Preparing the list data
*/
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data
listDataHeader.add("Top 250");
listDataHeader.add("Now Showing");
listDataHeader.add("Coming Soon..");
// Adding child data
List<String> top250 = new ArrayList<String>();
for(int x=0;x<str.length;x++)
{
top250.add(str[x]);
}
List<String> nowShowing = new ArrayList<String>();
nowShowing.add("The Conjuring");
nowShowing.add("Despicable Me 2");
nowShowing.add("Turbo");
nowShowing.add("Grown Ups 2");
nowShowing.add("Red 2");
nowShowing.add("The Wolverine");
List<String> comingSoon = new ArrayList<String>();
comingSoon.add("2 Guns");
comingSoon.add("The Smurfs 2");
comingSoon.add("The Spectacular Now");
comingSoon.add("The Canyons");
comingSoon.add("Europa Report");
listDataChild.put(listDataHeader.get(0), top250); // Header, Child data
listDataChild.put(listDataHeader.get(1), nowShowing);
listDataChild.put(listDataHeader.get(2), comingSoon);
}
}
添加了互联网权限, 在我的项目包中有JSONfunctions类, JSON文件也是有效的。
我认为在这部分只发生逻辑错误,但不知道如何解决它,
for(int x=0;x<str.length;x++)
{
top250.add(str[x]);
}
02-07 06:47:06.231: E/AndroidRuntime(2490): FATAL EXCEPTION: main
02-07 06:47:06.231: E/AndroidRuntime(2490): Process: info.androidhive.expandablelistview, PID: 2490
02-07 06:47:06.231: E/AndroidRuntime(2490): java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.expandablelistview/info.androidhive.expandablelistview.MainActivity}: java.lang.NullPointerException
02-07 06:47:06.231: E/AndroidRuntime(2490): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
02-07 06:47:06.231: E/AndroidRuntime(2490): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
02-07 06:47:06.231: E/AndroidRuntime(2490): at android.app.ActivityThread.access$700(ActivityThread.java:135)
02-07 06:47:06.231: E/AndroidRuntime(2490): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
02-07 06:47:06.231: E/AndroidRuntime(2490): at android.os.Handler.dispatchMessage(Handler.java:102)
02-07 06:47:06.231: E/AndroidRuntime(2490): at android.os.Looper.loop(Looper.java:137)
02-07 06:47:06.231: E/AndroidRuntime(2490): at android.app.ActivityThread.main(ActivityThread.java:4998)
02-07 06:47:06.231: E/AndroidRuntime(2490): at java.lang.reflect.Method.invokeNative(Native Method)
02-07 06:47:06.231: E/AndroidRuntime(2490): at java.lang.reflect.Method.invoke(Method.java:515)
02-07 06:47:06.231: E/AndroidRuntime(2490): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
02-07 06:47:06.231: E/AndroidRuntime(2490): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
02-07 06:47:06.231: E/AndroidRuntime(2490): at dalvik.system.NativeStart.main(Native Method)
02-07 06:47:06.231: E/AndroidRuntime(2490): Caused by: java.lang.NullPointerException
02-07 06:47:06.231: E/AndroidRuntime(2490): at info.androidhive.expandablelistview.MainActivity.prepareListData(MainActivity.java:208)
02-07 06:47:06.231: E/AndroidRuntime(2490): at info.androidhive.expandablelistview.MainActivity.onCreate(MainActivity.java:60)
02-07 06:47:06.231: E/AndroidRuntime(2490): at android.app.Activity.performCreate(Activity.java:5243)
02-07 06:47:06.231: E/AndroidRuntime(2490): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
02-07 06:47:06.231: E/AndroidRuntime(2490): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
02-07 06:47:06.231: E/AndroidRuntime(2490): ... 11 more
02-07 06:47:06.511: D/dalvikvm(2490): GC_FOR_ALLOC freed 201K, 9% free 2984K/3260K, paused 28ms, total 28ms
02-07 06:47:08.771: I/Process(2490): Sending signal. PID: 2490 SIG: 9
答案 0 :(得分:0)
您的问题可能是您在JSON数据可用之前填充了ExpandableListView
。尝试在prepareListData
功能中调用onPostExecute
功能。
可能这需要一段时间,你的ExpandableListView
会空了,如果这样做后你没有填写expandablelistview试着打电话给expListView.invalidateViews
我看到的另一个问题是你没有初始化你的str
属性,这可能是你NPE的原因。
答案 1 :(得分:0)
在上面的代码中,您有以下内容:
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);
str[i]=c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
我没注意到你在哪里准确地初始化了str数组,其中有一些空格,如下所示:
str[] = new String[100]; // for example
如果可能的话尝试将其初始化为某个值,然后将值存储到数组中。
以后不能增加或减少数组大小,如果使用arraylist
代替它会很好。
此外,即使在prepareList()
方法中,您正在访问字符串的长度,当它未初始化为某个值时,如上所述。