Back button restores modified text Views - java

I will simplify my code to address the problem specifically:
I have an activity A with some TextViews, which text is set to certain key values stored in SharedPreferences, in the activity's OnCreate method. Each textview has a button besides it. When a button is clicked it opens a new activity B which displays an adapter with different text strings. When the user clicks one, the new string is stored in preferences and the user is directed back to Activity A through an intent, and so OnCreate method is called and the textview is updated with the selected text. This works perfectly.
However, my problem is:
When a user does this and updates the textview, if they press Back button once, it will take them to Activity B, but if pressed twice that will take them to Activity A before updating the TextView and thus displaying the old textview, despite having stored in SharedPreferences the updated value. How can this be fixed?
A more simplified version of my problem is, I have a TextView in my layout, and a button which if pressed, deletes it and refreshes the Activity. User presses the delete button, text view disappears, but then presses back button and TextView is restored. That's what I dont want.
I have researched all the back button methodologies and savedInstanceState documentation but I still havent found something that works. I also tried adding an UpNavigation button in my action bar but it does the same effect than the back button.
ACTIVITY A (All these bits of code are called in OnCreate)
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String sound1name = prefs.getString("sound1", "1");
TextView sound1TV = findViewById(R.id.sound1);
sound1TV.setText(sound1Name);
ImageView sound1btn = findViewById(R.id.sound1_btn);
sound1btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent1 = new Intent(getApplicationContext(), SoundSelector.class);
startActivity(intent1);
}
});
ACTIVITY B (calls adapter)
AudioFileAdapter aFilesAdapter = new AudioFileAdapter(SoundSelector.this, audioFileList, soundID);
ListView listView = findViewById(R.id.sounds_list);
listView.setAdapter(aFilesAdapter);
ADAPTER IN ACTIVITY B (OnClickListener when text is selected)
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(contextL);
SharedPreferences.Editor editor = settings.edit();
editor.putString("sound1", sound1string);
editor.apply();
Intent intent1 = new Intent(getContext(), SoundEditor.class);
con.startActivity(intent1);
Im not sure if it is the Activity Lifecycle I have to modify, or intents, or something else but if someone could point me in the right direction I would really appreciate it, if you need any more information or code I'll post as soon as possible.

