I have some buttons in my application, which open up a dialog when clicked on them.
In those dialogs a user can fill in his homework in an edittext.
Anyway i would like to save that user input, so that if I close the dialogs or the application I am able to recall that data and because I am new to eclipse and programming i don't know how to do it.
This is my MainActivity
public class MainActivity extends ActionBarActivity {
protected static final String TAG = null;
private Button bthomeWork;
private Button bthomeWork1;
private Button bthomeWork2;
private Button bthomeWork3;
private Button bthomeWork4;
private AlertDialog.Builder dialogbuilder;
private String strName="";
private void homeworkdialog(){
dialogbuilder = new AlertDialog.Builder(this);
final EditText txtinput = new EditText(this);
dialogbuilder.setTitle("Homework");
dialogbuilder.setMessage("Was sind deine Hausaufgaben?");
dialogbuilder.setView(txtinput);
dialogbuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#SuppressLint("ShowToast") #Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
strName+= txtinput;
Toast.makeText(getApplicationContext(), "Eingetragen", Toast.LENGTH_SHORT);
}
});
dialogbuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#SuppressLint("ShowToast") #Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Kein Eintrag", Toast.LENGTH_SHORT);
}
});
dialogbuilder.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
bthomeWork = (Button)findViewById(R.id.bthomeWork);
bthomeWork1= (Button)findViewById(R.id.bthomeWork1);
bthomeWork2= (Button)findViewById(R.id.bthomeWork2);
bthomeWork3= (Button)findViewById(R.id.bthomeWork3);
bthomeWork4= (Button)findViewById(R.id.bthomeWork4);
bthomeWork.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
homeworkdialog();
}
});
bthomeWork1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
homeworkdialog();
}
});
Hope you can help me:)
You can get the text and save the value of the editText into a String
String MyText = txtinput.getText().toString();
Then you can save the value either using sharedPreferences or into your Database depending on what you want to do
you can save the value in shared preferences like this
SharedPreferences sp = getSharedPreferences("key", 0);
SharedPreferences.Editor sedt = sp.edit();
sedt.putString("textvalue", txtInput.getText().toString());
sedt.commit();
Then you can retrieve the saved text in another activity or anywhere in your project like this
SharedPreferences sp = getSharedPreferences("key", 0);
String textValue = sp.getString("textvalue","");
for more information about using shared preferences check out this link http://www.tutorialspoint.com/android/android_shared_preferences.htm
And also note that sharedpreferences are stored as simple xml values...so anyone with a rooted android phone can easily have accesss to the saved value...so if you want to keep the data safe you can check out ways of keeping data safe in android programming http://www.androidsnippets.com/encryptdecrypt-strings
Related
I am making a game and want the load button to bring the player back into the game where it was saved using shared preferences. Is there perhaps something the load method is missing? The load method and button are in a different activity in the main menu but you can go back using the menu button
public static final String MY_PREFS = "prefs";
public static final String POSITION = "position";
public static final String INVENTORY = "inventory";
SharedPreferences sharedPrefs;
SaveButton = findViewById(R.id.SaveButton);
SaveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveData();
}
});
MenuButton = findViewById(R.id.MenuButton);
MenuButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
} // public void setupControls()
public void saveData() {
sharedPrefs = getSharedPreferences(MY_PREFS, MODE_PRIVATE);
SharedPreferences.Editor edit = sharedPrefs.edit();
edit.putInt(POSITION, thePlayer.getPlayerPos());
edit.putString(INVENTORY, thePlayer.getInventory());
edit.commit();
Toast.makeText(this, "Data Saved", Toast.LENGTH_SHORT).show();
}
//The code below here is in a different activity
loadGame_button = findViewById(R.id.loadGame_button);
loadGame_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadData();
}
});
public void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences(MY_PREFS, MODE_PRIVATE);
inv = sharedPreferences.getString(INVENTORY, "");
pos = sharedPreferences.getInt(POSITION, 0);
}
Try this: split your game into various states in draw(): mainmenu, game pausemenu, gameoverscreen. Set your load button in any state which isn't game, and make it so besides loading your info, will also switch the state to game.
I want to run another application whose package name is obtained from EditText in AlertDialog. My problem is that I want to display Dialog only when PackageName has not been specified in SharedPreference or when the application is not available.
Here is my code:
public static final String mypref="mypref";
public static final String packagename="text";
private SharedPreferences pref;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gpref();
Button b=(Button)findViewById(R.id.btn);
b.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View p1)
{
// TODO: Implement this method
String s=pref.getString(packagename);
if(s!=""){
Intent i=getPackageManager().getLaunchIntentForPackage(s);
if(i!=null){
startActivity(i);
} else{ sd();}
} else{
sd();
}
}
});
}
public void sd(){
final EditText et=new EditText(this);
AlertDialog ad=new AlertDialog.Builder(MainActivity.this).create();
ad.setView(et); ad.setButton(AlertDialog.BUTTON_POSITIVE,
"Set", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface p1, int p2)
{
// TODO: Implement this method
String s=et.getText().toString();
spref(s);
}
});
}
public void gpref(){
pref=getSharedPreferences(mypref,MODE_PRIVATE);
}
public void spref(String s){
gpref();
SharedPreferences.Editor spedit=pref.edit();
spedit.putString(packagename,s); spedit.apply();
}
but I did not find a way to ensure packagename at SharedPreference since packagename has not been set. Would anyone give me some ideas?
Please read official reference about getString
When specific preference does not set, the getString method would be return default value.
you could check against this default value.For example:
String s=pref.getString(packagename,"Default");
if(!s.equals("Default")){
//Do something
}
I want to change the background colour of an activity using AlertDialog. Here is what I have done:
private SharedPreferences prefs;
private static final String SELECTED_ITEM = "SelectedItem";
private Editor sharedPrefEditor;
btnchangeColor = (ImageButton) findViewById(R.id.btnchangeColor);
btnchangeColor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final CharSequence[] items={"Red","Green","Blue", "Yellow", "#EE82EE"};
AlertDialog.Builder builder = new AlertDialog.Builder(
ContentView_2.this);
builder.setTitle("Pick a Color");
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {}
});
builder.setSingleChoiceItems(items, getSelectedItem(), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
wvContent = (WebView) findViewById(R.id.wvContent);
//LinearLayout ll=(LinearLayout)findViewById(R.id.wvContent);
if("Red".equals(items[which]))
{
wvContent.setBackgroundColor(Color.RED);
}
else if("Green".equals(items[which]))
{
wvContent.setBackgroundColor(Color.GREEN);
}
else if("Blue".equals(items[which]))
{
wvContent.setBackgroundColor(Color.BLUE);
}
else if("Yellow".equals(items[which]))
{
wvContent.setBackgroundColor(Color.YELLOW);
}
else if("#EE82EE".equals(items[which]))
{
wvContent.setBackgroundColor(Color.rgb(184,184,184));
}
saveSelectedItem(which);
}
});
builder.show();
}});
}
private int getSelectedItem() {
if (prefs == null) {
prefs = PreferenceManager
.getDefaultSharedPreferences(this);
}
return prefs.getInt(SELECTED_ITEM, -1);
}
private void saveSelectedItem(int which) {
if (prefs == null) {
prefs = PreferenceManager
.getDefaultSharedPreferences(this);
}
sharedPrefEditor = prefs.edit();
sharedPrefEditor.putInt(SELECTED_ITEM, which);
sharedPrefEditor.commit();
}
I also add this code to OnCreate:
wvContent = (WebView) findViewById(R.id.wvContent);
wvContent.setBackgroundColor(getSelectedItem());
The colour is selected and the web view (wvContent) changes to chosen colour, BUT this is not saved to and/or loaded from Shared Preferences. It returns to its default colour when the activity is relaunched.
So the question is: How can properly I save the selected colour to SharedPreferences and load it when activity relaunches?
Many thanks for help.
Currently you are saving position of selected item instead of color code in SharedPreferences. do it as:
wvContent = (WebView) findViewById(R.id.wvContent);
int bg_color=Color.TRANSPARENT;
if("Red".equals(items[which]))
{
wvContent.setBackgroundColor(Color.RED);
bg_color=Color.RED;
}
else if("Green".equals(items[which]))
{
wvContent.setBackgroundColor(Color.GREEN);
bg_color=Color.GREEN;
}
........
// save color in SharedPreferences
saveSelectedItem(bg_color);
Now getSelectedItem() method return color code for previously selected value from spinner.
Alright I am comparing the text that the user has input to the edittext and comparing to the answer that is there in the String.xml. The code seems completely sounds and error-less but it doesn't work at all. Any help would be appreciated.
package com.example.italianapp;
public class Pictures<sButton> extends MainActivity
{
int level=0; // integer that will keep track of users progress
Button sButton; // represents the submit button
EditText mEdit; // text area where the user types answer
private SensorManager mSensorManager; // new sensor
private ShakeEventListener mSensorListener; // variable that listens for movement
// if the back button is pressed, return to easy menu
public void onBackPressed()
{
Intent backIntent = new Intent(Pictures.this, Learningmenu.class);
startActivity(backIntent);
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.words); // uses easy_mode1 xml
// shared preferences variable that will act as a holder of users progress
final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
AlertDialog.Builder hint = new AlertDialog.Builder(this); // hint alert dialog box
hint.setMessage("Would you like a hint?");
hint.setCancelable(false);
hint.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
// if user clicks yes, toast pops up providing a hint
public void onClick(DialogInterface dialog, int id)
{
Toast.makeText(Pictures.this, "You have two of these on your body", Toast.LENGTH_LONG).show();
}
});
hint.setNegativeButton("No", new DialogInterface.OnClickListener()
{
// if the user clicks no the level is loaded again
public void onClick(DialogInterface dialog, int id)
{
Intent intent = new Intent(Pictures.this, Pictures.class);
startActivity(intent);
dialog.cancel();
}
});
final AlertDialog hintAlert = hint.create();
hintAlert.setTitle("Hint");
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorListener = new ShakeEventListener();
mSensorListener.setOnShakeListener(new ShakeEventListener.OnShakeListener()
{
// when the user shakes the device, alert them if they want a hint
public void onShake()
{
hintAlert.show();
}
});
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
TextView plot; // text view which will hold the plot
plot = (TextView)findViewById(R.id.question1); // look for text called question1 in xml
plot.setMovementMethod(new ScrollingMovementMethod());
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this); // alert dialog box
alt_bld.setMessage("Correct! Proceed to next level?");
alt_bld.setCancelable(false);
alt_bld.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
// if user decides to continue to the next level, load the second easy level
public void onClick(DialogInterface dialog, int id)
{
Intent intent = new Intent(Pictures.this, Pictures.class);
startActivity(intent);
}
});
alt_bld.setNegativeButton("No", new DialogInterface.OnClickListener()
{
// if the user does not want to continue, load the easy mode levels
public void onClick(DialogInterface dialog, int id)
{
Intent intent = new Intent(Pictures.this, Pictures.class);
startActivity(intent);
dialog.cancel();
}
});
final AlertDialog alert = alt_bld.create();
alert.setTitle("Yes! Mano means Hand");
sButton = (Button)findViewById(R.id.ansSubmit1); // submit button will find ansSubmit button in xml
sButton.setOnClickListener(new View.OnClickListener()
{
// if the submit button is clicked check text entered to actual answer
public void onClick(View view)
{
mEdit = (EditText)findViewById(R.id.ansField1);
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
Context context = getApplicationContext();
String text = getResources().getString(R.string.answer1);
// if the text that was entered matches the answer, alert dialog box will appear
if(mEdit.getText().toString().replaceAll(" ", "").replaceAll("-", "").toLowerCase().equals(text))
{
int level = app_preferences.getInt("level", 0);
if (level > 0)
{
level=level-1;
}
level++;
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("level", level);
editor.commit();
MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.correct);
mediaPlayer.start();
alert.show();
}
else
{
// if the text that was entered does not match the answer, toast pop up = "Incorrect"
CharSequence message = "Incorrect!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, message, duration);
toast.show(); // show toast alert
v.vibrate(250); // vibrate device for 250ms
}
}
});
}
#Override
protected void onResume()
{
super.onResume();
mSensorManager.registerListener(mSensorListener,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
}
#Override
protected void onPause()
{
mSensorManager.unregisterListener(mSensorListener);
super.onStop();
}
}
public class Pictures<sButton> extends MainActivity
{
int level=0; // integer that will keep track of users progress
Button sButton; // represents the submit button
It appears your class is a Generic of type sButton - and sButton isn't a type.
I have a list of objects which need to persist should the user minimize the app. Is there any way to do this without using SharedPreferences or an SQLite database (seems like overkill for a single list)?
Have the object implement Parclable or Serializable
Then you can just put it in the Bundle
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(key, value);
}
And get it back in onCreate(),onRestoreInstanceState() depending on your needs.
Using a tutorial I found here, I implemented it using SharedPreferences, the main difference was that instead of using a key ,"MEM1", I use an Index. When my activity loads, I can check the size of the index using this code,
for(int x =0; ;x++) {
index = x;
if(sharedPreferences.contains(String.valueOf(x))){
temp = gson.fromJson(sharedPreferences.getString(String.valueOf(x), null), PointOfInterest.class);
pointList.add(temp);
}
else {
break;
}
}
Example:
public class AndroidSharedPreferencesEditor extends Activity {
EditText editText1, editText2;
TextView textSavedMem1, textSavedMem2;
Button buttonSaveMem1, buttonSaveMem2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textSavedMem1 = (TextView)findViewById(R.id.savedmem1);
textSavedMem2 = (TextView)findViewById(R.id.savedmem2);
editText1 = (EditText)findViewById(R.id.edittext1);
editText2 = (EditText)findViewById(R.id.edittext2);
buttonSaveMem1 = (Button)findViewById(R.id.save_mem1);
buttonSaveMem2 = (Button)findViewById(R.id.save_mem2);
buttonSaveMem1.setOnClickListener(buttonSaveMem1OnClickListener);
buttonSaveMem2.setOnClickListener(buttonSaveMem2OnClickListener);
LoadPreferences();
}
Button.OnClickListener buttonSaveMem1OnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SavePreferences("MEM1", editText1.getText().toString());
LoadPreferences();
}
};
Button.OnClickListener buttonSaveMem2OnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SavePreferences("MEM2", editText2.getText().toString());
LoadPreferences();
}
};
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedMem1 = sharedPreferences.getString("MEM1", "");
String strSavedMem2 = sharedPreferences.getString("MEM2", "");
textSavedMem1.setText(strSavedMem1);
textSavedMem2.setText(strSavedMem2);
}
}