简体   繁体   English

共享首选项仅适用于首次应用重启。 在重新启动应用程序第二次卡视图标题不保留

[英]Shared preferences working only for the first app restart. On restarting the app second time card view titles are not retained

I have created an app which adds cards and a title is set on each card after taking a name input from user.我创建了一个添加卡片的应用程序,并在从用户输入名称后在每张卡片上设置了一个标题。 In order to retain the cards and the title during app restart I am using sharedpreferences and saving the individual card titles in an array.为了在应用程序重新启动期间保留卡片和标题,我使用 sharedpreferences 并将各个卡片标题保存在一个数组中。 The issue is after first app restart the card titles are retained but on further app restart the card titles are not retained.问题是在第一次重新启动应用程序后,卡片标题被保留,但在进一步的应用程序重新启动时,卡片标题不会保留。 Although the number of cards are still retained.虽然卡数仍然保留。

    public class MainActivity extends AppCompatActivity { 

        private CardView cardview;
        private CardView cardview2;
        private LinearLayout.LayoutParams layoutparams1;
        private LinearLayout layout;
        public SharedPreferences mSettings;
        int mCount;
        int i=0,j=0;
        public TextView tv1;
        public TextView tv4;
        public TextView tv3;
        String name;
        String names[] = new String[10];
        String key[] = {"A","B","C","D","F","G","H"};

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

            Button b1 = findViewById(R.id.button);
            layout=findViewById(R.id.view);
            tv1 = findViewById(R.id.textView);

            b1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    names[mCount] = tv1.getText().toString().trim();
                    mCount++;
                    saveName();
                }
            });
        }

       private void saveName()    //Cardview-1 function to 
        {
            cardview = new CardView(getApplicationContext());
            layoutparams1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            layoutparams1.setMargins(18, 30, 18, 0);
            cardview.setLayoutParams(layoutparams1);
            cardview.setCardBackgroundColor(Color.WHITE);
            cardview.setMinimumHeight(400);

            tv3 = new TextView(getApplicationContext());
            tv3.setText(tv1.getText().toString().trim());

            cardview.setRadius(30);
            cardview.addView(tv3);
            layout.addView(cardview);
        }

        private void saveName2()  //Cardview 2 function
        {
            cardview2 = new CardView(getApplicationContext());
            layoutparams1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            layoutparams1.setMargins(18, 30, 18, 0);
            cardview2.setLayoutParams(layoutparams1);
            cardview2.setCardBackgroundColor(Color.WHITE);
            cardview2.setMinimumHeight(400);
            tv4 = new TextView(getApplicationContext());

            mSettings = getSharedPreferences("APP_PREFERENCES", Context.MODE_PRIVATE);
            name = mSettings.getString(key[j],"");
            tv4.setText(name);
            j++;

            cardview2.setRadius(30);
            cardview2.addView(tv4);
            layout.addView(cardview2);
        }

        @Override
        public void onPause() {
            super.onPause();
            mSettings = getSharedPreferences("APP_PREFERENCES", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = mSettings.edit();
            editor.putInt("COUNT_CARDS", mCount);
            for(int i=0; i<mCount; i++)
            editor.putString(key[i],names[i]);
            editor.commit();
        }

        @Override
        public void onResume() {
            super.onResume();
            mSettings = getSharedPreferences("APP_PREFERENCES", Context.MODE_PRIVATE);
            if(mSettings.contains("COUNT_CARDS"))
            {
                mCount = mSettings.getInt("COUNT_CARDS", 0);
                for (int i=0; i<mCount; i++)
                    saveName2();
            }
        }
    }

XML File XML 文件

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:id="@+id/layout"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save"
        android:id="@+id/button"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/view"
        android:orientation="vertical"
        android:layout_marginTop="200dp"
        android:background="@color/cardview_dark_background">

    </LinearLayout>

    <EditText
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="40dp" />

</RelativeLayout>

There is no need to store every card in onPause() method.无需将每张卡片存储在 onPause() 方法中。 We will only write new card in sharedPref as prev cards are already presen in sharedPref.我们只会在 sharedPref 中写入新卡,因为 prev 卡已经存在于 sharedPref 中。 So when you are trying to save the prev cards in the loop, there is a problem.( writing blank value).因此,当您尝试将 prev 卡保存在循环中时,就会出现问题。(写入空白值)。

public class MainActivity extends AppCompatActivity {

    private CardView cardview;
    private CardView cardview2;
    private LinearLayout.LayoutParams layoutparams1;
    private LinearLayout layout;
    public SharedPreferences mSettings;
    int mCount;
    int i=0,j=0;
    public TextView tv1;
    public TextView tv4;
    public TextView tv3;
    String name;
    String names[] = new String[10];
    String key[] = {"A","B","C","D","F","G","H"};

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

        Button b1 = findViewById(R.id.button);
        layout=findViewById(R.id.view);
        tv1 = findViewById(R.id.textView);

        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                names[mCount] = tv1.getText().toString().trim();
                mCount++;
                saveName();
            }
        });
    }

    private void saveName()    //Cardview-1 function to
    {
        cardview = new CardView(getApplicationContext());
        layoutparams1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutparams1.setMargins(18, 30, 18, 0);
        cardview.setLayoutParams(layoutparams1);
        cardview.setCardBackgroundColor(Color.WHITE);
        cardview.setMinimumHeight(400);

        tv3 = new TextView(getApplicationContext());
        tv3.setText(tv1.getText().toString().trim());

        cardview.setRadius(30);
        cardview.addView(tv3);
        layout.addView(cardview);

        saveInPref();
    }

    private void saveInPref() {
        mSettings = getSharedPreferences("APP_PREFERENCES", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = mSettings.edit();
        editor.putInt("COUNT_CARDS", mCount);
        editor.putString(key[mCount-1],names[mCount-1]);
        editor.apply();
    }

    private void saveName2()  //Cardview 2 function
    {
        cardview2 = new CardView(getApplicationContext());
        layoutparams1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutparams1.setMargins(18, 30, 18, 0);
        cardview2.setLayoutParams(layoutparams1);
        cardview2.setCardBackgroundColor(Color.WHITE);
        cardview2.setMinimumHeight(400);
        tv4 = new TextView(getApplicationContext());

        mSettings = getSharedPreferences("APP_PREFERENCES", Context.MODE_PRIVATE);
        name = mSettings.getString(key[j],"");
        tv4.setText(name);
        j++;

        cardview2.setRadius(30);
        cardview2.addView(tv4);
        layout.addView(cardview2);
    }


    @Override
    public void onResume() {
        super.onResume();
        mSettings = getSharedPreferences("APP_PREFERENCES", Context.MODE_PRIVATE);
        if(mSettings.contains("COUNT_CARDS"))
        {
            mCount = mSettings.getInt("COUNT_CARDS", 0);
            for (int i=0; i<mCount; i++)
                saveName2();
        }
    }
}

So when you click on the SAVE button then only you can save card in SharedPref.因此,当您单击“保存”按钮时,只有您可以将卡片保存在 SharedPref 中。 This will save in unnecessary write operation on sharedPref.这将节省对 sharedPref 的不必要的写入操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM