旋转设备或重新打开APP而不注销时,Android会丢失内容

时间:2015-06-09 13:48:57

标签: java android arraylist android-recyclerview

我正在使用CardViews和RecyclerView创建项目列表。

当我旋转时,重新打开APP而不注销或重新创建内容丢失的活动。只有在您首次创建活动时(在APP中登录后)才会显示内容。

我不确定为什么会发生这种情况,我想知道是否有人可以帮助我。

我把代码放在这里:

MainActivity.java:

public class MainActivity extends AppCompatActivity {

    DrawerLayout drawerLayout;
    Toolbar toolbar;
    ActionBar actionBar;
    TextView textView;
    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_itemS = "items";
    private static final String TAG_item_ID = "item_id";
    private static final String TAG_NAME = "name";
    private static final String TAG_USERNAME = "username";
    private static final String TAG_PHOTO = "photo";

    List<item> items;

    JSONArray items = null;

    HashMap<String, String> user;

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

        items = new ArrayList<>();

        new LoadAllitems().execute();

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

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


        adapter = new itemAdapter(items);
        recycler.setAdapter(adapter);

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

        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);

        if (navigationView != null) {
            setupNavigationDrawerContent(navigationView);
            View header = (View)getLayoutInflater().inflate(R.layout.navigation_drawer_header, null);
            TextView navheaduser = (TextView) header.findViewById(R.id.usernameSession);
            navheaduser.setText("asdfa");
        }

        setupNavigationDrawerContent(navigationView);

        db = new SQLiteHandler(getApplicationContext());

        session = new SessionManager(getApplicationContext());

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

        user = db.getUserDetails();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_allitems, 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_allitems:
                                menuItem.setChecked(true);
                                drawerLayout.closeDrawer(GravityCompat.START);
                                intent = new Intent(MainActivity.this, MainActivity.class);
                                return true;
                            case R.id.item_navigation_drawer_myitems:
                                menuItem.setChecked(true);
                                drawerLayout.closeDrawer(GravityCompat.START);
                                intent = new Intent(MainActivity.this, Myitems.class);
                                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 LoadAllitems extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage(getResources().getString(R.string.loadingitems));
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All items from url
         */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            jParser = new JSONParser();
            JSONObject json = jParser.makeHttpRequest(AppConfig.URL_GET_ALL_itemS, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All items: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // items found
                    // Getting Array of items
                    items = json.getJSONArray(TAG_itemS);

                    // looping through All items
                    for (int i = 0; i < items.length(); i++) {
                        JSONObject c = items.getJSONObject(i);
                        items.add(new item(c.getInt(TAG_item_ID), getResources().getIdentifier(String.valueOf(LoadImageFromWebOperations(c.getString(TAG_PHOTO))), "drawable", getPackageName()), c.getString(TAG_NAME), c.getString(TAG_USERNAME)));
                    }
                    pDialog.dismiss();
                } else {
                    // no items found
                    pDialog.dismiss();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }
    }
}

itemAdapter.class:

public class itemAdapter extends RecyclerView.Adapter<itemAdapter.itemViewHolder> {
    private List<item> items;

    public static class itemViewHolder extends RecyclerView.ViewHolder {
        public ImageView image;
        public TextView name;
        public TextView userName;
        //public TextView description;
        public TextView username;

        public itemViewHolder(View v) {
            super(v);
            image = (ImageView) v.findViewById(R.id.itemImage);
            name = (TextView) v.findViewById(R.id.itemName);
            //userName = (TextView) v.findViewById(R.id.userName);
            //description = (TextView) v.findViewById(R.id.itemdescription);
            username = (TextView) v.findViewById(R.id.username);
        }
    }

    public itemAdapter(List items) {

        this.items = items;
    }

    @Override
    public int getItemCount() {

        return items.size();
    }

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