For storing and retrieving shared preferences try the following:
Storing
SharedPreferences preferences = getSharedPreferences("com.appname", Context.MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("sound1", "YOUR STRING HERE");
editor.apply();
Retrieving
SharedPreferences prfs = getSharedPreferences("com.appname", Context.MODE_PRIVATE);
String soundString = prfs.getString("sound1", "");
Your intent looks fine, are you sure you're passing Activity A's name?
For your second scenario, you could store if the text view was deleted in the shared preference, so when the back button is pressed, it won't display it again in the previous activity.
Something like this
if (isDeleted.equals("Yes")) {
textView.setVisibility(View.INVISIBLE);
}

The way Activity B is navigating back to Activity A by restarting the activity in the front and not by onBackPressed() navigation. Besides if the navigation is an important component to update the string value then the recommended method would be to use startActivityForResult() and update the preference and the TextView upon onActivityResult() of Activity A
class ActivityA extends AppCompatActivity {
private static final int activityRequest = 0x22;
public static final String keyPref = "keyToSharedPrefData";
private TextView mTextView;
private boolean isHidden = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.a_activity);
mTextView = findViewById(R.id.someTextView);
final String textForTextView = SharedPrefUtils.getString(keyPref);
mTextView.setText(textForTextView);
final Button button = findViewById(R.id.someButton);
if (button != null) {
button.setOnClickListener((view) -> {
final Intent intent = new Intent(ActivityA.this, AcitivtyB.class);
startActivityForResult(intent, activityRequest);
});
}
final deleteButton = findViewById(R.id.delete_button);
if (deleteButton != null) {
deleteButton.setOnClickListener((view) -> {
mTextView.setText("");
isHidden = true;
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == activityRequest && resultCode == ActivityB.resultSuccess && data != null) {
if (data.containsKey(ActivityB.resultKey)) {
SharedPrefUtils.saveString(keyPref,
data.getString(ActivityB.resultKey, SharedPrefUtils.getString(keyPref));
if (mTextView != null) {
mTextView.setText(SharedPrefUtils.getString(keyPref));
}
}
}
if (isHidden) {
mTextView.setVisibility(View.GONE);
}
}
}
in ActivityB you can
class ActivityB extends AppCompatActivity {
public static final int resultSuccess = 0x11
public static final int resultFailure = 0x33
public static final String resultKey = "keyForResult"
private void onListItemClick(final String soundString) {
// optional you can also do this
SharedPrefUtils.saveString(ActivityA.keyPref, soundString);
// better to do this
final Intent returnIntent = getIntent() != null ? getIntent() : new Intent();
returnIntent.putExtra(resultKey, soundString);
if (getCallingActivity() != null) {
setResult(returnIntent, resultSuccess);
}
onBackPressed();
}
}

Related

How to dynamically add items to GridView Android Studio (Java)

Hello I want to have an Add function that allows me to input items to my GridView
For Background: I have a standard GridView and an XML activity (which contains 2 TextView) that I want to convert to my GridView. I also have a custom ArrayAdapter class and custom Word object (takes 2 Strings variables) that helps me do this.
My problem: I want to have an Add button that takes me to another XML-Layout/class and IDEALLY it input a single item and so when the user goes back to MainActivity the GridView would be updated along with the previous information that I currently hard-coded atm. This previous sentence doesn't work currently
Custom ArrayAdapter and 'WordFolder' is my custom String object that has 2 getters
//constructor - it takes the context and the list of words
WordAdapter(Context context, ArrayList<WordFolder> word){
super(context, 0, word);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View listItemView = convertView;
if(listItemView == null){
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.folder_view, parent, false);
}
//Getting the current word
WordFolder currentWord = getItem(position);
//making the 2 text view to match our word_folder.xml
TextView title = (TextView) listItemView.findViewById(R.id.title);
title.setText(currentWord.getTitle());
TextView desc = (TextView) listItemView.findViewById(R.id.desc);
desc.setText(currentWord.getTitleDesc());
return listItemView;
}
}
Here is my NewFolder code. Which sets contentview to a different XML. it's pretty empty since I'm lost on what to do
public class NewFolder extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_folder_view);
Button add = (Button) findViewById(R.id.add);
//If the user clicks the add button - it will save the contents to the Word Class
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//make TextView variables and cast the contents to a string and save it to a String variable
TextView name = (TextView) findViewById(R.id.new_folder);
String title = (String) name.getText();
TextView descText = (TextView) findViewById(R.id.desc);
String desc = (String) descText.getText();
//Save it to the Word class
ArrayList<WordFolder> word = new ArrayList<>();
word.add(new WordFolder(title, desc));
//goes back to the MainActivity
Intent intent = new Intent(NewFolder.this, MainActivity.class);
startActivity(intent);
}
});
}
In my WordFolder class I made some TextView variables and save the strings to my ArrayList<> object but so far it's been useless since it doesn't interact with the previous ArrayList<> in ActivityMain which makes sense because its an entirely new object. I thought about making the ArrayList a global variable which atm it doesn't make sense to me and I'm currently lost.
Sample code would be appreciative but looking for a sense of direction on what to do next. I can provide other code if necessary. Thank you
To pass data between Activities to need to do a few things:
First, when the user presses your "Add" button, you want to start the second activity in a way that allows it to return a result. this means, that instead of using startActivity you need to use startActivityForResult.
This method takes an intent and an int.
Use the same intent you used in startActivity.
The int should be a code that helps you identify where a result came from, when a result comes. For this, define some constant in your ActivityMain class:
private static final int ADD_RESULT_CODE = 123;
Now, your button's click listener should looks something like this:
addButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent=new Intent(MainActivity.this, NewFolder.class);
startActivityForResult(intent, ADD_RESULT_CODE);
}
});
Now for returning the result.
First, you shouldn't go back to your main activity by starting another intent.
Instead, you should use finish() (which is a method defined in AppCompatActivity, you can use to finish your activity), this will return the user to the last place he was before this activity - ActivityMain.
And to return some data, too, you can use this code:
Intent intent=new Intent();
intent.putExtra("title",title);
intent.putExtra("desc",desc);
setResult(Activity.RESULT_OK, intent);
where title and desc are the variables you want to pass.
in your case it should look something like this:
public class NewFolder extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_folder_view);
Button add = (Button) findViewById(R.id.add);
//If the user clicks the add button - it will save the contents to the Word Class
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//make TextView variables and cast the contents to a string and save it to a String variable
TextView name = (TextView) findViewById(R.id.new_folder);
String title = (String) name.getText();
TextView descText = (TextView) findViewById(R.id.desc);
String desc = (String) descText.getText();
//Save it to the Word class
ArrayList<WordFolder> word = new ArrayList<>();
word.add(new WordFolder(title, desc));
Intent intent=new Intent();
intent.putExtra("title",title);
intent.putExtra("desc",desc);
setResult(Activity.RESULT_OK, intent);
//goes back to the MainActivity
finish();
}
});
}
You should probably also take care of the case where the user changed his mind and wants to cancel adding an item. in this case you should:
setResult(Activity.RESULT_CANCELLED);
finish();
In your ActivityMain you will have the result code, and if its Activity.RESULT_OK you'll know you should add a new item, but if its Activity.RESULT_CANCELLED you'll know that the user changed their mind
Now all that's left is receiving the data in ActivityMain, and doing whatever you want to do with it (like adding it to the grid view).
To do this you need to override a method called onActivityResult inside ActivityMain:
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check the result code to know where the result came from
//and check that the result code is OK
if(resultCode == Activity.RESULT_OK && requestCode == ADD_RESULT_CODE )
{
String title = data.getStringExtra("title");
String desc = data.getStringExtra("desc");
//... now, do whatever you want with these variables in ActivityMain.
}
}

Android: send data from adapter class to Activity

I want to add pictures to my favorite activity when a user tap on a picture. So far I'm able to get the data and display it but for some reason whenever I tap on an image it displays the favorited image, however, when I recheck the favorite activity by clicking on it, it shows empty.
Here's the little flow chart.
imageOnTap is implemented on RecyclerAdapter class. I have my Favorite activity and MainActivity.Any help would be appreciated. Thanks
Here's my MyRecyclerAdapter class
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.nameTxt.setText(albums.get(position).getName());
holder.img.setImageResource(albums.get(position).getImage());
//listener
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v, int pos) {
Toast.makeText(c,albums.get(pos).getName() + " ,added to favorite ",Toast.LENGTH_SHORT).show();
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("favorite",albums.get(pos).getImage());
editor.commit();
Toast.makeText(c,albums.get(pos).getName() + " ,added to favorite ",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(c, favorite.class);
// intent.putExtra(Intent.EXTRA_TEXT, albums.get(pos).getImage());
c.startActivity(intent);
}
});
}
Here's my favorite activity
public class favorite extends AppCompatActivity {
int favImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorite);
ImageView displayImage = (ImageView) findViewById(R.id.movieImage);
SharedPreferences settings = getSharedPreferences(PREFS_NAME,0);
displayImage.setImageResource(settings.getInt("Favorite", 0));
// Intent intent = getIntent();
// if (intent.hasExtra(Intent.EXTRA_TEXT)) {
// favImage = intent.getIntExtra(Intent.EXTRA_TEXT,image);
// displayImage.setImageResource(favImage);
//
// }
}
}
Here's my MainActivity
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_favorite) {
Intent intent = new Intent(this,favorite.class);
startActivity(intent);
}
If you are checking favourite activity from nav menu then it will not display anything afterall you are not passing any intent extras in it. Is it being display when you click the image? Are you getting intent params null here?
Use those preferences:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(ctx.getApplicationContext());
In your case it might be different activities observe different areas of settings.
THAT IS:
use:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(ctx.getApplicationContext());
SharedPreferences.Editor editor = settings.edit();
editor.putInt("favorite",albums.get(pos).getImage());
editor.commit();
instead of:
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("favorite",albums.get(pos).getImage());
editor.commit();
AND
this:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(ctx.getApplicationContext());
displayImage.setImageResource(settings.getInt("Favorite", 0));
instead of:
SharedPreferences settings = getSharedPreferences(PREFS_NAME,0);
displayImage.setImageResource(settings.getInt("Favorite", 0));

