Hot questions for Using Android EditText in sharedpreferences

Top Java Programmings / Android EditText / sharedpreferences

Question:

I am using shared preferences but my code is not working. I don't know what's wrong with it. Am I implementing something wrong?

My main java activity(relevant bit of code) is:

public class MainActivity extends AppCompatActivity {
    private String s;
    public static final String subjectKey = "SubjectID";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    final SharedPreferences sharedPreferences = getSharedPreferences(subjectKey, Context.MODE_PRIVATE);

    TextView calc_monday = (TextView) findViewById(R.id.monday_calc);


    calc_monday.setOnClickListener(
            new Button.OnClickListener(){
                public void onClick(View v){



                    CustomDialogClass cdd = new CustomDialogClass(MainActivity.this);
                    cdd.show();
                    TextView text1 = (TextView) cdd.findViewById(R.id.Subject_ID);

                    String text = sharedPreferences.getString(subjectKey, " ");


                    if(text != " ")
                    {
                       text1.setText(text); /* Edit the value here*/
                    }

                    TextView text2 = (TextView) cdd.findViewById(R.id.Room_ID);
                    text2.setText("6 (SEECS)");
                    TextView text3 = (TextView) cdd.findViewById(R.id.Time_ID);
                    text3.setText("09:00am  - 09:50am");


                }
            }
    );

    calc_monday.setOnLongClickListener(
            new Button.OnLongClickListener() {
                public boolean onLongClick(View v) {

                    SettingDialogClass SDC = new SettingDialogClass(MainActivity.this);
                    SDC.show();

                    EditText texii = (EditText) SDC.findViewById(R.id.set_Subject_ID);






                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString(subjectKey, texii.getText().toString());
                    editor.apply();


                    return true;


                }
            }
    );

Basically I want that when I longClick a textbox (calc_monday), a dialog box should appear which appears. Now I should be able to write something on the EditText field which appears on this dialog box. Whatever I write should be stored and then displayed when I SINGLE CLICK on the same textbox (calc_monday)

Please see the 2 methods: onClick and onLongClick to understand.

The code is not working, i.e the text I write on EditText field on onLongCLick dialog box is not being displayed when I single click on the textbox.

What's wrong with the code


Answer:

When you long press calc_monday, it just show your custom dialog with empty value for EditText. To save your text when input in EditText, create a button in your custom dialog, and call onClickListener action for this button, then save value to SharePreferences.

calc_monday.setOnLongClickListener(
        new Button.OnLongClickListener() {
            public boolean onLongClick(View v) {

                SettingDialogClass SDC = new SettingDialogClass(MainActivity.this);

                EditText texii = (EditText) SDC.findViewById(R.id.set_Subject_ID);

                Button btnSave = (Button)SDC.findViewById(R.id.your_custom_button);
                btnSave.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putString(subjectKey, texii.getText().toString());
                        editor.apply();
                        SDC.dismiss();
                    }
                });

                SDC.show();

                return true;
            }
        }
);

Question:

First of all - I've already checked different tutorials, but wasn't able to complete my task :(

I'm calling Activity 2 from onAddEventClicked method in Activity 1 to open the layout and let the user type the name in EditText. Then I want to close Activity 2, send captured name back to Activity 1 and use it to set the name parameter when creating new event in ArrayList: event.setName(dataFromActivity2).

I'm able to save EditText's data to String dataFromActivity2, but how should I pass it from onAddEventClicked method back to onAddEventClicked method and set event.setName(dataFromActivity2) ?

Unfortunately I've tried so many times with no luck. Could you guide me with any hints / tips please? I know that the solution is probably simple, but I'm still a beginner... :( Should I use SharedPreferences insted of startActivityForResult?

ACTIVITY1 :

public class BaseActivity extends AppCompatActivity implements WeekView.EventClickListener, MonthLoader.MonthChangeListener, WeekView.EventLongPressListener, WeekView.EmptyViewLongPressListener, WeekView.EmptyViewClickListener, WeekView.AddEventClickListener {
private static final int TYPE_DAY_VIEW = 1;
private static final int TYPE_THREE_DAY_VIEW = 2;
private static final int TYPE_WEEK_VIEW = 3;
private int mWeekViewType = TYPE_THREE_DAY_VIEW;
private static final int REQUEST_CODE = 0;
String TAG = "***";
private WeekView mWeekView;
private ArrayList<WeekViewEvent> mNewEvents;
...

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
        String dataFromActivity2= data.getStringExtra("fav");
}


@Override
public void onAddEventClicked(Calendar startTime, Calendar endTime) {

Intent intent = new Intent(this, Test2.class);
startActivityForResult(intent, REQUEST_CODE);

WeekViewEvent event = new WeekViewEvent();
event.setId(7);
event.setName(fav);
event.setStartTime(startTime);
event.setEndTime(endTime);
event.setColor(getResources().getColor(R.color.event_color_03));

Log.d(TAG, "Intent test:" +fav);
mNewEvents.add(event);
mWeekView.notifyDatasetChanged();
}

...
}

ACTIVITY 2:

public class Test2 extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test);

    Button btn = (Button) findViewById(R.id.btn_test);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            EditText et = (EditText)findViewById(R.id.etv_test);
            String favourities=et.getText().toString();

            Intent intent=new Intent();
            intent.putExtra("fav", favourities);

            setResult(RESULT_OK,intent);
            finish();//finishing activity
            Toast.makeText(Test2.this, "INTENT CONTAINS:" + intent.getExtras(), Toast.LENGTH_SHORT).show();
        }});}}

Answer:

