I have a bundle passed from one activity to another. That contains String n (the length is max 30), String ID and String color. I need to save these values to an ArrayList as an array (n, ID, color) and then to save ArrayList to androids memory. I was looking for a best way of doing that.. I've tried database but its to complicated for me at the moment and I don't think I need such a complex thing. I've tried FileOutputStream (as it explained here: http://developer.android.com/guide/topics/data/data-storage.html#pref?) but it's not working for me, probably because I'm doing something wrong. Do I actually need to create an arraylist of arrays or may be i could use arraylist of bundles, or any other way..? Whats the best way...? Please help..
Thanks every one...Was trying all this time but no luck.. I'm posting the code hoping that someone could give me a hand on that:
public class MainActivity extends Activity
{
String gotNotes;
String n;
String gotDOW;
String gotID;
public String clrs;
public String id;
public String nts;
String gotHour;
String gotColor;
TextView notes;
public static String FILENAME = "allevents";
String[] newevent;
String[] events;
SharedPreferences sharedPref;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button settings = (Button)findViewById(R.id.settings);
Bundle gotPackage = getIntent().getExtras();
if (gotPackage != null){
gotNotes = gotPackage.getString("AddedNote");
if (gotNotes.equals(" "))
{
n = "Empty";
}
else
{
n = gotNotes;
}
//gotDOW = gotPackage.getString("Day");
//gotHour = gotPackage.getInt("Hour");
gotID = gotPackage.getString("ID");
gotColor = gotPackage.getString("color");
initialize();
}
else{}
settings.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent i = new Intent(v.getContext(),Settings.class);
startActivityForResult(i,0);
}
});
}
private void initialize()
{
// TODO Auto-generated method stub
String[] newevent = {n, gotID, gotColor};
ArrayList<String[]> events = new ArrayList<String[]>();
events.add(newevent);
SharedPreferences sharedPref = this.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = this.getPreferences(Activity.MODE_PRIVATE).edit();
editor.putString("yourKey", events.toString());
editor.commit();
String allData = sharedPref.getString("yourKey", null);
String[] playlists = allData.split(",");
/* for (int number=0;number<events.lastIndexOf(sharedPref);number++)
{
notes = (TextView)findViewById(getResources().getIdentifier(playlists[number], getString(0), allData));
notes.setText(number+1);
}*/
notes = (TextView)findViewById(getResources().getIdentifier(gotID, "id",getPackageName()));
notes.setText(n);
notes.setGravity(Gravity.CENTER_HORIZONTAL);
notes.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
if (gotColor.equals("Blue")){
notes.setBackgroundColor(Color.rgb(99, 184, 255));}else
if(gotColor.equals("Green")){
notes.setBackgroundColor(Color.rgb(189, 252, 201));}else
if(gotColor.equals("Yellow")){
notes.setBackgroundColor(Color.rgb(238, 233, 191));}else
if(gotColor.equals("Grey")){
notes.setBackgroundColor(Color.LTGRAY);}else
if(gotColor.equals("Aqua")){
notes.setBackgroundColor(Color.rgb(151, 255, 255));}else
if(gotColor.equals("White")){}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Simply use SharedPreferences to save your application's data.
SharedPreferences sharedPref = activity.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = activity.getPreferences(Activity.MODE_PRIVATE).edit();
editor.putString("yourKey", yourArray.toString());
editor.commit();
To get your array as String do the following:
String arrayString = sharedPref.getString("yourKey", null);
You can save array into shared preferences and retrieve it back. Here is a good example with fully functional code.
Related
I have two strings that I want to save them I wrote the code as shown below
public class MainActivity extends Activity {
Button result;
EditText b951, b9511, sum95, t95, p95
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LoadPreferences();
result = (Button)findViewById(R.id.btn1);
b951 = (EditText)findViewById(R.id.b951);
b9511 = (EditText)findViewById(R.id.b9511);
sum95 = (EditText)findViewById(R.id.sum95);
p95 = (EditText)findViewById(R.id.p95);
t95 = (EditText)findViewById(R.id.t95);
}
public void close (View v){
SavePreferences("p2b951", b951.getText().toString());
SavePreferences("p2b9511", b9511.getText().toString());
finish();
}
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String p1b951 = sharedPreferences.getString("p2b951", "1");
String p1b9511 = sharedPreferences.getString("p2b9511", "1");
b951.setText(p1b951);
b9511.setText(p1b9511);
}
public void result (View v) {
try {
int ib951 = Integer.parseInt(b951.getText().toString());
int ib9511 = Integer.parseInt(b9511.getText().toString());
int iisum95 = (ib9511-ib951);
sum95.setText(String.valueOf(iisum95));
int isum95 = Integer.parseInt(sum95.getText().toString());
int ip95 = Integer.parseInt(p95.getText().toString());
int pp95 = (isum95*ip95);
t95.setText(String.valueOf(pp95));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
But it seems there is a problem with this two lines:
b951.setText(p1b951);
b9511.setText(p1b9511);
I tried this
b951.setText(String.valueOf.p1b951);
b9511.setText(String.valueOf.p1b9511);
Also the problems still exist
When I open the application and when the loadpreferences is called the app will force close
The logcat show me that the error is with this two lines for sure it's just with the first line coz he didn't get the second but they are the same so they are wrong wroted
Any help??
Change onCreate() as follows:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
result = (Button)findViewById(R.id.btn1);
b951 = (EditText)findViewById(R.id.b951);
b9511 = (EditText)findViewById(R.id.b9511);
sum95 = (EditText)findViewById(R.id.sum95);
p95 = (EditText)findViewById(R.id.p95);
t95 = (EditText)findViewById(R.id.t95);
LoadPreferences();
}
This is because you are using the EditTexts in the LoadPreferences() without calling findViewById() on the EditTexts.
You can follow and help from like codes. such as
Setting values in Preference:
SharedPreferences.Editor editor = getSharedPreferences(MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.commit();
Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
}
it any confused about this then follow this link
I've been getting null returns from getting strings from my saved preferences. I'm not sure how savedpreferences worked but my understanding was that when call a sharedpreferences, it creates the keypair file on the phone so you can come back to it later.
My program is essentially a string creation application. When you press a button, it creates a string to send as an sms. My settings activity page has four edittexts that save whatever is inside them with a buttonclick and returns to the main activity. The final button creates a String by getting the value from the keyvalue pair and constructs the message. However, I've always gotten null for each of the values.
Heres the code for the settings page and then the main page. Please ask if I could add more, I didn't add ALL of the code, just the sharedpreferences portions.
public SharedPreferences sp;
public Editor e;
public void savethethings(){ //run this when enter is pressed/savew
EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);
String introstring = smsintro_hint.getText().toString();
String bodystring = smsbody_hint.getText().toString();
String checkboxbodystring = checkboxbody_hint.getText().toString();
String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();
e.putString("intro", introstring);
e.commit(); // you forgot to commit
if(!bodystring.isEmpty())
{
e.putString("body", bodystring);
e.commit();
}
if(!checkboxbodystring.isEmpty())
{
e.putString("checkbody", checkboxbodystring);
e.commit();
}
if(!checkboxdescriptionstring.isEmpty())
{
e.putString("checkboxdescr", checkboxdescriptionstring);
e.commit();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.settingmenu);
//SP
sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); // forget about
// named preferences - get the default ones and finish with it
e = sp.edit();
Button tt = (Button)findViewById(R.id.savebutton);
tt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
public void save(View view)
{
//THINGS HAPPEN HERE WITH SHARED PREFERENCES :(
savethethings();
this.finish();
return;
}
public String finishedtext(String userstring)
{
smsintroduction = (sp.getString("intro", ""));
smsbody = (sp.getString("body", ""));
checkboxtext = (sp.getString("checkbody", ""));
checkboxmessage = (sp.getString("checkboxdescr", ""));
if(smsintroduction.isEmpty())
{
if(smsbody.isEmpty())
{
if(checkboxtext.isEmpty())
{
if(checkboxmessage.isEmpty()) //topkek for most AND statements Ive ever put in in if/then form
{
//Essentially the DEFAULT if they're ALL null
smsbody = "Hi "+ userstring +"! This is coming from jake's phone and it wants to send a text so we can talk or whatever. ";
}
}
}
}
Toast.makeText( this, "Creating text, then press send!", Toast.LENGTH_LONG).show();
String thetext = "";
thetext = smsintroduction + " " + smsbody + " " + checkboxtext;
return thetext;
}
public void savethethings(){ //run this when enter is pressed/savew
EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);
String introstring = smsintro_hint.getText().toString();
String bodystring = smsbody_hint.getText().toString();
String checkboxbodystring = checkboxbody_hint.getText().toString();
String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();
// if(!introstring.isEmpty()) //if the fields are NOT empty, they should get saved.
// {
e.putString("intro", introstring);
e.commit(); // you forgot to commit
if(!bodystring.isEmpty())
{
e.putString("body", bodystring);
e.commit();
}
if(!checkboxbodystring.isEmpty())
{
e.putString("checkbody", checkboxbodystring);
e.commit();
}
if(!checkboxdescriptionstring.isEmpty())
{
e.putString("checkboxdescr", checkboxdescriptionstring);
e.commit();
}
}
Create java class named SessionManger and put all your methods for setting and getting SharedPreferences values. When you want to save value use the object of this class and set and get the values.
Sample code given below.
public class SessionManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences("name_that_you_use", PRIVATE_MODE);
editor = pref.edit();
editor.apply();
}
public void setIntroMessage(String data) {
editor.putString("intro", data);
editor.commit();
}
public String getIntroMessage() {
return pref.getString("intro", null);
}
}
I have more than 3 edittext. When i enter something inside edittext i need to save this to another screen. I referred some question got answer. But how to pass through array. I used separate putExtra method of each edittext and another screen i need to display one TextView. Now i created separate TextView for each.
code:
Activity:
et=(EditText)findViewById(R.id.et);
et1=(EditText)findViewById(R.id.et1);
btn=(Button)findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Save.this, Get.class);
String[] myStrings = new String[] {"et.getText().toString()", "et1.getText().toString()"};
intent.putExtra("strings", myStrings);
startActivity(intent);
SharedPreferences preferences = getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","test");
editor.commit();
}
});
Activity1:
Intent intent = getIntent();
String[] myStrings = intent.getStringArrayExtra("strings");
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name","");
txt=(TextView)findViewById(R.id.txt);
txt.setText(myStrings);
I'll write a complete answer.
Intent intent = new Intent(Save.this, Get.class);
String[] myStrings = new String[] { et.getText().toString() , et1.getText().toString() };
intent.putExtra("strings", myStrings);
startActivity(intent);
and then
Intent intent = getIntent();
String[] myStrings = intent.getStringArrayExtra("strings");
txt1=(TextView)findViewById(R.id.txt1);
txt1.setText(myStrings[0]);
txt2=(TextView)findViewById(R.id.txt2);
txt2.setText(myStrings[1]);
or you can just join the strings and pass it to a single TextView
Intent intent = getIntent();
String[] myStrings = intent.getStringArrayExtra("strings");
String joined = myStrings[0] + " - " + myStrings[1];
txt=(TextView)findViewById(R.id.txt);
txt.setText(joined);
Hope this will help.
Usually I write a class that will handle the SharedPrenferences with some static method, like:
public class Storage {
public static String getName(Context context) {
final SharedPreferences prefs = context.getSharedPreferences("com.my.package", Context.MODE_PRIVATE);
return prefs.getString("name", "");
}
public static void setName(Context context, String name) {
final SharedPreferences prefs = context.getSharedPreferences("it.enrichman.bolloauto", Context.MODE_PRIVATE);
prefs.edit().putString("name", name).commit();
}
}
You can try this storing it the first time in your first activity and then retrive it in the second one. Use a Toast to test.
This code is working properly.
scrollview=(ScrollView)findViewById(R.id.scrollview1);
tb2.setTextSize(30);
tb2.setMovementMethod(new ScrollingMovementMethod());
scrollview.post(new Runnable() {
public void run() {
scrollview.fullScroll(View.FOCUS_DOWN);
}
});
chat1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
{
textsaring1=edt1.getText().toString();
tb2.setText(tb2.getText()+" "+textsaring1);
edt1.setText(" ");
}
}
});
}
I need your help here..
I have the following code:
public class GameActivity extends Activity {
TextView test1;
String punkte, points;
#Override
public void onCreate(Bundle savedInstanceState) {
test1 = (TextView) findViewById(R.id.test1);
punkte = points;
SharedPreferences load = getSharedPreferences(punkte, 0);
points = load.getString("punkte", "0");
test1.setText(points);
}
public void mehrPunkte() {
punkte = "3";
SharedPreferences load = getSharedPreferences(punkte, 0);
points = load.getString("punkte", "0");
test1.setText(points);
SharedPreferences save = getSharedPreferences(punkte, 0);
save.edit().putString("punkte", punkte).commit();
}
But it still shows "0" if i restart the app.
What did I do wrong?
The first parameter of getSharedPreferences is its name, and you save it to a different shared preferences, indicated by the value of the punkte variable. Try this instead:
final private static String SHARED_PREF_ID = "My shared preferences";
#Override
public void onCreate(Bundle savedInstanceState) {
// ...
SharedPreferences load = getSharedPreferences(SHARED_PREF_ID, MODE_PRIVATE);
// ...
}
public void mehrPunkte() {
punkte = "3";
SharedPreferences load = getSharedPreferences(SHARED_PREF_ID, MODE_PRIVATE);
points = load.getString("punkte", "0");
test1.setText(points);
SharedPreferences save = getSharedPreferences(SHARED_PREF_ID, MODE_PRIVATE);
save.edit().putString("punkte", punkte).commit();
}
Also, use constants to indicate the mode, not integer literals (MODE_PRIVATE, not 0)
Put mehrPunkte(); in onCreate()
I am having a problem with my code here. I am using SharedPreferences in my code, and I am getting a NullPointerException at one line in the code. Here's the full code:
public class Exercise extends Activity {
String WEIGHT = "0";
String AGE = "0";
String FEET = "0";
String INCHES = "0";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.exercise);
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putInt(WEIGHT, 0);
prefsEditor.putInt(AGE, 0);
prefsEditor.putInt(FEET, 0);
prefsEditor.putInt(INCHES, 0);
prefsEditor.commit();
final EditText weightField = (EditText) findViewById(R.id.EditTextWeight);
try {
prefsEditor.putInt(WEIGHT, Integer.parseInt(weightField.getText().toString()));
prefsEditor.commit();
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
The NullPointerException appears at this line:
prefsEditor.putInt(WEIGHT, Integer.parseInt(weightField.getText().toString()));
Thanks!
EDIT: Here's the activity that calls setContentView(R.layout.main):
public class CalorieIntakeCalculator extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void next(View view) {
Intent intentExercise = new Intent(view.getContext(), Exercise.class);
startActivityForResult(intentExercise, 0);
}
}
When the "next" button is pushed in main.xml, it sends next which switches Activities from CalorieIntakeCalculator to Exercise.
Since you successfully used prefsEditor several times above that line, it seems like weightField must be null. Have you checked its value in the debugger?
EDIT: I also just noticed that you never assigned a value to WEIGHT, nor any of the other Strings for the SharedPreferences keys, so they are all null. You need to fix that.
String WEIGHT = "weight";
String AGE = "age";
String FEET = "feet";
String INCHES = "inches";
For the weight field, make sure there is an EditText in your exercise layout that has the id R.id.EditTextWeight