解析JSON响应列表视图异步编程

时间:2013-08-23 08:56:56

标签: java android json

我正在尝试填充列表视图的餐馆名称

  • 但有一些错误
  • 我已经提到了下面的代码

MainActivity.java

public class MainActivity extends Activity {

    // url to make request
    private static String url = "http://xxxxxxxx/";

    // JSON Node names
    private static final String TAG_RESTAURANTS = "restaurants";
    private static final String TAG_RESTAURANT_ID = "restaurantID";
    private static final String TAG_RESTAURANT_NAME = "restaurantNAME";


    // Hashmap for ListView
    ArrayList<HashMap<String, String>> RestaurantList = new ArrayList<HashMap<String, String>>();

    // contacts JSONArray
    JSONArray restaurants = null;

    ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Instantiating ProgressDialog with onCreate method
        progressDialog=new ProgressDialog(MainActivity.this);
        new ParsingAsync().execute();

    }

    private class ParsingAsync extends AsyncTask<Void, Void, Void>
    {

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            progressDialog=ProgressDialog.show(MainActivity.this, "", "Please Wait", true, false);


        }

        @Override
        protected Void doInBackground(Void... params) {

            JSONObjParser jParser = new JSONObjParser();

            JSONObject json = jParser.getJSONFromUrl(url);

            try {

                restaurants = json.getJSONArray(TAG_RESTAURANTS);

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

                    String id = c.getString(TAG_RESTAURANT_ID);
                    String name = c.getString(TAG_RESTAURANT_NAME);

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

                    map.put(TAG_RESTAURANT_ID, id);
                    map.put(TAG_RESTAURANT_NAME, name);

                    RestaurantList.add(map);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            progressDialog.dismiss();

            ListAdapter adapter = new SimpleAdapter(this, RestaurantList,
                    R.layout.itemlistrow,
                    new String[] { TAG_RESTAURANT_NAME }, new int[] {
                            R.id.RestaurantNameID });

            setListAdapter(adapter);


        }

    }

}

JSONObjParser.java

public class JSONObjParser {

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

    // constructor
    public JSONObjParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 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) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

itemlistrow.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content" 
    android:layout_width="fill_parent">


    <TextView
                android:id="@+id/RestaurantNameID"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="age" android:textStyle="bold"
                android:gravity="center"/>



</RelativeLayout>

编辑后

解决了一些错误,但仍然存在一些错误

Description Resource    Path    Location    Type
The method setListAdapter(ListAdapter) is undefined for the type MainActivity.ParsingAsync  MainActivity.java   /FindMyBuffet/src/com/project/findmybuffet  line 107    Java Problem

任何想法,

感谢

2 个答案:

答案 0 :(得分:0)

好的......如果您正确检索数据,请更改

ListAdapter adapter = new SimpleAdapter(this, RestaurantList,
                R.layout.itemlistrow,
                new String[] { TAG_RESTAURANT_NAME }, new int[] {
                        R.id.RestaurantNameID });
使用

在postExecute方法中

ListAdapter adapter = new SimpleAdapter(MainActivity.this, RestaurantList,
                R.layout.itemlistrow,
                new String[] { TAG_RESTAURANT_NAME }, new int[] {
                        R.id.RestaurantNameID });

也改变

setListAdapter(adapter);

setAdapter(adapter);

答案 1 :(得分:0)

在SimpleAdapter的构造函数中传递MainActivity.this而不是this

进行以下更改

 ListAdapter adapter = new SimpleAdapter(MainActivity.this, RestaurantList,
                R.layout.itemlistrow,
                new String[] { TAG_RESTAURANT_NAME }, new int[] {
                        R.id.RestaurantNameID });