SharedPreferences会覆盖值

时间:2016-09-11 11:15:04

标签: android sharedpreferences spinner

我正在制作一个应用程序,当用户填写该文本并点击Spinner文本时,我会使用EditTextButtonButtonSpinner我的问题是我做了所有的事情,但当我将数据添加到Spinner时,它会覆盖以前的数据而之前的数据不会显示

public class MainActivity extends Activity {
    Spinner spinner1;
    Button add;
    EditText subject;
    ArrayAdapter btArrayAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        spinner1 = (Spinner) findViewById(R.id.spinner);
        ArrayAdapter dataAdapter = new ArrayAdapter(MainActivity.this,android.R.layout.simple_spinner_item, list);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner1.setAdapter(btArrayAdapter);
        add = (Button) findViewById(R.id.button);
        subject = (EditText) findViewById(R.id.editText);
        spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> adapter, View v,
                                       int position, long id) {
                String item = adapter.getItemAtPosition(position).toString();

                // Showing selected spinner item
                Toast.makeText(getApplicationContext(),
                        "Selected Subject : " + item, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {


            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SharedPreferences sharedPref =getSharedPreferences("Info", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString("Spinner_name",subject.getText().toString());
        editor.commit();
    }

    public void btnClick(View view)
    {
        String content;
        content = subject.getText().toString();
        btArrayAdapter.add(content);
         btArrayAdapter = new ArrayAdapter(MainActivity.this,android.R.layout.simple_spinner_item);
        btArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    }
}
  

java.lang.RuntimeException:无法实例化活动   ComponentInfo {com.example.helloworld / com.example.helloworld.MainActivity}:   显示java.lang.NullPointerException                                                                             在   android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)                                                                             在   android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)                                                                             在android.app.ActivityThread.access $ 600(ActivityThread.java:130)                                                                             在   android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1195)                                                                             在android.os.Handler.dispatchMessage(Handler.java:99)                                                                             在android.os.Looper.loop(Looper.java:137)                                                                             在android.app.ActivityThread.main(ActivityThread.java:4745)                                                                             at java.lang.reflect.Method.invokeNative(Native Method)                                                                             在java.lang.reflect.Method.invoke(Method.java:511)                                                                             在   com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:786)                                                                             在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)                                                                             at dalvik.system.NativeStart.main(Native Method)                                                                          引起:java.lang.NullPointerException                                                                             在   android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:153)                                                                             在com.example.helloworld.MainActivity。(MainActivity.java:30)                                                                             at java.lang.Class.newInstanceImpl(Native Method)                                                                             在java.lang.Class.newInstance(Class.java:1319)                                                                             在android.app.Instrumentation.newActivity(Instrumentation.java:1053)                                                                             在   android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)                                                                             在   android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)                                                                             在android.app.ActivityThread.access $ 600(ActivityThread.java:130)                                                                             在   android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1195)                                                                             在android.os.Handler.dispatchMessage(Handler.java:99)                                                                             在android.os.Looper.loop(Looper.java:137)                                                                             在android.app.ActivityThread.main(ActivityThread.java:4745)                                                                             at java.lang.reflect.Method.invokeNative(Native Method)                                                                             在java.lang.reflect.Method.invoke(Method.java:511)                                                                             在   com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:786)                                                                             在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)                                                                             在dalvik.system.NativeStart.main(本地方法)

2 个答案:

答案 0 :(得分:1)

editor.putString("Spinner_name",subject.getText().toString()); 

每次执行此操作时,旧字符串都会被覆盖。

首先,您应该将ArrayAdapter声明为类字段。然后在onClick()中,您需要将每个String添加到ArrayAdapter。最后在onDestroy()中,您可以将所有字符串保存到SharedPreferences。

btArrayAdapter.add(content);
btArrayAdapter = new ArrayAdapter(MainActivity.this,android.R.layout.simple_spinner_item);
btArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 

这里你正确地添加了字符串,然后你立即丢弃适配器并创建一个新的。不要这样做。您只应在onCreate()中初始化适配器一次。

editor.putString("Spinner_name",subject.getText().toString()); 

这只保存最近的字符串。它也会覆盖前一个。您需要从适配器获取所有字符串,然后将它们保存为字符串集。

答案 1 :(得分:0)

您可以通过保留单个Set<String>来实现该功能,并在按钮点击时更新它。此外,Code-Apprentice表示,您可以将onDestory格式保存在首选项import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class MainActivity extends Activity { /* Views */ Spinner spinner; Button add; EditText subject; /* Adapter */ ArrayAdapter<String> dataAdapter; ArrayList<String> list = new ArrayList<String>(); /* Preference */ SharedPreferences sharedPref; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /* initializing views */ spinner = (Spinner) findViewById(R.id.spinner); add = (Button) findViewById(R.id.button); subject = (EditText) findViewById(R.id.editText); /* Get spinner data from preference */ sharedPref = getSharedPreferences("Info", Context.MODE_PRIVATE); Set<String> savedStringSet = sharedPref.getStringSet("SpinnerData", null); if (savedStringSet != null) { list = new ArrayList<>(savedStringSet); } /* Setting up spinner */ dataAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, list.toArray(new String[list.size()])); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(dataAdapter); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapter, View v, int position, long id) { String item = adapter.getItemAtPosition(position).toString(); // Showing selected spinner item Toast.makeText(getApplicationContext(), "Selected Subject : " + item, Toast.LENGTH_LONG).show(); } @Override public void onNothingSelected(AdapterView<?> arg0) { } }); } @Override protected void onDestroy() { super.onDestroy(); /* save list in shared preference */ SharedPreferences.Editor editor = sharedPref.edit(); editor.putStringSet("SpinnerData", new HashSet<String>(list)); editor.apply(); } public void btnClick(View view) { String content = subject.getText().toString(); // get user entered text. /* update spinner */ list.add(content); // add to data list.. dataAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, list); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); /* set updated spinner */ spinner.setAdapter(dataAdapter); } } 内。

btnClick

注意:您可能需要在""方法内部进行一些验证,以便在您不想在{{1}上保存空字符串时编辑文字值按钮单击。