Save text/string internally Android [duplicate] - java

This question already has answers here:
Read/Write String from/to a File in Android
(11 answers)
Closed 4 years ago.
In this app, I want to save the text that ends up on the TextView view and be able to see it the next time I launch the app. I'm relatively new to Android Studio. How can I do this?
My code:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
Button submit;
EditText habbit;
EditText money;
TextView view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submit = (Button) findViewById(R.id.button2);
habbit = (EditText) findViewById(R.id.habbit1);
money = (EditText)findViewById(R.id.money1);
view = (TextView)findViewById(R.id.textView3);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
view.setText((habbit.getText().toString() + " for $" + money.getText().toString()) + "/day");
}
});
}}

You can use shared preferences to save the text in a file. And when app is open again you can retrieve the text from file and put in a textView.
public class MainActivity extends AppCompatActivity {
SharedPreferences preferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences=getSharedPreferences("File_name",MODE_PRIVATE);
editor=preferences.edit();
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
view.setText((habbit.getText().toString() + " for $" + money.getText().toString()) + "/day");
editor.putString("key",habbit.getText().toString());
editor.commit();
}
});
}
And then you can retrieve data as -
public class MainActivity extends AppCompatActivity {
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences=getSharedPreferences("File_name",MODE_PRIVATE);
String data = preferences.getString("key", "");
view = (TextView)findViewById(R.id.textView3);
view.setText(data);
}
}

You can use shared preferences to store a simple string.
static final String MY_PREF = "MY_PREF";
static final String SAVE_TEXT = "SAVE_TEXT";
SharedPreferences sharedPreferences = context.getSharedPreferences(MY_PREF, Context.MODE_PRIVATE);
//To store string use this line
sharedPreferences.edit().putString(SAVE_TEXT, textview.getText().toString()).commit();
//To retrieve the same use this line
sharedPreferences.getString(SAVE_TEXT, "default_value");

Related

How to save the state of a radio group?

I want the user to have the same radio button checked which he had
previously checked before the app was closed.
This is my source code
package com.example.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.myapplication.R;
public class MainActivity extends AppCompatActivity {
RadioGroup radioGroup;
RadioButton radioButton;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup = findViewById(R.id.radioGroup);
textView = findViewById(R.id.text_view_selected);
Button buttonApply = findViewById(R.id.button_apply);
buttonApply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int radioId = radioGroup.getCheckedRadioButtonId();
radioButton = findViewById(radioId);
textView.setText("Your choice: " + radioButton.getText());
}
});
}
public void checkButton(View v) {
int radioId = radioGroup.getCheckedRadioButtonId();
radioButton = findViewById(radioId);
Toast.makeText(this, "Selected Radio Button: " + radioButton.getText(),
Toast.LENGTH_SHORT).show();
}
}
I want the radio button states to be saved for next time the app is
used.
You should take a look at sharedPreferences : https://developer.android.com/training/data-storage/shared-preferences
Save your data :
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("myRadio", radioButton.getText());
editor.commit();
Retrieve data :
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String defaultValue = "";
String radioButtonText = sharedPref.getString("myRadio", defaultValue);
For now, you can do this :
public class MainActivity extends AppCompatActivity {
RadioGroup radioGroup;
RadioButton radioButton;
TextView textView;
// Declare SharedPreferences as attributes
private SharedPreferences sharedPref;
private SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup = findViewById(R.id.radioGroup);
textView = findViewById(R.id.text_view_selected);
// Retrieve SharedPreferences
sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
editor = sharedPref.edit();
Button buttonApply = findViewById(R.id.button_apply);
buttonApply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int radioId = radioGroup.getCheckedRadioButtonId();
radioButton = findViewById(radioId);
textView.setText("Your choice: " + radioButton.getText());
}
});
}
#Override
protected void onResume() {
int radioIdChecked = -1;
radioIdChecked = sharedPref.getInt("myRadioChecked", radioIdChecked);
if (radioIdChecked == -1) {
// ERROR, don't check anything
Log.d("TAG", "error: don't check anything");
}
else {
RadioButton radioButton = radioGroup.findViewById(radioIdChecked);
if (radioButton != null) {
radioButton.setChecked(true);
}
}
}
#Override
protected void onPause() {
editor.putInt("myRadioChecked", radioGroup.getCheckedRadioButtonId());
editor.commit();
}
Best