    @Override
    public void onBindViewHolder(itemViewHolder viewHolder, int i) {
        viewHolder.image.setImageResource(items.get(i).getImagen());
        viewHolder.name.setText(items.get(i).getName());
        viewHolder.username.setText(viewHolder.username.getText() + " " + String.valueOf(items.get(i).getUsernamer()));
    }
}

item.class:

public class item {
    private int item_id;
    private int image;
    private String name;
    private String username;
    private String description;

    public item(int item_id, int imagen, String name, String username) {
        this.item_id = item_id;
        this.image = imagen;
        this.name = name;
        this.username = username;
        this.description = description;
    }

    public int getitem_id() {
        return item_id;
    }

    public String getName() {

        return name;
    }

    public String getUsernamer() {

        return username;
    }

    public String getdescription() {
        return description;
    }

    public int getImagen() {

        return image;
    }
}

activity_main.xml中:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/navigation_drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="@bool/fitsSystemWindows">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="@dimen/status_bar_height"
            android:background="?colorPrimary"/>

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="@dimen/status_bar_height"
            android:background="?colorPrimaryDark"/>

    </LinearLayout>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/status_bar_height">

        <android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/recycler"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:padding="3dp"
            android:layout_marginTop="55dp"
            android:scrollbars="vertical" />

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?actionBarSize"
            android:background="?attr/colorPrimary"
            android:elevation="4dp"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:theme="@style/ToolbarTheme" />

    </FrameLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/navigation_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="@bool/fitsSystemWindows"
        app:headerLayout="@layout/navigation_drawer_header"
        app:menu="@menu/navigation_drawer_menu"
        app:theme="@style/NavigationViewTheme" />

</android.support.v4.widget.DrawerLayout>

item_card.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="150dp"
    card_view:cardCornerRadius="4dp"
    card_view:cardElevation="4dp"
    card_view:cardUseCompatPadding="true">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/itemImage"
            android:layout_width="100dp"
            android:layout_height="150dp"
            android:scaleType="centerCrop" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Large Text"
            android:id="@+id/itemName"
            android:textColor="#666"
            android:layout_toRightOf="@+id/itemImage"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="10dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="@string/userTag"
            android:id="@+id/username"
            android:textColor="#666"
            android:layout_below="@+id/itemName"
            android:layout_alignLeft="@+id/itemName" />
        <View
            android:layout_width="wrap_content"
            android:layout_height="1dp"
            android:background="#ffd5d5d5"
            android:id="@+id/linea"
            android:layout_toRightOf="@+id/itemImage">

        </View>


    </RelativeLayout>
</android.support.v7.widget.CardView>

任何人都可以帮助我吗?我正在搜索并尝试修复它,但我无法使其正常工作。

谢谢!

编辑:

我添加了这段代码,现在列表是加载器旋转重新创建活动,但列表重复添加自己。

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

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

2 个答案:

答案 0 :(得分:4)

Android每次旋转设备时都会重新创建布局。因此,如果 您希望用户能够旋转设备(方向更改) 覆盖Activity方法onSaveInstanceState并提供Bunde 提供您所需的所有信息。

更改方向后,将在

中提供此包
protected void onCreate(Bundle savedInstanceState)

这样您就可以重新创建视图和活动状态。

编辑:也不要忘记完成AsyncTask

编辑:我已经添加了一个小解释你需要做什么,但在此 我认为Google链接有效:Recreating an Activity

如上所述,每次更改设备的方向时,Android都会重新创建您的活动。因为布局需要重新填充等等。

  1. 在onCreate中初始化您的应用
  2. 在活动处于活动状态时执行您的活动逻辑
  3. 如果活动进入后台onSaveInstanceState,则称为
  4. 保存捆绑中所有您需要的信息(作为方法的争论)
  5. 重新创建您的活动
  6. 从提供给onCreate
  7. 的套装中提取您保存的信息

答案 1 :(得分:-1)

您可以使用@ JacksOnF1re解决方案或将其添加到您需要的活动中的清单中

android:configChanges="orientation|screenSize"

在您的情况下,不需要任何其他代码。