How to save button State into SharedPreferences in Android

I want create content application, i load data from JSON and when users click on button save this content into SQLitedatabase.
I want use this library for button.
And for checkable button, I use this code
I write below codes, when click on button i save this content into SQLitedatabase, but i can't save button sate into SharedPreferences!
When click on button (boolean checked) button is turn on, and when click again on the button turn off this button.
I want when click on button, turn on this button and save in SharedPreferences and when go to other activity and again back this activity, see turn on this button NOT turn off. when click again this button at that time turn off button!
Activity codes:
private ShineButton postShow_favPost;
private String favData = "FavPrefsList";
private Boolean favState;
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.post_show_page);
bindActivity();
//Give Data
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
title = bundle.getString("title");
image = bundle.getString("image");
content = bundle.getString("content");
dateTime = bundle.getString("dateTime");
author = bundle.getString("author");
category = bundle.getString("category");
categoryID = bundle.getString("categoryID");
}
mAppBarLayout.addOnOffsetChangedListener(this);
//// Save Fav state
final SharedPreferences saveFavPrefs = getSharedPreferences(favData, MODE_PRIVATE);
final SharedPreferences.Editor editor = saveFavPrefs.edit();
favState = saveFavPrefs.getBoolean("isChecked", false);
postShow_favPost = (ShineButton) mToolbar.findViewById(R.id.post_FavImage);
postShow_favPost.init(this);
postShow_favPost.setOnCheckStateChangeListener(new ShineButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(View view, boolean checked) {
if (checked == true) {
editor.putBoolean("isChecked", true);
editor.commit();
//////////// Database
favDB = new FavHelper(context);
long addNewFAV = favDB.insertFAV(title, image, content, dateTime, author, category);
if (addNewFAV < 0) {
TastyToast.makeText(context, "Not save in database", TastyToast.LENGTH_LONG, TastyToast.ERROR);
} else {
TastyToast.makeText(context, "Save in database", TastyToast.LENGTH_LONG, TastyToast.SUCCESS);
}
////////////////////
} else {
editor.putBoolean("isChecked", false);
editor.commit();
Toast.makeText(context, "Checked False", Toast.LENGTH_SHORT).show();
}
}
});
How can i fix my issue ?
Well you need to save the state when you click the button.
For example :
postShow_favPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (postShow_favPost.isChecked()){
editor.putBoolean("isChecked", true);
editor.apply();
}
else{
editor.putBoolean("isChecked", false);
editor.apply();
}
}
});
Then you have to load it in your onCreate():
#Override
protected void onCreate(Bundle savedInstanceState)
{
SharedPreferences saveFavPrefs = getSharedPreferences(favData, MODE_PRIVATE);;
postShow_favPost.setChecked(saveFavPrefs.getBoolean("isChecked", true));
}
Maybe this example will help you.
EDIT
Ok let's presume in your f function you just finished doing whatever you're doing to your database, after that, set the state as on or off, let's say you want on.
So :
public void loadPrefs(SharedPreferences prefs){
favState = prefs.getBoolean("isChecked",false);
}
public void f(SharedPreferences.Editor editor){
//database stuff
editor.putBoolean("isChecked", true); // or false
editor.apply();
loadPrefs(prefs);
// in here your state will be saved for your button as soon as you
finish working with your database, after that in your onResume() you
may change that state to false(off) in case you want it just for that post
}

Android - Change class variable before onCreate

