2

我是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);        
}

}

4

1 回答 1

1

为什么绝对有必要将该逻辑放在 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% 确定发生了什么,但至少我们能够指出这一点。

于 2013-07-24T04:35:21.353 回答