I have an app where I take the Name of the user in an editText and I have it storing to firebase but when I get out of the activity and go back into it, the editText field does not show the Name of the user anymore. I want their name to stay in the editText field.
also how would I do the same thing but for an image in an ImageView that the user puts in. Please help.
IDEA:
You can use shared preference. When user launches his application first task will be load his user name and password from shared preference.
By doing this you can also manage a session manager for better user experience.
For example: After every successful authentication you can store the basic information of the user that is needed to update the screen everytime.
Benefit:
This will help you to show old data on screen if user launches your app without internet enabled. You can check the internet and if disabled then simply show the old data from preference.
You Can do something like this
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
text.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count)
{
prefs.edit().putString("autoSave", s.toString()).commit();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after)
{
}
#Override
public void afterTextChanged(Editable s)
{
//At here you can call some method to get the text from shared preferences and display it on EDitText
}
or You can save into DB at onTextChanged() method
Here is a little activity example which saves the username into SharedPreferences at stop of activity and restores the value to the EditText when activity is (re)started:
public class Test extends Activity {
EditText edtUser;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
edtUser = (EditText) findViewById(R.id.editTextUser);
edtUser.setText(preferences.getString("username", ""));
}
#Override
protected void onStop() {
super.onStop();
preferences.edit().putString("username", edtUser.getText().toString()).commit();
}
}
Set on click listener to edit text.
Inside on click enable edit text and write to firebase using setValue.
Set on click to parent layout or check is focus changed of edit text. Inside read from firebase using add value event listener.
In Oncreate disable edit text and read from firebase using add value event listener.
This will auto save and retrieve edit text data seamlessly.
In OnCreate create method of activity
//Initialize edittext
mEditText = (EditText) findViewById(R.id.edittext);
// Disable mEditText
mEditText.setEnabled(false);
//Read from firebase and set text to mEditText if mTextEdit is not in focus
if (!mEditText.isFocused()){
mFirebaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String editTextData = (String) dataSnapshot.getValue();
mEditText.setText(editTextData);
}
#Override
public void onCancelled(FirebaseError firebaseError) {}
});
}
// Set onclick listener to mEditText
mEditText.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mEditText.setEnabled(true);
editTextData = mEditText.getText().toString();
mFirebaseRef.setValue(editTextData);
}
});
This works for me and UI looks simple without any extra buttons to switch between edit and save.
Hope I understood your requirement correctly. Thanks
Related
I'm new to JAVA and Android. Previously, I was working on Javascript & Jquery.
As in HTML using Javascript (or Jquery) we can add custom data attribute to any element. for example-
$("#element").data("customdata", "customvalue");
And later I can get the value by doing-
var customvalue = $("#element").data("customdata");
Is there any method available in Android to achieve this type of thing?
Like, if I need to set multiple type of strings to a single TextView and later get them as needed.
Thank you all in advance.
You can get your textview from XML and set text on it . Something like this
TextView textView = findViewById(R.id.textview_id);
textView.setText("Your awesome text");
// Later fetch the text details back
String textDetails = textView.getText().toString();
This is a basic code sample of how to add and retrieve text from the text-view. Hope this help your case
You can use the View's setTag() and getTag() for that purpose.
However, most of the time there are cleaner ways like using ViewModel architecture etc. but that is a different story.
I saw your link. I think you can use AlertDialog.
this is my code.I think you would need it.
public class MainActivity extends AppCompatActivity {
EditText e1;
TextView t4;
Buttob btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t4=(TextView)findViewById(R.id.t4);
t4.setOnClickListener(t4click);
e1=(EditText)findViewById(R.id.e1);
btn=(Button)findViewById(R.id.btn);
btn.setOnClickListener(btnlogin);
}
private Button.OnClickListener btnlogin=new Button.OnClickListener(){
//click button
public void onClick(View v){
String account=e1.getText().toString();//get edittext value
String tmp="";
tmp=t4.getText().toString()+account; //get textview value and add
edittext string
t4.setText(tmp);//insert new value
}
}
};
private TextView.OnClickListener t4click=new TextView.OnClickListener(){
#Override
//if click textview it,would show dialog
//if your dialog value is from edittext ,you can reuse it.
public void onClick(View view) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("product")
.setMessage("item:pen"+"\nid=A001"+"\nprice:10 USD")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i)
{
}
})
.show();
}
};
}
I have a problem that should remember-save the text from the TextView that the user inputs through his voice, but I have enabled the Night mode, at the time when the day mode passes into the night mode, the text entered at that moment disappears. I know that it needs to be SharedPreferences, I tried this code, but I can not record anything. I emphasize that there is no Save button. It is necessary to return the text already entered when refreshing the Activity. I ask for help please
/*...*/{
//...
myText = (TextView) findViewById(R.id.textView);
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (!TextUtils.isEmpty(restoredText)) {
myText.setText(restoredText);
}
//...
}
public void loadData() {
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("text", myText.getText().toString());
editor.commit();
}
It sounds like your activity is getting killed. If this is the case, then you should implement the android activity lifecycle methods onSaveInstanceState and onRestoreInstanceState.
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(bundle);
state.putString("text", myText.getText().toString());
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
myText.setText(savedInstanceState.getString("text"));
}
EDIT: After adding onPause() and onResume(), the app no longer crashes; however, the instance is still not saving, and I lose the text I put inside the EditText. I speculate that I'm supposed to save the instance using onPause(), onStop(), and recall it using onResume() (or maybe using this and onSaveInstanceState(), onRestoreInstanceState() together) - I'm reading up on how to use these three methods now, and I would appreciate any pointers.
I'm currently writing a simple Android App with only a four (maybe five) activities. The app's function is to provide help and advice to students in university, where they are required to add the courses themselves (which appear on the activity_main_page page as buttons) - when the button is pressed, it will take the student to the advice page.
What I'm currently working on is the course adding page: activity_add_course. I'm trying to add a way to save the state of the EditText's text (this is where the user adds the course name) when the activity is paused/stopped (for example when user presses the back button or home button), and to have it recalled when the user returns to the page.
The app worked fine (using dummy intents to connect activities - I havent added an SQL database to actually make the app work) before I tried adding instance state saving to the App. Now that I have added instance state saving and recalling, the app stops running when I click the back button and I have no idea why? or how to fix it? - This issue has been solved. Thanks #peresisUser
This is the code for the back button
btBk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent New = new Intent(AddCourse.this, MainPage.class);
startActivity(New);
}
});
}
And these are the codes I use for instance save and restore.
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
//Save instance state
savedInstanceState.putString("edC1", edCourse1.getText()+"");
savedInstanceState.putString("edC2", edCourse2.getText()+"");
savedInstanceState.putString("edC3", edCourse3.getText()+"");
savedInstanceState.putString("edC4", edCourse4.getText()+"");
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//Restore instance state
String edC1 = savedInstanceState.getString("edC1");
edCourse1.setText(edC1+"");
String edC2 = savedInstanceState.getString("edC2");
edCourse2.setText(edC2+"");
String edC3 = savedInstanceState.getString("edC3");
edCourse3.setText(edC3+"");
String edC4 = savedInstanceState.getString("edC4");
edCourse4.setText(edC4+"");
}
edCourse1-4 are all different EditTexts.
From my understanding, the onSaveInstanceState() will save edC1 as the text from edCourse1.getText()+"" and so on, then the onRestoreInstanceState() will restore the String inside edC1 to edCourse1 and so on.
Having trouble on this, I have no idea how I would solve my next issue, which has to save the state of buttons on the page activity_main_page. Here I would have 10 buttons which start off as invisible and nameless, where activity_add_course will add a name to the button and make it visible. I speculate that the issue I will run into is: that all the buttons would become invisible when the app is restarted.
It looks to me that your should just add the super call in onPause() which is probably deleted in your code.
First row of the stack trace:
android.util.SuperNotCalledException: Activity {com.example.user.icecres/com.example.user.icecres.AddCourse} did not call through to super.onPause()
Let me know if that helped.
So I've figured out how to do all of this, next task: doing the same thing for buttons!
Feel free to add/edit anything appropriate to this answer.
This is my final source code:
package com.example.user.icecres;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.view.View;
public class AddCourse extends AppCompatActivity {
private EditText edCourse1, edCourse2, edCourse3,edCourse4;
private Button btConfirm, btReset, btBk;
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.activity_add_course);
if(state != null){
//restore state onStop()
SharedPreferences pText = getSharedPreferences(PREFS_NAME,0);
String edC1 = pText.getString("edC1", "");
String edC2 = pText.getString("edC2", "");
String edC3 = pText.getString("edC3", "");
String edC4 = pText.getString("edC4", "");
edCourse1.setText(edC1);
edCourse2.setText(edC2);
edCourse3.setText(edC3);
edCourse4.setText(edC4);
} else {
btConfirm = (Button) findViewById(R.id.btConfirm);
btReset = (Button) findViewById(R.id.btReset);
edCourse1 = (EditText) findViewById(R.id.edCourse1);
edCourse2 = (EditText) findViewById(R.id.edCourse2);
edCourse3 = (EditText) findViewById(R.id.edCourse3);
edCourse4 = (EditText) findViewById(R.id.edCourse4);
btBk = (Button) findViewById(R.id.btBk);
}
btConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// add course to database
edCourse1.setText("");
edCourse2.setText("");
edCourse3.setText("");
edCourse4.setText("");
AlertDialog.Builder d = new AlertDialog.Builder(
AddCourse.this);
d.setTitle("Success");
d.setMessage("Courses have been added");
d.setPositiveButton("OK", null);
}
});
btReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder c = new AlertDialog.Builder(
AddCourse.this);
c.setTitle("Confirmation");
c.setMessage("Would you like to clear all fields?");
c.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
edCourse1.setText("");
edCourse2.setText("");
edCourse3.setText("");
edCourse4.setText("");
}
});
c.setNegativeButton("NO",null);
c.show();
}
});
btBk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent New = new Intent(AddCourse.this, MainPage.class);
startActivity(New);
}
});
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences pText = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor edit = pText.edit();
edit.putString("edC1",edCourse1.getText()+"");
edit.putString("edC2",edCourse2.getText()+"");
edit.putString("edC3",edCourse3.getText()+"");
edit.putString("edC4",edCourse4.getText()+"");
edit.commit();
}
#Override
protected void onStop() {
super.onStop();
SharedPreferences pText = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor edit = pText.edit();
edit.putString("edC1",edCourse1.getText()+"");
edit.putString("edC2",edCourse2.getText()+"");
edit.putString("edC3",edCourse3.getText()+"");
edit.putString("edC4",edCourse4.getText()+"");
edit.commit();
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences pText = getSharedPreferences(PREFS_NAME,0);
String edC1 = pText.getString("edC1", "");
String edC2 = pText.getString("edC2", "");
String edC3 = pText.getString("edC3", "");
String edC4 = pText.getString("edC4", "");
edCourse1.setText(edC1);
edCourse2.setText(edC2);
edCourse3.setText(edC3);
edCourse4.setText(edC4);
}
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
//Save instance state
state.putString("edC1", edCourse1.getText()+"");
state.putString("edC2", edCourse2.getText()+"");
state.putString("edC3", edCourse3.getText()+"");
state.putString("edC4", edCourse4.getText()+"");
}
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
//Restore instance state on crash
String edC1 = state.getString("edC1","");
String edC2 = state.getString("edC2","");
String edC3 = state.getString("edC3","");
String edC4 = state.getString("edC4","");
edCourse2.setText(edC2+"");
edCourse3.setText(edC3+"");
edCourse1.setText(edC1+"");
edCourse4.setText(edC4+"");
}
}
So the onPause() and onStop() are used to save the text inside the EditText fields to the file initialized at the top. The onResume() is used to call the texts saved and apply them to the relevant EditText fields. The onSaveInstanceState() is used to save the state and onRestoreInstanceState() is used to restore the state on crash. The if else in the onCreate(), is used to determine if there was a previous state to be restored or not (by onStop), and the values are called/initialised depending on this condition.
Hope this helps someone with similar problems!
I need to stored my listview that i create dynamically by a "add" button. Of course right now if i go out of application the items disappears. I tryied in this way but something's wrong
public class MainActivity extends Activity{
private EditText etInput;
private Button btnAdd;
private ListView lvItem;
private ArrayList<String> itemArrey;
private ArrayAdapter<String> itemAdapter;
/* Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setUpView();
// Eliminare un elemento al longClick con dialog di conferma
lvItem.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View v,
final int position, long id) {
// TODO Auto-generated method stub
AlertDialog.Builder adb = new AlertDialog.Builder(
MainActivity.this);
adb.setTitle("Are you sure");
adb.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
itemArrey.remove(position);
itemAdapter.notifyDataSetChanged();
}
});
adb.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
adb.show();
return false;
}
});
lvItem.setClickable(true);
lvItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Object o = lvItem.getItemAtPosition(position);
Intent intent2 = new Intent(getApplicationContext(), MainActivity.class); // Mettere settings.class quando creata
MainActivity.this.startActivity(intent2);
}
});
}
private void setUpView() {
etInput = (EditText)this.findViewById(R.id.editText_input);
btnAdd = (Button)this.findViewById(R.id.button_add);
lvItem = (ListView)this.findViewById(R.id.listView_items);
itemArrey = new ArrayList<String>();
itemArrey.clear();
itemAdapter = new ArrayAdapter<String>(this, R.layout.customlistview,itemArrey);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addItemList();
}
});
}
protected void addItemList() {
if (isInputValid(etInput)) {
itemArrey.add(0,etInput.getText().toString());
etInput.setText("");
itemAdapter.notifyDataSetChanged();
}
}
protected boolean isInputValid(EditText etInput2) {
// TODO Auto-generatd method stub
if (etInput2.getText().toString().trim().length()<1) {
etInput2.setError("Insert value");
return false;
} else {
return true;
}
}
// Shared preferences
protected void SavePreferences(String key, String value) {
// TODO Auto-generated method stub
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = data.edit();
editor.putString(key, value);
editor.commit();
}
protected void LoadPreferences(){
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
String dataSet = data.getString("LISTS", "None Available");
itemAdapter.add(dataSet);
itemAdapter.notifyDataSetChanged();
}
I don't know how "call" the shared preferences and i don't know if in this way it's correct. Right now nothing happen, nothing is saving. Someone can help me please? Thanks
You should look at this API training about activity life cycle:
http://developer.android.com/training/basics/activity-lifecycle/index.html
and also this:
http://developer.android.com/training/basics/activity-lifecycle/recreating.html
As you can see, your activity can be gone because the user actively destroy it (using the back button) or the system can destroy it. If they system destroy it you can use onSaveInstanceState to save the data and onCreate to retrieve it. In that case you do not have to use SharedPreferences - just use Bundle as described in the link.
However, if you want to persist your data when the user close it, you should save your data when the call back onDestroy() is called. And retrieve the data when onCreate() is called. onDestroy() is called before the system thinks that your activity is not needed anymore, like when the user click the "back" button. In that case you do have to use one of the storage method provided by android, including Shared preferences. Like someone else said, it requires a "key, value" mechanism, so it might not match 100% with what you do. Using sqlLite is a bit heavy weight for this task, since your data is not really of a table type either (a single column table, actually, which is still not database worthy IMO). I think the best way to store your list is to use internal file. When onDestroy() is called, grab all your data and save to a file. When onCreate() is called, read the file and repopulate your list. You can read about android file system, including internal files here:
http://developer.android.com/training/basics/data-storage/files.html
As a close note, if the user press the "Home" button, your activity will not be destroyed. If he then "Force close" your app then nothing will be saved. If you still want to save it even in that case, I suggest you to save your data when "onStop()" is called and reset your list when onStart() is called.
Right now nothing happen, nothing is saving.
That's because you never call your SavePreferences() method.
If you want to continue using SharedPreferences to store the data in your list, you will need to call SavePreferences() on every item in the list.
However, SharedPreferences are used for storing data in a key-value format. This means that every item in your list will require a key, and you need to know that key to retrieve the data. If your list can contain a variable number of items, SharedPreferences is likely not what you want.
I recommend reading the Storage Options documentation, which provides a complete example using Shared Preferences correctly, and discusses other options which may better suit your needs.
I have an if loop when a chebkox in sharedpreferences changed status. But I'm not able to set putBoolean("blabla", false); when the status changed.
For example: User hits checkbox, CB gets checked, if says uncheck it but it won't uncheck.
My Code:
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals("cbSaveUsername")) {
SharedPreferences.Editor SFEdit2 = sharedPreferences.edit();
SFEdit2.putBoolean("cbSaveUsername", false);
SFEdit2.commit();
}
}
Can anyone tell me my mistake?
Edit: It looks like it works programatically but the tick is still in the box :o Where could be the mistake? I use it like Gunaseelan postet
Try to use onPause() and onResume() methods.
#Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
For more details onSharedPreferenceChanged not fired if change occurs in separate activity?