I have the following code but the application force closes before even opening. I have an EditText, a Button and a TextView. Clicking the Button should save the String from EditText to SharedPreference and the SharedPreference String should be displayed in the TextView. What am I doing wrong here.
package com.jainchiranjeev.arduinoremote.newcomponents;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText edittext;
Button confirm;
TextView text;
public static final String Name = "MyPrefs";
SharedPreferences.Editor editor = getSharedPreferences(Name, MODE_WORLD_WRITEABLE).edit();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
confirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
editor.putString("name", String.valueOf(edittext.getText()));
editor.commit();
}
});
SharedPreferences prefs = getSharedPreferences(Name, MODE_WORLD_READABLE);
String restoredText = prefs.getString("name","Your name appears here");
text.setText(restoredText);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
editor = getSharedPreferences(Name, MODE_WORLD_WRITEABLE).edit();line. to fix issue moveeditor = getSharedPreferences(Name, MODE_WORLD_WRITEABLE).edit();insideonCreatemethod