You should move your code for event creation into the onActivityResult method:

   private Calendar startTime, endTime;
   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
            String dataFromActivity2 = data.getStringExtra("fav");
            // create event here
            WeekViewEvent event = new WeekViewEvent();
            event.setId(7);
            event.setName(dataFromActivity2);
            event.setStartTime(startTime);
            event.setEndTime(endTime);
            event.setColor(getResources().getColor(R.color.event_color_03));

            Log.d(TAG, "Intent test:" + dataFromActivity2);
            mNewEvents.add(event);
            mWeekView.notifyDatasetChanged();
    }

In onAddEventClicked you have to save its parameters (startTime, endTime) to instance variables - to be able to use them in onActivityResult:

    @Override
    public void onAddEventClicked(Calendar startTime, Calendar endTime) {
        this.startTime = startTime;
        this.endTime = endTime;
        Intent intent = new Intent(this, Test2.class);
        startActivityForResult(intent, REQUEST_CODE);
    }

Question:

I am trying to save the data of my EditText topic automatically after it'S changed, but I get is this logcat

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference at com.example.barryblack.FragmentPage0.onCreateView(FragmentPage0.java:68)

So heres the code the problem is on

final SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(this.getActivity());

    topic = view.findViewById(R.id.topicText0);

    topic.setText(prefs.getString("autosave", ""));
    topic.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            prefs.edit().putString("autosave", s.toString()).apply();

        }
    });

And this is my whole code if needed(the loadData() and SaveDate() are a method i made to save ArarayList but has nothing to do with my problem)

package com.example.barryblack;



public class FragmentPage0 extends Fragment {

private ExampleAdapter mAdapter;
private EditText editTask;
private Button insertbtn;
private TextView taskText;

private String task;


Context context;
ArrayList<MyItem> items;


private static final String SHARED_PREFS_FRAGMENT_A = "fragmentA";

private EditText topic;


@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable 
ViewGroup container, @Nullable Bundle savedInstanceState) {


    CreateExampleList();


    View view = inflater.inflate(R.layout.page_fragment1, container, false);




    loadData();

    final SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(this.getActivity());

    topic = view.findViewById(R.id.topicText0);

    topic.setText(prefs.getString("autosave", ""));
    topic.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, 
int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int 
count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            prefs.edit().putString("autosave", s.toString()).apply();

        }
    });




    RecyclerView recyclerView = view.findViewById(R.id.listRecyclerView);
    recyclerView.setHasFixedSize(true);
    RecyclerView.LayoutManager layoutManager = new 
LinearLayoutManager(getActivity());
    new 
ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(recyclerView);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setItemViewCacheSize(500);
    mAdapter = new ExampleAdapter(items);
    recyclerView.setAdapter(mAdapter);


    taskText = view.findViewById(R.id.tv_country);
    insertbtn = view.findViewById(R.id.button_insert);
    editTask = view.findViewById(R.id.editTask);


    context = getActivity();


    insertbtn.setEnabled(false);
    editTask.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, 
int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int 
count) {

            String taskInput = editTask.getText().toString().trim();
            insertbtn.setEnabled(!taskInput.isEmpty());

        }

        @Override
        public void afterTextChanged(Editable s) {
            task = editTask.getText().toString().trim();

        }
    });


    insertbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            InsertItem();
            SaveData();
            editTask.setText(null);


        }
    });


    return view;
}


private void SaveData() {
    SharedPreferences sharedPreferences = 
this.getActivity().getSharedPreferences(SHARED_PREFS_FRAGMENT_A, 
MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    Gson gson = new Gson();
    String json = gson.toJson(items);
    editor.putString("task list", json);
    editor.apply();
}

private void loadData() {
    SharedPreferences sharedPreferences = 
this.getActivity().getSharedPreferences(SHARED_PREFS_FRAGMENT_A, 
MODE_PRIVATE);
    Gson gson = new Gson();
    String json = sharedPreferences.getString("task list", null);
    Type type = new TypeToken<ArrayList<MyItem>>() {
    }.getType();
    items = gson.fromJson(json, type);

    if (items == null) {
        items = new ArrayList();
    }

}

 public void InsertItem() {

    items.add(new MyItem(task));
    mAdapter.notifyItemInserted(items.size());
    SaveData();


}

private void CreateExampleList() {
    items = new ArrayList<MyItem>();
}


ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new 
ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | 
ItemTouchHelper.RIGHT) {
    @Override
    public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull 
RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) 
{
        return false;
    }

    @Override
    public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int 
direction) {
        items.remove(viewHolder.getAdapterPosition());
        mAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());
        SaveData();

    }
};

}

Answer:

Put these:

topic.setText(prefs.getString("autosave", ""));
topic.addTextChangedListener(new TextWatcher() {

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        prefs.edit().putString("autosave", s.toString()).apply();

    }
});

directly under this line:

topic = view.findViewById(R.id.topicText0);

Question:

I have an age input edit text which i want to put user's previous input there using shared preferences (for after first input). i have written following code but it force closes. what is the problem??

  @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

//setting text for editText
age_editText.setText(my_prefs.getInt("age_value", 0) + ""); //when i delete this part, it doesn't force close

btn_calculate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                try {
                    Int age_value = Integer.parseInt(age_editText.getText().toString());
                    //shared preferences
                    sharedPreferences my_prefs = getActivity().getPreferences(Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = my_prefs.edit();
                    editor.putInt("age_value", age_value);
                    editor_bmi.commit();

                } catch (Exception e) {
                    Toast.makeText(getContext(), getString(R.string.please_fill_all_inputs), Toast.LENGTH_LONG).show();
                }
        }
    });

Answer:

You need to use getSharedPreferences() in place of getPreferences() as shown below.

SharedPreferences sharedPreferences = getSharedPreferences("name", MODE_PRIVATE);

Note: getPreferences() and getSharedPreferences() are two different methods that return different Preference objects.