使用AsyncTask传递可序列化对象

时间:2012-08-15 22:10:53

标签: java android

所以我使用JSONObject解析JSON Parser,并使用AsyncTask将数据放入多个对象中。我的问题是:我如何通过所有这些对象?它们都是Serializable,我读过你可以创建Intent并使用Intent方法将对象放入putExtras;但是,当我这样做时,我收到一个错误。

另外,为了创建所有对象,我在原始构造函数中使用构造函数调用每个不同对象的构造函数。所以我可以调用一个构造函数,该构造函数使用第一个构造函数中的方法调用其他构造函数。我知道这听起来有点令人困惑,但最终解析器创建了8个不同的对象,我想传递给下一个活动。

我愿意接受有关如何执行此操作的任何建议。

编辑:我不想使用Parcelable这对于我想要做的事情来说复杂得多,我并不担心速度,因为我的档案很小。

@Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.main);

        checkWifiConnection(menuUrl);

    }




    class LoadJSON extends AsyncTask<String, Void, Restaurant>{

        @Override
        protected Restaurant doInBackground(String... params) {
            JSONObject jo=null;
            Restaurant rest = null;

            try {

                Log.i(TAG, "Running background thread"); 
                URL mURL = new URL(menuUrl);
                Log.i(TAG, mURL + ": menuUrl"); 
                URLConnection uc = mURL.openConnection();


                JsonParser parser = new JsonParser(); 

                try {
                    jo = parser.getJson(getApplicationContext(), uc);
                    rest = new Restaurant(jo); <<-- Start the parsing using this constructor, which calls the other objects constructors
                } catch (IOException e) {

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



            } catch (MalformedURLException e) {

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

                e.printStackTrace();
            } 
            return rest;
        }

        @Override
        protected void onPostExecute(Restaurant rest){

            ImageButton ib = (ImageButton)findViewById(R.id.continuebutton); 
            ib.setVisibility(View.VISIBLE); 
            ib.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    Intent homeIntent = new Intent(MainActivity.this, HomeActivity.class); 
                    homeIntent.putExtra("Restaurant", rest); //<< get an error here
                    startActivity(homeIntent); 


                }
            }); 

        }

以下是Restaurant类:

package com.uie.menu.app;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

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

import android.util.Log;

public class Restaurant implements Serializable {

    private final static String TAG = Restaurant.class.getSimpleName();

    String name;
    String category;
    String created_at;
    String updated_at;
    private List<Menu> menuList;
    private List<SideDishes> sideDishes;
    private List<Drinks> drinks; 
    private List<Ingredients> ingredients; 
    private List<DrinkCategories> drinkCategories; 

    private Restaurant() {
        menuList = new ArrayList<Menu>();
        sideDishes = new ArrayList<SideDishes>();
        drinks = new ArrayList<Drinks>();
        ingredients = new ArrayList<Ingredients>(); 
        drinkCategories = new ArrayList<DrinkCategories>(); 
    }

    public Restaurant(JSONObject jo) throws JSONException {

        this();

        if (jo != null) {

            this.name = jo.optString("name");
            Log.i(TAG, name + " : Restaurant 'name'");
            this.category = jo.optString("category");
            Log.i(TAG, category + " : Restaurant category");
            this.created_at = jo.optString("created_at");
            Log.i(TAG, created_at + " : Restaurant 'created at'");
            this.updated_at = jo.optString("updated_at");
            Log.i(TAG, updated_at + " : Restaurant 'updated_at'");

            addMenus(jo);
            addMenuSides(jo); 
            addMenuDrinks(jo); 
            addMenuIngredients(jo); 
            addDrinkCategories(jo); 

        }

    }

    private void addMenus(JSONObject jo) throws JSONException {
        JSONArray menus = jo.optJSONArray("menus");

        if (menus != null) {
            for (int ii = 0; menus != null && ii < menus.length(); ii++) {
                JSONObject menu = menus.optJSONObject(ii);
                Log.d(TAG,  "==Adding Restaurant Menu==");
                addMenu(new Menu(menu));
            }
            Log.d(TAG, "==Done adding Restaurant Menu==");
        }
    }

    private void addMenu(Menu menu) {
        menuList.add(menu);
    }

    private void addMenuSides(JSONObject jo) throws JSONException{
        JSONArray sides = jo.optJSONArray("side_dishes");

        if (sides != null) {
            for (int ii = 0; sides != null && ii < sides.length(); ii++) {
                JSONObject side = sides.optJSONObject(ii);
                Log.d(TAG,  "==Adding Restaurant Side Dish==");
                addSide(new SideDishes(side));
            }
            Log.d(TAG, "==Done adding Restaurant Side Dishes==");
        }
    }

    private void addSide(SideDishes side){
        sideDishes.add(side); 
    }

    private void addMenuDrinks(JSONObject jo) throws JSONException{
        JSONArray drinks = jo.optJSONArray("drinks");

        if (drinks != null) {
            for (int ii = 0; drinks != null && ii < drinks.length(); ii++) {
                JSONObject drink = drinks.optJSONObject(ii);
                Log.d(TAG,  "==Adding Restaurant Drinks==");
                addDrink(new Drinks(drink));
            }
            Log.d(TAG, "==Done adding Restaurant Drinks==");
        }
    }

    private void addDrink(Drinks drink){
        drinks.add(drink); 
    }

    private void addMenuIngredients(JSONObject jo){
        JSONArray ingredients = jo.optJSONArray("ingredients");

        if (ingredients != null) {
            Log.d(TAG,  "==Adding Restaurant Ingredient==");
            for (int ii = 0; ingredients != null && ii < ingredients.length(); ii++) {
                JSONObject ingredient = ingredients.optJSONObject(ii);

                addIngredient(new Ingredients(ingredient));
            }
            Log.d(TAG, "==Done adding Restaurant Ingredients==");
        }
    }

    private void addIngredient(Ingredients ingredient){
        ingredients.add(ingredient); 
    }

    private void addDrinkCategories(JSONObject jo) throws JSONException{
        JSONArray drinkCategories = jo.optJSONArray("drink_categories");

        if (drinkCategories != null) {
            Log.d(TAG,  "==Adding Restaurant Drink Categories==");
            for (int ii = 0; drinkCategories != null && ii < drinkCategories.length(); ii++) {
                JSONObject drinkCategory = drinkCategories.optJSONObject(ii);

                addCategory(new DrinkCategories(drinkCategory));
            }
            Log.d(TAG, "==Done adding Restaurant Drink Categories==");
        }
    }

    private void addCategory(DrinkCategories drinkCategory){
        drinkCategories.add(drinkCategory); 
    }
}

我得到的错误是:Cannot refer to a non-final variable rest inside an inner class defined in a different method

2 个答案:

答案 0 :(得分:0)

餐厅应该实现Parcelable,这是将对象从Intent传递给另一个活动的最佳方式。

修改:您可能会在以后遇到另一个与您相关的序列化餐厅内的列表。它解释了here

答案 1 :(得分:0)

尝试在LoadJSON的类范围中声明您的rest对象,而不是在doInBackground方法中。 e.g。

class LoadJSON extends AsyncTask<String, Void, Restaurant>{
    Restaurant rest = null;

    private void doInBackground(...) {
       ...
    }
}