Textview value not incrementing on button click - android

Iam developing a game in which i have to increment the textview value every time a "Rematch" button is tapped
Iam saving the textview value using shared preference, it works fine.
The Problem is that "if i tapped my 5 times on button then the value is shown 5, then if i closed the app and comes again it shows 5 (so shared pref works fine) but when i tapped on rematch again it again starts the textview value from 1, although my expected result was 6 because 5 was already saved
Here is my code for oncreate method
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
SharedPreferences sp = getSharedPreferences(SP_NAME, MODE_PRIVATE);
tValue = sp.getString("textvalue","");
coins=(TextView)findViewById(R.id.textView1);
coins.setText(tValue);
and on button click iam doing this
count++;
coins.setText(String.valueOf(count));
SharedPreferences sp = getSharedPreferences(SP_NAME, MODE_PRIVATE);
SharedPreferences.Editor sedt = sp.edit();
sedt.putString("textvalue", coins.getText().toString());
sedt.commit();

The problem I think is that count when you start the activity again is 0. You have to make count to start from the value that is saved, this could be a way to do it
count = Integer.valueOf(sp.getString("textValue",""))

The problem is that you use the value of count instead of tValue. So don't do count++ but save tValue as int and increment that one. Also do setText(tValue). Then it will work. Good luck.

That's because count starts again as 0,
and when u press the button it wil increment to 1.
so in your onCreate after you get your saved value back.
assign it to count, like:
count = Integer.parseInt(tValue);
Hope this will help u out.

Related

Handle textview that takes text from asynctask

I have a text view called tv that takes content from a web page. I want to store the content of that text view on button click but I don't want that the content of one day overwrite the content of the previous day ( for example today tv=ok and tomorrow tv=ok1 , I want to store ok and ok1 not only ok1)
Of course with shared preferences, I can store that text but I don't want to overwrite the text of the previous day
TextView tv = (TextView) findViewById(R.id.oks);
tv.setText(result[1].toString());
//in pass there is the text of tv(in main activity)
SharedPreferences ok = getSharedPreferences("pass", 0);
String str = ""+ok.getString("textvalue","");
SharedPreferences.Editor editor = ok.edit();
editor.putString("textvalue",str);
editor.apply();
TextView textView=(TextView) findViewById(R.id.preferiti);
textView.setText(ok.getString("textvalue",""));
This is your textview
//this are two fields which you want to append and getting somehow from API
String todayTv="ok" , tomorrowTv="ok1";
TextView tv = (TextView) findViewById(R.id.oks);
Let's set todayTv value on textView
tv.setText(todayTv);
now you want to store this value
SharedPreference sharedPref= getSharedPreferences("pass", 0);
Editor edit=sharedPref.edit();
edit.putString("textvalue",tv.getText().toString()); //getting value from textview
edit.apply();
Saved ! lets say you have now tomorrowTv which you want to show with your previous result i.e like this ok ok1
tv.setText(sharedPref.getString("textvalue","")+" "+tomorrowTv); //Concat strings and set text
Old Value - sharedPref.getString("textvalue","")
New Value - tomorrowTv
Now save it again with the above code for future
SharedPreference sharedPref= getSharedPreferences("pass", 0);
Editor edit=sharedPref.edit();
edit.putString("textvalue",tv.getText().toString()); //It will give you final string containg old and new value into one string
edit.apply();
Hope it will give you insight about It.
Read More : https://developer.android.com/training/basics/data-storage/shared-preferences.html
https://developer.android.com/reference/android/widget/TextView.html

How to retain changed button text in android?

In my project I have one edit text and one button.
When the project loads and I press the button,
the text of the button changes to the value of edit text.
But when I press the back button the change of button text does not persist.
I have included the snapshot which can describe my problem better.
I basically want the button text change to persist.
Please help.
The text doesn't show up on reopening the app because it was stored temporarily and when you closed your app it got destroyed. To retain the text you can store it in shared preference or file and on app startup load the text of the button from that source and if source is not present(When opening app for the first time) then put the default text on the button.
In your activity onCreate () method, you can add this code:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String btnText = preferences.getString("btnText", "");
if(!btnText.equalsIgnoreCase(""))
{
yourButton.setText(btnText);
}
yourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("btnText",yourTextEdit.getText().toString());
editor.apply();
....your code
}
});
In your layout xml file, set your button default text. android:text="#string/yourtext"
You need to save the text somewhere and load it when the activity starts. There are various ways to do this but I think Shared Preferences will work for you.
In the on click function for the button set the Shared Preference and in the Activity's onCreate check if the same Shared Preference is set. If the value is present load it else load the default value.
When you press the button for first time after getting text from edit text use the following code to save the edit text text that to be set on button in shared prefrences:
In on Button Click method:
EditText et = (EditText) findViewById(....);
String text = et.getTex().toString();
then you set it on button and so..
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("buttonText", text);
editor.commit();
then when you relauch the app in onCreate method use the following code:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String value= prefs.getString("buttonText", "");
button.setText(value); //whatever you button is

highlight the linearlayout background in android

