我是android开发的新手。我在mainactivity中使用JSON时没有问题,但是将代码移到ListFragment时遇到了问题
这行什么也没有发生:
JSONObject json = userFunctions.announcementFeed(myID,myType);
这是完整的代码:
package com.example.demo123;
import java.util.ArrayList;
import java.util.HashMap;
import library.UserFunctions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleAdapter;
public class AnnouncementList extends ListFragment {
private static final String TAG = "MyAnnouncement";
JSONArray announcementList = null;
UserFunctions userFunctions;
String myID = MainActivity.myID;
String myType = MainActivity.myType;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.i(TAG,"START ANNOUNCEMENT LIST");
ArrayList<HashMap<String, String>> theAnnnouncement = new ArrayList<HashMap<String, String>>();
JSONObject json = userFunctions.announcementFeed(myID, myType);
try {
if (json.getString("success") != null) {
announcementList = json.getJSONArray("announceDT");
for (int i = 0; i < announcementList.length(); i++) {
JSONObject c = announcementList.getJSONObject(i);
String title = c.getString("topic");
String course = c.getString("course") + " - " + c.getString("courseTitle");
String created = "By " + c.getString("entered_by") + " | " + c.getString("entry_date");
HashMap<String, String> map = new HashMap<String, String>();
map.put("title", title);
map.put("course", course);
map.put("created", created);
theAnnnouncement.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
String[] from = { "title","course","created" };
int[] to = { R.id.title,R.id.course,R.id.created};
SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(), theAnnnouncement, R.layout.list_item, from, to);
setListAdapter(adapter);
}
}
最佳答案
为什么绝对有必要将该逻辑放在onActivityCreated中?那时候您的Fragment不会被完全初始化,因此您可能需要将该逻辑移到onResume或其他地方。
编辑:我看了一下您链接的代码,以及announcementFeed()方法。
看来您正在尝试通过这种方法在主线程上进行一些联网。
public JSONObject announcementFeed(String username, String userType){
..................................
JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
// return json
return json;
}
您正在onActivityCreated中调用此方法。我建议将其移至后台线程或AsyncTask。尽管如此,如果没有LogCat,我不能100%确定发生了什么,但是至少我们能够指出这一点。