I want to make an app that basically the user inputs some strings inside a
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColorHint="#ffffff"
app:errorEnabled="true">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/texto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#4249ff"
android:hint="@string/BtnO"
android:textColor="#ffffff" />
</com.google.android.material.textfield.TextInputLayout>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="confirmInput"
android:text="@string/Btns" />
</LinearLayout>
So when the user presses the confirm button I want it to be saved but the app crashes instead its the first time I'm using shared preferences and I don't really understand it.I doesn't save the value the user.Also I know I have used hint but with my shared preferences it changes the hint into a text instead of it staying like that. Here is my java code:
public class MainActivity extends AppCompatActivity {
private EditText nameInput;
private EditText homeInput;
private SharedPreferences prefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences prefs= getSharedPreferences("my_data",MODE_PRIVATE);
String name = prefs.getString("MY_NAME","name");
String home = prefs.getString("MY_HOME","home");
((EditText)findViewById(R.id.texto)).setText(name);
((EditText)findViewById(R.id.textd)).setText(home);
nameInput =(EditText)findViewById(R.id.texto);
nameInput =(EditText)findViewById(R.id.textd);
}
public void copy(View view) {
}
public void confirmInput(View view) {
String name=nameInput.getText().toString();
SharedPreferences.Editor editor = prefs.edit();
editor.putString("MY_NAME",name);
editor.apply();
}
public void confirmInput2(View view) {
String home=homeInput.getText().toString();
SharedPreferences.Editor editor=prefs.edit();
editor.putString("MY_HOME",home);
editor.apply();
}
}