Faiz Mir Faiz Mir - 1 year ago 70
Android Question

SharedPrefrences overwite value

I am making an application in which i am using a

Spinner
,
EditText
and a
Button
when user fill that text and click that
Button
the text will be shown in
Spinner
and my problem is i do all the stuff but when i add the data to
Spinner
it override the previous data and the previous data wont showed up
Any help would be appreciated

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: Unable to instantiate activity ComponentInfo{com.example.helloworld/com.example.helloworld.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:153)
at com.example.helloworld.MainActivity.(MainActivity.java:30)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1319)
at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 
at android.app.ActivityThread.access$600(ActivityThread.java:130) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4745) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
at dalvik.system.NativeStart.main(Native Method) 

Answer Source

You can achieve the functionality by keeping single ArrayAdapter and update it on button click. Also as Code-Apprentice said you can save the data in form of Set<String> inside preference 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);
    }
}

Note: You might need to put some validations, inside btnClick method, for edit text values in case you don't want to save empty string on "" button click.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download