I am new to Android development. I am trying to call a method of one of my classes when a button on my main activity is pressed.
On my Main Activity I have this button:
public void buttonTest(){
Button b = (Button) findViewById(R.id.test);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String s = "changeText:myText";
Intent in = new Intent(PlusActivity.this, Test.class);
in.putExtra("method",s);
startActivity(in);
}
});
}
And here is is the class (without imports) which that intent above is calling to.
public class Test extends Activity {
static String text = "test";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
TextView mTextView = (TextView) findViewById(R.id.textView);
mTextView.setText(text);
}
public void changeText(String s){
this.text = s;
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
String[] array = intent.getStringExtra("method").split(":");
if(array[0].equals("changeText")){
changeText(array[1]);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.test, menu);
return true;
}
}
Basically I want to know if it is possible to change the value of that String text, before onCreate(). Basically each button will have a correspondent text, and I want to be able to modify that text based on which button.
If it is, what should I do/change?
Thanks in advance.
The right way to do it is to send the string you want it to be as an extra in the intent, and to read the extra from the intent and assign it to that variable in the onCreate function.
Use SharedPreference. Save in OnCLick of first class and retrieve in OnCreate of second class.
Initialization
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
Storing Data
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
editor.commit(); // commit changes
Retrieving Data
// returns stored preference value
// If value is not present return second param value - In this case null
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
Deleting Data
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes
Clearing Storage
editor.clear();
editor.commit(); // commit changes
String text;
if (savedInstanceState == null) {
extras = getIntent().getExtras();
if(extras == null) {
text= null;
} else {
text= extras.getString("your default string message");
}
} else {
String s = "your default string message";
text= (String) savedInstanceState.getSerializable(s);
}

AppWidget with SharedPreferences has to update twice

I'm building a Widget which displays a textview which is editable as a edittext in a configuration class. And I just implemented sharedpreferences, so when the user would edit the widget for the second or third time etc. the already inputted text would appear in the edittext field in the configuration class.
And it works I guess. Well, before I implemented the sharedpreferences, the widget would update just fine after configuration. But now, I edit the text, press apply, but the widget doesn't update, I then edit the widget again and the widget updates with the text I applied to it the time before. So i guess you can say, that it's one update delayed. I hope I'm being clear, it's a little hard to explain.
So what am I doing wrong, I can not get it to work, any help would be very much appreciated.
Code:
public class WidgetConfig extends Activity implements OnClickListener {
AppWidgetManager awm;
int awID;
Context c;
EditText info;
Button b;
String note;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.widgetconfig);
c = WidgetConfig.this;
info = (EditText)findViewById(R.id.etwidgetconfig);
b = (Button)findViewById(R.id.bwidgetconfig);
loadPrefs();
b.setOnClickListener(this);
//Getting Info about the widget that launched this activity
Intent i = getIntent();
Bundle extras = i.getExtras();
if (extras != null){
awID = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID );
}
awm = AppWidgetManager.getInstance(c);
}
private void loadPrefs(){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
note = sp.getString("NOTE", "DEFAULT");
info.setText(note);
}
private void savePrefs(String key, String value){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, value); // value to store
editor.commit();
}
public void onClick(View v) {
// TODO Auto-generated method stub
savePrefs("NOTE", info.getText().toString());
RemoteViews views = new RemoteViews(c.getPackageName(), R.layout.widget);
views.setTextViewText(R.id.tvConfigInput, note);
ComponentName thisWidget = new ComponentName(this, Widget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(this);
manager.updateAppWidget(thisWidget, views);
Intent in = new Intent(c, WidgetConfig.class);
PendingIntent pi = PendingIntent.getActivity(c, 0, in, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.B_EditAgain, pi);
awm.updateAppWidget(awID, views);
Intent result = new Intent();
result.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, awID);
setResult(RESULT_OK, result);
finish();
}
}
You're not actually updating the TextView with the value of the EditText field. Your pseudocode currently looks like this:
String note;
onCreate(){
note = getSharedPref(NOTE);
}
onClick(){
putSharedPref(info.getText());
views.setText(note);
}
This ignores the value in your EditText until the NEXT time that you call onCreate, which you observed.
You should update the views with the text from the EditText:
onClick(){
putSharedPref(info.getText());
views.setText(info.getText());
}

Categories

Resources