我有一个扩展listFragment的类。我编写了一个用于在类的oncreate中调用的方法中获取json响应的代码。为了在后台获取json,我创建了新的内部类,它扩展了asyncTask。我可以在logcat中的json响应中获取jsonarrays和字符串。但是当我尝试将它们保存在字符串数组中并将它们传递给我的自定义baseadapter时,我得到了一个nullpointer异常。
public class OnlineInfo extends ListFragment {
public static String result;
public String[] Technologies1;
public String[] TechnologyDescription1;
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
}
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
downloadjsonresponse();
}
public class Download extends AsyncTask<String, Void, String>
{
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
StringBuilder stringbuilder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet url = new HttpGet(params[0]);
try
{
Log.d("in background", "in background");
HttpResponse response = client.execute(url);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line ;
while((line = reader.readLine()) != null)
{
stringbuilder.append(line);
}
}
catch(ClientProtocolException e)
{
Log.d("error in clientprotocol", "error");
e.printStackTrace();
}
catch(IOException e)
{
Log.d("error in IO", "error");
e.printStackTrace();
}
return stringbuilder.toString();
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
OnlineInfo.result = result;
try {
JSONObject jsonobject = new JSONObject(result);
JSONArray raja = jsonobject.getJSONArray("Technologies");
//String raja = jsonobject.getJSONArray("Technologies").getJSONObject(0).getString("desc");
//Log.d("desc:", raja);
for(int i=0; i<raja.length();i++)
{
Technologies1[i] = raja.getJSONObject(i).getString("name");
TechnologyDescription1[i] = raja.getJSONObject(i).getString("desc");
Log.d("technology :", raja.getJSONObject(i).getString("name"));
Log.d("technologydescription :", raja.getJSONObject(i).getString("desc"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("desc:", "error");
}
getListView().setAdapter(new AdapterForOnlineInfo(getActivity(), OnlineInfo.this.Technologies1, OnlineInfo.this.TechnologyDescription1));
}
}
public void downloadjsonresponse()
{
Download jsonresponse = new Download();
jsonresponse.execute("http://www.avantajsoftwares.com/result.json");
}
}
每当我在for循环中注释这两行时,我就可以在logcat中得到结果:
Technologies1[i] = raja.getJSONObject(i).getString("name");
TechnologyDescription1[i] = raja.getJSONObject(i).getString("desc");
不知道出了什么问题。请有人给我一些见解......: - (
答案 0 :(得分:0)
我认为您需要在字符串数组中分配空间来保存新字符串。
在你的for
循环之前,尝试使用以下内容:
Technologies1 = new String[raja.length()];
TechnologyDescription1 = new String[raja.length()];