SharedPreferences in Android Studio Clicker App Not Working

I am creating a simple clicker program. I am clicking a pear picture and then it increments by 1 and displays that. I want to save this number so I they can click and then completely exit the app and when they return the same number they left off at is still there. This is my code but yet it still does not save that pears int when I restart the app.
CODE:
package pearclicker.pearclicker;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
ImageButton imageButtonPear;
TextView showValue;
int pears;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showValue = (TextView) findViewById(R.id.countText);
}
public void PearIncrease(View v) {
SharedPreferences pref = getApplicationContext().getSharedPreferences("PearCount", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("pearCount", pears);
pears++;
if (pears == 1) {
showValue.setText(pears + " pear");
editor.putInt("pearCount", pears);
editor.apply();
}
else {
showValue.setText(pears + " pears");
editor.putInt("pearCount", pears);
editor.apply();
}
}
}
Your code is doing fine when clicking the button to increase the value of your pear. but you're doing nothing in your onCreate() so you think that the SharedPreference is not storing the value of pear when you restart the app..
to do that you need some modification to your code.
public class MainActivity extends AppCompatActivity {
ImageButton imageButtonPear;
TextView showValue;
int pears = 0;
SharedPreferences pref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = getApplicationContext().getSharedPreferences("PearCount", MODE_PRIVATE);
showValue = (TextView) findViewById(R.id.countText);
pears = pref.getInt("pearCount", 0); // This will get the value of your pearCount, It will return Zero if its empty or null.
showValue.setText(pears + " pears");
}
public void PearIncrease(View v) {
editor = pref.edit();
pears++;
showValue.setText(pears + " pears");
editor.putInt("pearCount", pears);
editor.apply();
}
}

Android Edittext Sharedpreferences

Can someone please help me edit the following code so that it saves the info typed into the edittext and then once the app is relaunched it will automatically display the text that was saved in the edittext field. I have tried SharedPreferences tutorials but so far I have not been able to get it working.
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText txtLink;
Button btnOpenLink;
String defaultLink;
String secondLink;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
defaultLink = "http://";
secondLink = ".whatver.com";
txtLink = (EditText) findViewById(R.id.editText);
btnOpenLink = (Button) findViewById(R.id.button);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
btnOpenLink.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String server = txtLink.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, server);
editor.commit();
if(!TextUtils.isEmpty(server)){
Intent intent=new Intent(MainActivity.this,webactivity.class);
intent.setData(Uri.parse(defaultLink+server+secondLink));
startActivity(intent);
}else{
Toast.makeText(MainActivity.this, "Please enter your server name.", Toast.LENGTH_LONG).show();
}
}
});
}
}
Verify the stored preferences and load them if any avaliable, after that display them in the textview
Example:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
defaultLink = "http://";
secondLink = ".whatver.com";
txtLink = (EditText) findViewById(R.id.editText);
btnOpenLink = (Button) findViewById(R.id.button);
checkIfPreferencesAvaliable();
if(defaultLink!=null && secondLink!=null){
txtLink.setText(defaultLink+secondLink);
}
defaultLink = "http://";
secondLink = ".whatver.com";
void checkIfPreferencesAvaliable(){
SharedPreferences preferences = getPreferences(Activity.MODE_PRIVATE);
defaultLink = preferences.getStr("mydefaultLink", null);
secondLink = preferences.getStr("mysecondLink", null);
}
In your onCreate(), check if you have already have values in your preferences-
String savedVal = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE).getString(Name, null);
if(savedVal == null){ //This means you don't have the saved values in your prefs file
//Do whatever you want to
} else{
//Use "savedVal" anyway you want
}
I fixed it by calling this
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
txtLink.setText(sharedpreferences.getString(Name, ""));

Android Activities startactivity [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Android - How to open Activity by clicking button
i want to open another Activity(GameProcess) from this one (KlikomaniaActivity) through button, but when i tap the button the program crashes. i don't a proffesional android programmer, please say what mistakes i have:
packagecom.makeandroid.klikomania;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class KlikomaniaActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button Butstart = (Button)findViewById(R.id.butstart);
final Button Butrez = (Button)findViewById(R.id.butrez);
Butstart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent("com.makeandroid.klikomania.GameProcess");
// эапускаем деятельнсть
startService(intent);
}
});
}
}
and here GameProcess Acticity:
public class GameProcess extends KlikomaniaActivity {
private static int rezult = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameprocess);
final Button Butklik = (Button)findViewById(R.id.klik);
final TextView TextTime = (TextView)findViewById(R.id.texttime);
final TextView TextKolvo = (TextView)findViewById(R.id.kolvo);
Butklik.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
rezult=rezult+1;
TextKolvo.setText(rezult);
}
});
}
}
First make sure that you added your activity to the manifest file :
<activity android:name="com.makeandroid.klikomania.GameProcess"></activity>
second, to start the activity use this code:
final Intent gameProcessIntent= new Intent(this, GameProcess.class);
Butstart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(gameProcessIntent);
}
});
this should work normaly

