JSON解析数据未显示在ListFragment中

时间:2014-04-28 10:29:57

标签: android mysql json android-listfragment android-json

我使用了MYSQL数据库,并使用PHP将其连接到我的Android应用程序。我在表中添加了一个示例行,PHP脚本返回JSON。我已经尽力解析JSON并将其显示在列表中。但它似乎没有奏效。能够运行应用程序 - 但不显示内容 - 仅显示对话框。它似乎适用于一个活动的情况 - 应该做什么改变才能使它适用于片段。当我打开片段时,这是我的LogCat - http://prntscr.com/3f6k0a

package com.example.socbeta;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListFragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class events extends ListFragment {

private ProgressDialog pDialog;

 private static final String READ_EVENTS_URL ="http://socapptest.comoj.com/socbeta/events.php";   

//JSON IDS:
private static final String TAG_SUCCESS = "success";
private static final String TAG_EventName = "EventName";
private static final String TAG_POSTS = "posts";
private static final String TAG_ID = "ID";
private static final String TAG_DATE = "Date";
private static final String TAG_MESSAGE = "message";

private JSONArray mEvents = null;
private ArrayList<HashMap<String, String>> mEventList;


public events(){}

@Override public View onCreateView(LayoutInflater inflater, ViewGroup container,  Bundle savedInstanceState) 
{ 
  return inflater.inflate(R.layout.events, container, false); 
}



@Override
public void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    //loading the comments via AsyncTask
    new LoadEvents().execute();

  }
  public void updateJSONdata() {





    mEventList = new ArrayList<HashMap<String, String>>();


    JSONParser jParser = new JSONParser();

    JSONObject json = jParser.getJSONFromUrl(READ_EVENTS_URL);


    try {


        mEvents = json.getJSONArray(TAG_POSTS);


        for (int i = 0; i < mEvents.length(); i++) {
            JSONObject c = mEvents.getJSONObject(i);

            String EventName = c.getString(TAG_EventName);
            String content = c.getString(TAG_MESSAGE);
            String Date = c.getString(TAG_DATE);


            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();

            map.put(TAG_EventName, EventName);
            map.put(TAG_MESSAGE, content);
            map.put(TAG_DATE, Date);


            mEventList.add(map);


        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
}
private void updateList() {


ListAdapter adapter = new SimpleAdapter(getActivity(), mEventList,
        R.layout.list_item, 
        new String[] { TAG_EventName, TAG_MESSAGE,TAG_DATE }, 
        new int[] { R.id.eventname, R.id.message,R.id.date });



            setListAdapter(adapter);


            ListView lv = getListView();    
            lv.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {

            });
}

public class LoadEvents extends AsyncTask<Void, Void, Boolean> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Loading Events...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }
    @Override
    protected Boolean doInBackground(Void... arg0) {

        updateJSONdata();
        return null;

    }


    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        pDialog.dismiss();

        updateList();
        }
      }
   }

编辑:

让我的代码工作。问题在于JSON结构。我没有正确导航,这给了我一个&#34;没有价值的消息&#34;错误。对于可能遇到相同问题的其他人 - 请记住,当您拥有{使用JSON时,使用JSONArray以及何时使用JSONObject。您需要通过JSON导航模块。

1 个答案:

答案 0 :(得分:1)

试试这段代码

将json字符串传递给此方法。它会起作用

public JSONObject getJSONfromURL(String url)

{
    InputStream is = null;
    JSONObject jObj = null;
    String json = "";

尝试{

// defaultHttpClient
   DefaultHttpClient httpClient = new DefaultHttpClient();
   HttpGet httpget= new HttpGet(url);
   HttpResponse httpResponse = httpClient.execute(httpget);
   HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        }

    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    return jObj;
}