旋转时不会恢复Android RecyclerView

时间:2015-06-18 18:20:21

标签: java android rotation android-recyclerview android-cardview

当我旋转我的应用程序时,内容消失了,我有一个RecyclerView,其中有一个卡片列表,可以使用JSON和Web服务从外部数据库获取内容。我试图通过以下方式保存内容:

@Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if(items != null) {
            outState.putParcelableArrayList("ITEMS", items);
            items = null;
        }
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (items == null) {
            items = savedInstanceState.getParcelableArrayList("ITEMS");
            recycler.setAdapter(adapter);
        }
    }

但仍然会出现同样的问题。

我的MainActivity.java文件:

public class MainActivity extends AppCompatActivity {

    DrawerLayout drawerLayout;
    Toolbar toolbar;
    ActionBar actionBar;
    Intent intent;

    private SQLiteHandler db;
    private SessionManager session;

    private RecyclerView recycler;
    private RecyclerView.Adapter adapter;
    private RecyclerView.LayoutManager lManager;

    private ProgressDialog pDialog;

    JSONParser jParser;

    private static final String TAG_SUCCESS = "success";
    private static final String TAG_RECIPES = "recipes";
    private static final String TAG_RECIPE_ID = "recipe_id";
    private static final String TAG_NAME = "name";
    private static final String TAG_USERNAME = "username";
    private static final String TAG_PHOTO = "photo";

    ArrayList<Recipe> items;

    HashMap<String, String> user;

    String uns;

    TextView usernamesessionTV;

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

        //uns = session.getUsername();

        Intent i = getIntent();
        if (i.hasExtra("user")) {
            Bundle bd = getIntent().getExtras();
            if (!bd.getString("user").equals(null) || bd.getString("user").trim().length() > 0) {
                uns = bd.getString("user");
            }
        }

        usernamesessionTV = (TextView) findViewById(R.id.navigation_view).findViewById(R.id.usernameSession);

        items = new ArrayList<>();

        new LoadAllRecipes().execute();

        recycler = (RecyclerView) findViewById(R.id.recycler);
        recycler.setHasFixedSize(true);

        lManager = new LinearLayoutManager(this);
        recycler.setLayoutManager(lManager);