Access Shared Preferences Across Activities

I have a SharedPreference in this .java File; towards the bottom you can see I save the values to the SharedPreferences GB_PREFERENCES_BENCH, and GB_PREFERENCES_FLIES. How do I use these values in another activity? See the second code example for how I want to use it.
package com.creativecoders.gymbuddy;
import com.creativecoders.gymbuddy.R;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
public class Benchmark extends Activity {
public static final String GB_PREFERENCES = "Prefs";
public static final String GB_PREFERENCES_BENCH = "Bench";
public static final String GB_PREFERENCES_FLIES = "Flies";
SharedPreferences gBValues;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_benchmark);
gBValues = getSharedPreferences(GB_PREFERENCES, Context.MODE_PRIVATE);
}
public void onStart() {
super.onStart();
findViewById(R.id.button5).setOnClickListener(new handleButton5());
}
class handleButton5 implements OnClickListener {
public void onClick(View v) {
EditText editText1 = (EditText)findViewById(R.id.editText1);
String sWeight = editText1.getText().toString();
final double dWeight = Double.parseDouble(sWeight);
EditText editText2 = (EditText)findViewById(R.id.editText2);
String sPush = editText2.getText().toString();
final double dPush = Double.parseDouble(sPush);
EditText editText3 = (EditText)findViewById(R.id.editText3);
String sSit = editText3.getText().toString();
final double dSit = Double.parseDouble(sSit);
EditText editText4 = (EditText)findViewById(R.id.editText4);
String sPull = editText4.getText().toString();
final double dPull = Double.parseDouble(sPull);
double dBench = (((Math.floor(dWeight*.0664))*10)-10)+dPush;
double dFlies = (Math.floor(((Math.floor(dBench*.6)/10)*10)));
int iBench = (int)dBench;
int iFlies = (int)dFlies;
Editor editor1 = gBValues.edit();
editor1.putInt(GB_PREFERENCES_BENCH, iBench);
editor1.commit();
Editor editor2 = gBValues.edit();
editor2.putInt(GB_PREFERENCES_FLIES, iFlies);
editor2.commit();
}
}
}
Here is how I want to use it; (specifically in the on create method to set a TextView's text to the value in the SharePreference)
package com.creativecoders.gymbuddy;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class Upper100Start extends Activity {
public static final String GB_PREFERENCES = "Prefs";
public static final String GB_PREFERENCES_CURLS = "Curls";
SharedPreferences gBValues;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upper100start);
if (gBValues.contains(GB_PREFERENCES_CURLS)){
TextView TextView2 = (TextView)findViewById(R.id.textView2);
TextView2.setText(gBValues.getString(GB_PREFERENCES_CURLS, ""));
}
}
public void onStart() {
super.onStart();
findViewById(R.id.button2).setOnClickListener(new handleButton2());
findViewById(R.id.button3).setOnClickListener(new handleButton3());
}
class handleButton2 implements OnClickListener {
public void onClick(View v) {
Intent intent = new Intent(Upper100Start.this, Upper101.class);
startActivity(intent);
}
}
class handleButton3 implements OnClickListener {
public void onClick(View v) {
Intent intent = new Intent(Upper100Start.this, Main.class);
startActivity(intent);
}
}
}
The shared preferences are accessible throughout your application, so you can read them from any activity in the application.
Storing a key/value pair in activity A:
SharedPreferences settings = getSharedPreferences("mysettings",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("mystring", "wahay");
editor.commit();
Reading this value from another activity:
SharedPreferences settings = getSharedPreferences("mysettings",
Context.MODE_PRIVATE);
String myString = settings.getString("mystring", "defaultvalue");
You can find more information at http://developer.android.com/guide/topics/data/data-storage.html#pref

Categories

Resources