JSON Parsed Data not showing in ListFragment

2019-08-31 18:16发布

问题:

I have used a MYSQL Database and connected it to my Android App using PHP. I added a sample row in the table and the PHP Script is returning JSON. I have tried my best in parsing the JSON and displaying it in a list. But it does not seem to be working. Able to run the App - But does not display content - Only shows the Dialog. It seems to work in Case of an Activity - What changes should be made to make it work for a Fragment. Here is my LogCat when I open up the fragment - 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();
        }
      }
   }

EDIT :

Got my code to work. The Problem was with the JSON Structure. I did not Navigate properly and this gave me a "No Value for message" Error. For others who might be having same issues - Remember that when you have { in your JSON , you use JSONArray and when you have [ you use JSONObject. You need to navigate module wise through your JSON.

回答1:

try this code

pass json string to this method . it will work

public JSONObject getJSONfromURL(String url)

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

try {

// 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;
}