如何解析JSONArray并在列表视图中显示数据

时间:2015-04-24 09:49:38

标签: android json listview

在我的Android应用程序中,我现在收到一个Response数组,我需要获取它并在listview中显示数据。我知道如何解析单个数据但这次我需要解析一个数组,我已经尝试过了但列表项重复这是我试过的...结果是

enter image description here

    AsyncHttpClient client = new AsyncHttpClient();
    RequestParams params = new RequestParams();
    params.put("topicsJSON",composeJSON());
    client.post("http://www.example.com/LSM_Sci-Mat/load_topics.php",params,new AsyncHttpResponseHandler()
    {

        public void onSuccess(String response)
        {


            Gson gson = new GsonBuilder().create();
            try 
            {

                JSONArray arr = new JSONArray(response);

                for (int i = 0; i < arr.length(); i++) 
                {
                    //JSONObject obj = (JSONObject) arr.get(i);


                    list.add(arr.get(i).toString());

                    //Toast.makeText(getApplicationContext(), "Element ==> "+list, 5000).show();

                }
                load_data();
            }
            catch (JSONException e) 
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

                }

        @Override
        public void onFailure(int statusCode, Throwable error,String content)

        {

            if (statusCode == 404) 

            {
                Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
            } 

            else if (statusCode == 500) 

            {
                Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
            } 

            else 

            {
                Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]",
                        Toast.LENGTH_LONG).show();
            }
        }

    });



}

private String composeJSON() {
    // TODO Auto-generated method stub
    ArrayList<HashMap<String, String>> check_in_List;
    check_in_List = new ArrayList<HashMap<String, String>>();
    HashMap<String, String> map = new HashMap<String, String>();

    map.put("subject_code",received_subject_code);


    check_in_List.add(map);
    Gson gson = new GsonBuilder().create();
    return gson.toJson(check_in_List);

}

public void load_data()
{
    ArrayAdapter<String> phy = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,list);

    l1.setAdapter(phy);

    l1.setOnItemClickListener(new OnItemClickListener() { 
        public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
            // When clicked, show a toast with the TextView text 

            //String pos = (String) l1.getItemAtPosition(position);
            int topic_index = position + 1;
            String pos = String.valueOf(topic_index);

            }


    }); 

}

1 个答案:

答案 0 :(得分:0)

这是一种简单的技术。您应该从Url获​​取JSON的内容,然后解析它以在ListView上显示。我根据你的网址制作了一个场景。请遵循以下代码。

import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class SampleActivity extends Activity
{
    ListView listView;

    String url = "http://www.thetaf.com/LSM_Sci-Mat/load_topics.php";

    ArrayList<String> data = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.sample);

        listView = (ListView) findViewById(R.id.listView1);

        new GetData().execute();
    }

    private class GetData extends AsyncTask<String, Void, JSONArray>
    {
        ProgressDialog pd;

        @Override
        protected void onPreExecute() 
        {
            pd = ProgressDialog.show(SampleActivity.this, "", "Getting Data from server");
        }

        @Override
        protected JSONArray doInBackground(String... params) 
        {
            try
            {
                HttpClient client = new DefaultHttpClient();

                HttpPost httpPost = new HttpPost(url);

                HttpResponse httpResponse = client.execute(httpPost);

                HttpEntity entity = httpResponse.getEntity();

                String responseInString = EntityUtils.toString(entity);

                return new JSONArray(responseInString);
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(JSONArray result) 
        {
            super.onPostExecute(result);

            pd.dismiss();

            if(result != null)
            {
                try
                {
                    data.clear();

                    for(int a = 0; a < result.length(); a++)
                    {
                        JSONArray array = result.getJSONArray(a);

                        for(int b = 0; b < array.length(); b++)
                        {
                            data.add(array.getString(b));
                        }
                    }

                    if(data.size() > 0)
                    {
                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(SampleActivity.this, 
                                android.R.layout.simple_list_item_1, data);

                        listView.setAdapter(adapter);

                        // here you can also define your custom adapter and set it to listView 
                        //according to your own defined layout as items
                    }
                    else
                    {
                        Toast.makeText(SampleActivity.this, "No Data Found", Toast.LENGTH_LONG).show();
                    }

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