使用Asynctask解析JSON数据

时间:2013-11-14 04:52:50

标签: android json android-asynctask

我要解析从数据库中获取的JSON数据。我可以成功地获得它们,但我想让它们使用asynctask。但我对这个概念不熟悉。下面是我的代码,它有自定义适配器,因为解析后的数据将显示在listview中。

public class Favourites extends ListActivity {

    ProgressDialog pDialog;
    ListView lv;
    String data = "";
    ArrayList<String> arr;
    ArrayAdapter<String> adapter;


    ArrayList<String> useridarr;
    ArrayList<String> namearr;
    ArrayList<String> store_namearr;
    ArrayList<String> brand_namearr;
    ArrayList<String> pricearr;
    ArrayList<String> imagearr;
    ArrayList<String> addressarr;
    ArrayList<String> typearr;

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


         useridarr = new ArrayList<String>();
         namearr = new ArrayList<String>();
         store_namearr = new ArrayList<String>();
         brand_namearr = new ArrayList<String>();
         pricearr = new ArrayList<String>();
         imagearr = new ArrayList<String>();
         addressarr = new ArrayList<String>();
         typearr = new ArrayList<String>();


        // getting data from db     
        final GetDataFromDB getdb = new GetDataFromDB();
        new Thread(new Runnable() {
            public void run() {
                data = getdb.getDataFromDB("1");
                System.out.println(data);

                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        ArrayList<Users> users = parseJSON(data);
                        addData(users);                     
                    }
                });

            }
        }).start();

    }



     public ArrayList<Users> parseJSON(String result) {
            ArrayList<Users> users = new ArrayList<Users>();
            try {
                JSONArray jArray = new JSONArray(result);
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);
                    Users user = new Users();

                    user.setUser_id(json_data.getString("user_id"));
                    user.setName(json_data.getString("name"));
                    user.setStore_name(json_data.getString("store_name"));
                    user.setBrand_name(json_data.getString("brand_name"));
                    user.setPrice(json_data.getString("price"));
                    user.setPic(json_data.getString("pic"));
                    user.setAddress(json_data.getString("address"));
                    user.setType(json_data.getString("type"));
                    users.add(user);
                }
            } catch (JSONException e) {
                Log.e("log_tag", "Error parsing data " + e.toString());  
            }
            return users;
        }


     @SuppressWarnings({ "rawtypes" })
        public void addData(ArrayList<Users> users) {

            arr = new ArrayList<String>();
            for (Iterator i = users.iterator(); i.hasNext();) {

                Users p = (Users) i.next();

                useridarr.add(p.getUser_id());
                namearr.add(p.getName());
                store_namearr.add(p.getStore_name());
                brand_namearr.add(p.getBrand_name());
                pricearr.add(p.getPrice());
                imagearr.add(p.getPic());
                addressarr.add(p.getAddress());
                typearr.add(p.getType());

            }



            adapter = new CustomListFavourites(Favourites.this, useridarr, namearr, store_namearr, brand_namearr, pricearr, imagearr, addressarr, typearr);
            lv= getListView();
            lv.setAdapter(adapter);

      }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }



}

1 个答案:

答案 0 :(得分:1)

试试这种方式

使用asynctask而不是像这样的线程

public class Favourites extends ListActivity {

    ProgressDialog pDialog;
    ListView lv;
    String data = "";
    ArrayList<String> arr;
    ArrayAdapter<String> adapter;

    ArrayList<String> useridarr;
    ArrayList<String> namearr;
    ArrayList<String> store_namearr;
    ArrayList<String> brand_namearr;
    ArrayList<String> pricearr;
    ArrayList<String> imagearr;
    ArrayList<String> addressarr;
    ArrayList<String> typearr;

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

        useridarr = new ArrayList<String>();
        namearr = new ArrayList<String>();
        store_namearr = new ArrayList<String>();
        brand_namearr = new ArrayList<String>();
        pricearr = new ArrayList<String>();
        imagearr = new ArrayList<String>();
        addressarr = new ArrayList<String>();
        typearr = new ArrayList<String>();

        new AsyncTask<Void, Void, Void>() {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = ProgressDialog.show(Favourites.this, "Loading Data", "Please wait...");
            }

            @Override
            protected Void doInBackground(Void... params) {
                final GetDataFromDB getdb = new GetDataFromDB();
                data = getdb.getDataFromDB("1");
                ArrayList<Users> users = parseJSON(data);
                addData(users);

            }

            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
                            pDialog.dismiss();
                adapter = new CustomListFavourites(Favourites.this, useridarr, namearr, store_namearr, brand_namearr, pricearr, imagearr,
                        addressarr, typearr);
                lv = getListView();
                lv.setAdapter(adapter);

            }
        }.execute();

    }

    public ArrayList<Users> parseJSON(String result) {
        ArrayList<Users> users = new ArrayList<Users>();
        try {
            JSONArray jArray = new JSONArray(result);
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject json_data = jArray.getJSONObject(i);
                Users user = new Users();

                user.setUser_id(json_data.getString("user_id"));
                user.setName(json_data.getString("name"));
                user.setStore_name(json_data.getString("store_name"));
                user.setBrand_name(json_data.getString("brand_name"));
                user.setPrice(json_data.getString("price"));
                user.setPic(json_data.getString("pic"));
                user.setAddress(json_data.getString("address"));
                user.setType(json_data.getString("type"));
                users.add(user);
            }
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }
        return users;
    }

    @SuppressWarnings({ "rawtypes" })
    public void addData(ArrayList<Users> users) {

        arr = new ArrayList<String>();
        for (Iterator i = users.iterator(); i.hasNext();) {

            Users p = (Users) i.next();

            useridarr.add(p.getUser_id());
            namearr.add(p.getName());
            store_namearr.add(p.getStore_name());
            brand_namearr.add(p.getBrand_name());
            pricearr.add(p.getPrice());
            imagearr.add(p.getPic());
            addressarr.add(p.getAddress());
            typearr.add(p.getType());

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }

}