        adapter = new RecipeAdapter(this, items);
        recycler.setAdapter(adapter);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, NewRecipe.class);
                intent.putExtra("usersession", (String)uns);
                startActivity(intent);
            }
        });

        actionBar = getSupportActionBar();
        actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
        actionBar.setDisplayHomeAsUpEnabled(true);

        drawerLayout = (DrawerLayout) findViewById(R.id.navigation_drawer_layout);

        NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);

        TextView usersession = (TextView) findViewById(R.id.navigation_view).findViewById(R.id.usernameSession);
        usersession.setText(uns);


        if (navigationView != null) {
            setupNavigationDrawerContent(navigationView);
            View header = (View) getLayoutInflater().inflate(R.layout.navigation_drawer_header, null);
            usernamesessionTV.setText(uns);
        }

        setupNavigationDrawerContent(navigationView);

        adapter.notifyDataSetChanged();

        db = new SQLiteHandler(getApplicationContext());

        session = new SessionManager(getApplicationContext());

        if (!session.isLoggedIn()) {
            logoutUser();
        }

        user = db.getUserDetails();

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if(items != null) {
            outState.putParcelableArrayList("ITEMS", items);
            items = null;
        }
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (items == null) {
            items = savedInstanceState.getParcelableArrayList("ITEMS");
            recycler.setAdapter(adapter);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                drawerLayout.openDrawer(GravityCompat.START);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void setupNavigationDrawerContent(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {
                        switch (menuItem.getItemId()) {
                            case R.id.item_navigation_drawer_allrecipes:
                                menuItem.setChecked(true);
                                drawerLayout.closeDrawer(GravityCompat.START);
                                intent = new Intent(MainActivity.this, MainActivity.class);
                                intent.putExtra("usersession", (String)uns);
                                startActivity(intent);
                                return true;
                            case R.id.item_navigation_drawer_myrecipes:
                                menuItem.setChecked(true);
                                drawerLayout.closeDrawer(GravityCompat.START);
                                intent = new Intent(MainActivity.this, MyRecipes.class);
                                intent.putExtra("usersession", (String)uns);
                                startActivity(intent);
                                return true;
                            case R.id.item_navigation_drawer_logout:
                                menuItem.setChecked(true);
                                drawerLayout.closeDrawer(GravityCompat.START);
                                logoutUser();
                                return true;
                        }
                        return true;
                    }
                });
    }

    public static Drawable LoadImageFromWebOperations(String url) {
        try {
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable d = Drawable.createFromStream(is, "src name");
            return d;
        } catch (Exception e) {
            return null;
        }
    }

    private void logoutUser() {
        session.setLogin(false);

        db.deleteUsers();

        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    class LoadAllRecipes extends AsyncTask<String, String, String> {

        /**
         * Muestra Progress Dialog mientras carga.
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (pDialog != null) {
                pDialog = null;
            }
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage(getResources().getString(R.string.loadingRecipes));
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * Obtiene todas las recetas desde una URL
         */
        protected String doInBackground(String... args) {
            // Construye los parámetros a enviar
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            JSONArray recipes = new JSONArray();
            // Obtiene un JSON string desde la URL
            jParser = new JSONParser();
            JSONObject json = jParser.makeHttpRequest(AppConfig.URL_GET_ALL_RECIPES, "GET", params);

            Log.d("All recipes: ", json.toString());

            try {
                // Comprueba si devolvió SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // recetas encontradas
                    // Obtiene array de recetas
                    recipes = json.getJSONArray(TAG_RECIPES);

                    // recorre todas las recetas agregándolas al List
                    for (int i = 0; i < recipes.length(); i++) {
                        JSONObject c = recipes.getJSONObject(i);
                        items.add(new Recipe(c.getInt(TAG_RECIPE_ID), c.getString(TAG_PHOTO), c.getString(TAG_NAME), c.getString(TAG_USERNAME)));
                    }
                    pDialog.dismiss();
                } else {
                    // no se han encontrado recetas
                    Intent i = new Intent(getApplicationContext(), NewRecipe.class);
                    // Cierra todas las activities previas
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

    }
}

RecipeAdapter.java:

public class RecipeAdapter extends RecyclerView.Adapter<RecipeAdapter.RecipeViewHolder> {

    private ArrayList<Recipe> items;
    private static Context context;
    public View view;

    public static class RecipeViewHolder extends RecyclerView.ViewHolder {
        public int recipe_id;
        public ImageView image;
        public TextView name;
        public TextView userName;
        //public TextView method;
        public TextView username;
        public Recipe currentItem;

        public RecipeViewHolder(View v) {
            super(v);
            v.setOnClickListener(new View.OnClickListener() {
                @Override public void onClick(View v) {
                    Intent intent = new Intent(context, RecipeActivity.class);
                    intent.putExtra("recipe_id", currentItem.getRecipe_id());
                    context.startActivity(intent);
                }
            });
            image = (ImageView) v.findViewById(R.id.recipeImage);
            name = (TextView) v.findViewById(R.id.recipeName);
            //userName = (TextView) v.findViewById(R.id.userName);
            //method = (TextView) v.findViewById(R.id.recipeMethod);
            username = (TextView) v.findViewById(R.id.username);
        }

        /*@Override
        public void onClick(AdapterViewCompat<?> parent, View view, int position, long id) {
            Intent intent = new Intent(context, RecipeActivity.class);
            context.startActivity(intent);
        }*/

    }

    public RecipeAdapter(Context context, ArrayList<Recipe> items) {
        this.context = context;
        this.items = items;
    }

    private String[] mDataset;

    public RecipeAdapter(String[] dataset) {
        mDataset = dataset;
    }


    public interface OnItemClickListener {
        public void onItemClick(View view , int position);
    }

    @Override
    public RecipeViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recipe_card, viewGroup, false);
        RecipeViewHolder vh = new RecipeViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(RecipeViewHolder viewHolder, int i) {
        viewHolder.recipe_id = items.get(i).getRecipe_id();
        //viewHolder.image.setImageResource(items.get(i).getImage());
        new DownloadImageTask((ImageView) viewHolder.image).execute(items.get(i).getImage());
        viewHolder.name.setText(items.get(i).getName());
        viewHolder.username.setText(context.getResources().getString(R.string.userTag)+" "+String.valueOf(items.get(i).getUsername()));
        viewHolder.currentItem = items.get(i);
    }

    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap imageBM = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                imageBM = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return imageBM;
        }

        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
        }
    }

    @Override
    public int getItemCount() {

        return items.size();
    }
}


Recipe.java:

public class Recipe implements Parcelable {
    private int recipe_id;
    private String image;
    private String name;
    private String username;
    private String method;

    public Recipe(int recipe_id, String imagen, String name, String username) {
        this.recipe_id = recipe_id;
        this.image = imagen;
        this.name = name;
        this.username = username;
        this.method = method;
    }

    public int getRecipe_id() {

        return recipe_id;
    }

    public String getName() {

        return name;
    }

    public String getUsername() {

        return username;
    }

    public String getMethod() {
        return method;
    }

    public String getImage() {

        return image;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(name);
        parcel.writeString(method);
        parcel.writeString(username);
        parcel.writeString(image);
    }
}

0 个答案:

没有答案