Im trying to make a simple program, that saves and retrieves string using SharedPreferences. App normally loads, but if i click button, app falls. I have no idea what is wrong.
Here is the code:
Shared.java
package com.example.sharedpreferences;
import android.content.Context;
import android.content.SharedPreferences;
public class Shared {
SharedPreferences prefe;
SharedPreferences.Editor editor;
Context mycontext;
public Shared(Context context){
mycontext = context;
prefe = mycontext.getSharedPreferences("Preference", 0);
editor = prefe.edit();
}
public void setpref(String name, String value){
editor.putString(name, value);
editor.commit();
}
public String getvalue(String name){
return prefe.getString(name, "Nothing!");
}
}
MainActivity.java
package com.example.sharedpreferences;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
Shared preferences;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences = new Shared(getApplicationContext());
}
public void btn_send(View button){
TextView name = (TextView)findViewById(R.id.name2);
TextView value = (TextView)findViewById(R.id.value2);
String names = (String) name.getText();
String values = (String) value.getText();
preferences.setpref(names, values);
}
public void btn_read(View button){
TextView name = (TextView)findViewById(R.id.name2);
TextView value = (TextView)findViewById(R.id.value2);
String names = (String) name.getText();
String values = preferences.getvalue(names);
value.setText(values);
}
}
Thanks!
It seems that the error is caused by your casting Char sequence to String. You may use
String superString = fromTextEdit.getText().toString();instead.