I have to develop one android application.
Here is the scenario:There are many images in a linearlayout. When selected, the layout should be displayed with another background. This works well now.
Now, I would like that when I open a new activity and come back tho this one, the last selected layout should still be the highlighted one (with the second background).
How can this be done ???
Now i have used below code for highlighting the image when pressed:
LinearLayout ar = new LinearLayout(this);
ar.setOrientation(LinearLayout.VERTICAL);
ar.setPadding(3, 3, 3, 3);
ar.setLayoutParams(artiLayoutParams);
ar.setGravity(Gravity.CENTER);
ar.setBackgroundColor(Color.parseColor("#666666"));
ar.setBackgroundDrawable(getResources().getDrawable(R.drawable.list_selector));
ar.setId(position);
position++;
ar.setOnClickListener(mArticleClick);
EDIT:
private OnClickListener mArticleClick = new OnClickListener()
{
#Override
public void onClick ( View v )
{
int object = v.getId();
v.setSelected(true);
String articletitle = Appscontent.Sub_arraylist.get(object).toString();
Intent in = new Intent(MainActivity.this, SubCate.class);
in.putExtra("Title", articletitle);
startActivity(in);
}
};
Here i have to clicked one item means it is go to next activity.afterthat i have clicked back button means the selected item is stay on highlighted with another background.afterthat i have selected another item means its go to next activity.now i have to click back button means these item only highlight with background....but the pervious item also highlighted....
I wish to need the o/p like :
The last selected item only highlighted after click the back button...please help me...how can i do ..
EDIT:
I have declared int prevPosition = -1; globally...
Afterthat i have save the value here:
ar = new LinearLayout(this);
ar.setOrientation(LinearLayout.VERTICAL);
ar.setPadding(3, 3, 3, 3);
ar.setLayoutParams(artiLayoutParams);
ar.setGravity(Gravity.CENTER);
ar.setBackgroundColor(Color.parseColor("#666666"));
ar.setBackgroundDrawable(getResources().getDrawable(R.drawable.list_selector));
ar.setId(position);
position++;
ar.setOnClickListener(mArticleClick);
SharedPreferences preferences = getSharedPreferences(SPF_NAME, android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putLong("POSITION", prevPosition);
editor.commit();
In Onclick method:
private OnClickListener mArticleClick = new OnClickListener()
{
#Override
public void onClick ( View v )
{
int object = v.getId();
SharedPreferences preferences = getSharedPreferences(SPF_NAME, android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putLong("POSITION", -1);
editor.commit();
But my background color is not staying here after press the back button...
This is "easy". In order to be able to know which image should be highlighted, you need to store this information somewere. A good practice is a database, but if you have only this info to store, you can create something like a shared preferance or some other types of global variables. Then, when you will re-open the activity with your listview (or come back to it), you should tell to your listview which item should be highlighted and highlight this item.

Comparing variables

I'm writing a game and I am storing the players top score as a SharedPrefrence. I am using this method so that when the user exits the application, his top score stays. I have everything coded up until that point. I now want to implement a way to display the new top score when the player plays the game again. The logic behind this is that If the first top score is greater than zero, display the first top score. Then when the game is played again, if the second top score is greater than the first top score, display the second top score, else display the first top score. In my head, I would think a simple If/else statement would suffice, but my problem comes into play when declaring the first variables. I wrote the following code, but it doesn't seem to work. It just displays the new score--even if it is a lower value than the first score which is what I don't want. Any help would be much appreciated. Code:
TextView textSavedWeek2ms2_1 = (TextView)findViewById(R.id.ts02);
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
String strSavedWeek2ms2_1 = sharedPreferences.getString("top_score", "");
String topscore = strSavedWeek2ms2_1;
int topscore1 = Integer.valueOf( topscore);
if (topscore1 > 0 )
{
textSavedWeek2ms2_1.setText(topscore);
}
else
textSavedWeek2ms2_1.setText("0");
}
This is probably unintended:
if (topscore2 > topscore2){
I think you made a typo....
if (topscore2 > topscore2)
{
textSavedWeek2ms2_1.setText(topscore);
}
So it should be
if (topscore2 > topscore1)
{
textSavedWeek2ms2_1.setText(topscore);
}

SharedPreferences editing

Im having problem incrementing a sharedpreference. Isn't it possible?
..
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor favEdit = getPrefs.edit();
int somepref = getPrefs.getInt("somePref", 0);
somepref++;
favEdit.putInt("somePref", somepref);
favEdit.commit();
This should work imo, but when executed it's just ignored.
If i use a number instead it works fine, but then the point in using the sharedpreference is lost..
Anyone?
How I load my preferences:
SharedPreferences getPrefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
getPrefs = getSharedPreferences(filename, 0);
int somepref = getPrefs.getInt("somePref", 0);
The problem is that I want my somepref to increase in function1 # activity1, and use the somepref to define what function to run in activity2.
The main plan:
I want to add a imagebutton from one activity to another by doing a longclick. And I want to be able add more than one imagebutton.
And from this new activity I want a longclick to remove the imagebutton.
I'm having problems getting my head around how to do this..
somepref.putInt("somePref", somepref);
should be
favEdit.putInt("somePref", somepref);
and fav.commit(); shouls be favEdit.commit();
and do you have getPrefs = getSharedPreferences(filename, 0); somewhere?
i don't know how you compile the current code
you need to change the last two lines to
favEdit.putInt("somePref", somepref);
favEdit.commit();

Categories

Resources