Android Seek Bar Saved Preferences - android

Hi there I am trying to get an integer that will be given by a SeekBar using the .getprogress to go into an Integer which will get saved by the preference and will go to my toast code at another side of my application to make things easier heres my code already.
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;
import tk.mizzeeboy.freestorageconverter.R;
public class SettingsActivity extends Activity{
SeekBar cl;
TextView t;
String lolly , finlly;
int hehe;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.333);
cl = (SeekBar) findViewById(R.id.seekB3r1);
t = (TextView) findViewById(R.id.textV3w1);
cl.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
// TODO Auto-generated method stub
t.setTextSize((cl.getProgress()) * getResources().getDisplayMetrics().density);
hehe = cl.getProgress();
finlly.valueOf(hehe);
SharedPreferences mypreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mypreferences.edit();
editor.putString("TeamName", finlly);
editor.commit();
}
});
}
}
and in my other activity I want to open and read it heres the code for that
SharedPreferences mypreferences = getApplicationContext().getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
String teamnamestring = mypreferences.getString("TeamName", "Please Enter :)");
Toast andEggs = Toast.makeText(BitActivity.this, teamnamestring , Toast.LENGTH_SHORT);
andEggs.show();
But my problem is that it I am getting the Please Enter Sign everytime and it will not pick up my integer can someone help?

What TGMCians is saying is that you put hehe as Int in the preferences (editor.putInt("TeamName", hehe);), in first Activity then get it as String in the other Activity (mypreferences.getString("TeamName",...). This will cause ClassCastException. Either, you put it as a String from the begining or get it as an Int in the second Activity.
Try:
int val=mypreferences.getInt("TeamName",-1);
String teamnamestring="";
if(val==-1){
teamnamestring="Please Set Up Your Custom Text Size!";}
else {teamnamestring=String.ValueOf(val);}
Toast andEggs = Toast.makeText(BitActivity.this, teamnamestring , Toast.LENGTH_SHORT);
andEggs.show();

Related

Android : Save Button Instance

Hello i'm working on my android project. I have created an activity where the use gets four buttons, n i want the user to select any one. I have done this by setting other buttons to .setClickable(false). But when I restart or say relaunch the app again all the buttons get enabled. I want that when user selects a button it should save its choice, so that on retstart of app, the user doesn't get confused. Below is the piece of code:
Notifications.class
package com.mateoj.multiactivitydrawer;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.NotificationCompat;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.mateoj.multiactivitydrawer.department.dept_1styeartab;
import com.pushbots.push.Pushbots;
public class notifications extends BaseActivity {
private WebView webView;
Button clickButton;
Button clickButton1;
Button clickButton2;
Button clickButton3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Pushbots.sharedInstance().init(this);
Pushbots.sharedInstance().setCustomHandler(customHandler.class);
setContentView(R.layout.activity_notifications);
final SharedPreferences preferences = getSharedPreferences("com.mateoj.multiactivitydrawer", MODE_PRIVATE);
final SharedPreferences.Editor editor = preferences.edit();
clickButton = (Button) findViewById(R.id.ncs);
clickButton1 = (Button) findViewById(R.id.nmech);
clickButton2 = (Button) findViewById(R.id.nece);
clickButton3 = (Button) findViewById(R.id.neee);
clickButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent show = new Intent(getApplicationContext(), noti_cse.class);
Pushbots.sharedInstance().tag("cse");
Pushbots.sharedInstance().untag("mech");
Pushbots.sharedInstance().untag("ece");
Pushbots.sharedInstance().untag("eee");
editor.putString("session", "cse").commit();
editor.commit();
startActivity(show);
}
});
clickButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent show = new Intent(getApplicationContext(), noti_mech.class);
Pushbots.sharedInstance().tag("mech");
Pushbots.sharedInstance().untag("ece");
Pushbots.sharedInstance().untag("eee");
Pushbots.sharedInstance().untag("cse");
editor.putString("session", "mech").commit();
editor.commit();
startActivity(show);
}
});
clickButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent show = new Intent(getApplicationContext(), noti_ece.class);
Pushbots.sharedInstance().tag("ece");
Pushbots.sharedInstance().untag("mech");
Pushbots.sharedInstance().untag("eee");
Pushbots.sharedInstance().untag("cse");
editor.putString("session", "ec").commit();
editor.commit();
startActivity(show);
}
});
clickButton3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent show = new Intent(getApplicationContext(), noti_eee.class);
Pushbots.sharedInstance().tag("eee");
Pushbots.sharedInstance().untag("ece");
Pushbots.sharedInstance().untag("mech");
Pushbots.sharedInstance().untag("cse");
editor.putString("session", "eee").commit();
editor.commit();
startActivity(show);
}
});
onStartUp();
}
private void onStartUp()
{
SharedPreferences sharedPreferences = getSharedPreferences("com.mateoj.multiactivitydrawer", Context.MODE_PRIVATE);
String str = sharedPreferences.getString("session", "");
if (str.equals("cs")) {
clickButton.setClickable(true);
clickButton1.setClickable(false);
clickButton2.setClickable(false);
clickButton3.setClickable(false);
} else if (str.equals("mech")) {
clickButton.setClickable(false);
clickButton1.setClickable(true);
clickButton2.setClickable(false);
clickButton3.setClickable(false);
} else if (str.equals("ec")) {
clickButton.setClickable(false);
clickButton1.setClickable(false);
clickButton2.setClickable(true);
clickButton3.setClickable(false);
} else if (str.equals("eee")) {
clickButton.setClickable(false);
clickButton1.setClickable(false);
clickButton2.setClickable(false);
clickButton3.setClickable(true);
}
}
/* private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
} */
#Override
protected boolean useDrawerToggle() {
return false;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_credits)
return true;
if (item.getItemId() == android.R.id.home)
onBackPressed();
return super.onOptionsItemSelected(item);
}
}
So what should be changed here
One thing you could do is save the state of the Button (Everytime you/user click on the Button save the true or false on your SharedPreferences) and everytime you start the Activity the value of setClickable() put the result of your SharedPrefernce.
That's an option, but there are a lot of ways to do it, that's one of them.
I don't know this framework that you are using (Pushbots), but I think you are forgeting to check which tag is saved in Pushbots during the activity method onCreate() and enable or disable the buttons according to it. You are saving the tags on Pushbots button you never check which tag is saved on it to enable or disable the button.
I'd recommend you to use SharedPreferences directly instead of use this framework, even I don't know it. SharedPreferences is so simple to use that I don't see any reason to use frameworks.
You can use the SharedPreferences class to save the user selection.This video can help you get started - https://www.youtube.com/watch?v=riyMQiHY3V4 .Just save the user selection of button in a key value pair with sharedpreferences class.On activity restart or relaunch just check for the value in the shared preferences instance and accordingly set the button setClickable(true) or setClickable(false).
EDIT:
clickButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//same code as above without the setClickable() on buttons
//remove the button.setClickable(false); for rest of the buttons
editor.putString("session", "akash").commit();
editor.commit();
startActivity(show); //Start the activity here
}
}):
Repeat this for all the click listeners and change the "akash" to something different (according to need) for each button click listener.Then use the method
private void onStartUp(){
SharedPreferences sharedPreferences = getSharedPreferences("com.mateoj.multiactivitydrawer", Context.MODE_PRIVATE);
String str=sharedPreferences .getString("session","akash");
if(str.equals("akash")){
//set buttons setClickable(true) or setClickable(false)
} else if(str.equals("...")) //replace "..." with other strings which can replace "akash"
//set buttons setClickable(true) or setClickable(false)
} //continue the else if logic till all conditions are met
}
call onStartUp(); in onCreate(); after setting the on click listeners for the buttons .

How to store the seekbar values in a global variable use in another screen

Hi I am try to write a code in android where I have a 2 seekbars and I want to store the values obtained from seekbars and would like to use it in another screen. So can any help me how to do it.
I am using global variables because I want store the values untill the I store I reuse them.
Here is my code so please any one tell me how to do that.
package com.example.newairways;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class relationship extends Activity implements OnSeekBarChangeListener {
private String Q1a,Q1b;
private SeekBar mSeekBar1, mSeekBar2;
private TextView tv1, tv2;
private Button ok,nextQ,cancel;
private ProgressDialog dialog = null;
Intent myIntent;
//List<NameValuePair> nameValuePairs= null;
Bundle myValues;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.relationships);
myValues=getIntent().getExtras();
mSeekBar1 = (SeekBar) findViewById(R.id.Q1a);
mSeekBar1.setOnSeekBarChangeListener(this);
mSeekBar2= (SeekBar) findViewById(R.id.Q1b);
mSeekBar2.setOnSeekBarChangeListener(this);
tv1 = (TextView)findViewById(R.id.Ans1a);
tv2 = (TextView)findViewById(R.id.Ans1b);
TextView welcomeMsg = (TextView)findViewById(R.id.username);
welcomeMsg.setText("name : "+myValues.getString("value"));
ok = (Button)findViewById(R.id.ok);
nextQ = (Button)findViewById(R.id.nextquestion);
cancel= (Button)findViewById(R.id.cancel);
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
switch (seekBar.getId())
{
case R.id.Q1a:
tv1.setText(Integer.toString(progress)+"%") ;
Toast.makeText(relationship.this, "Seekbar Value : " + progress, Toast.LENGTH_SHORT).show();
break;
case R.id.Q1b:
tv2.setText(Integer.toString(progress)+"%") ;
Toast.makeText(relationship.this, "Seekbar Value : " + progress, Toast.LENGTH_SHORT).show();
break;
}
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
}
Create a file GlobalVars.java:
public class GlobalVars extends Application {
private static String value2;
public static String getSeekBarValue() {
return value2;
}
public static void setSeekBarValue(String value) {
value2 = value;
}
}
Then in your files you can save and load your variables:
GlobalVars.setSeekBarValue(progress);
int v = GlobalVars.getSeekBarValue();
You asked for global variables but don't forget that the values they store are deleted every time you exit the app.

Saving the score using shared preferences

Hey guys I know there are already many posts for the same and I have followed each of them.
Here I am facing a problem and need to know the sloution.
I am releasing my app tomorrow so need help with this.
I have tried to use it with string as well as int but none of them are working and giving error.
Thanks
My Code :
package com.droidacid.apticalc.tys;
import com.droidacid.apticalc.R;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.widget.TextView;
public class HighScores extends Activity {
TextView tvHighScore;
private static String SCORE_KEY = "savedScore";
String myScore;
int score;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.tys_high_score);
tvHighScore = (TextView) findViewById(R.id.tv_tys_score);
getScore();
}
private void getScore() {
Bundle getScore = getIntent().getExtras();
score = getScore.getInt("score");
myScore = Integer.toString(score);
setScore(score);
getScore(score);
}
private void setScore(int score) {
SharedPreferences saveScore = getSharedPreferences("saveScores", MODE_PRIVATE);
SharedPreferences.Editor editor = saveScore.edit();
editor.putString(SCORE_KEY, myScore);
editor.commit();
}
SharedPreferences saveScore = getSharedPreferences("saveScores", MODE_PRIVATE);
tvHighScore.setText(saveScore.getString(SCORE_KEY, ""));
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
It's because that these two lines are not in any method.
SharedPreferences saveScore = getSharedPreferences("saveScores", MODE_PRIVATE);
tvHighScore.setText(saveScore.getString(SCORE_KEY, ""));
Try to put these two lines in your on create method and you will see that this error will stop.
Tell me how it goes.

SharedPreferences ToggleButton not saving

*I've been going nuts with this problem the last few days.I'm trying to use SharedPreferences to allow my users to save the selected option of the in-game audio via the ToggleButton but everytime when I run my app and hit my "Done" button to go back to the main_activity screen and then click on settings again it never saves.I've done some research on this by googling,my book and this site but by many methods I've tried the result is the same.
I'm new to android development let alone app development so as much as I learned these past few weeks this has been a major roadblock for me and I apologize if this question has been covered already on this site but I'm at a real loss on what I'm doing wrong here.
Here is my code from my settings activity.
package com.fullfrontalgames.numberfighter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ToggleButton;
public class Settings extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
Button Notifications = (Button) findViewById(R.id.Notifications);
Button Done = (Button) findViewById(R.id.done);
Button AccountSettings = (Button) findViewById(R.id.AccountSettings);
final ToggleButton AT = (ToggleButton) findViewById(R.id.AudioToggle);
AT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
{
if ((AT.isChecked()))
{
SharedPreferences appPrefs =
getSharedPreferences("com.fullfrontalgames.numberfighter.Settings_preferences",
MODE_PRIVATE);
SharedPreferences.Editor editor = appPrefs.edit();
editor.putBoolean("atpref", AT.isChecked()); //value to store
editor.commit();
}
}
}
});
SharedPreferences appPrefs =
getSharedPreferences("com.fullfrontalgames.numberfighter.Settings_preferences",
MODE_PRIVATE);
boolean atpref = appPrefs.getBoolean("atpref", true); //default is true
AT.setChecked(atpref);
Done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent Intent = new Intent(Settings.this,activity_main.class);
Intent.setFlags(android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(Intent);
}
});
Notifications.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("com.fullfrontalgames.numberfighter.Notifications"));
}
});
AccountSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("com.fullfrontalgames.numberfighter.AccountSettings"));
}
});
}
public void onToggleClicked(View view) {
// Is the toggle on?
boolean on = ((ToggleButton) view).isChecked();
if (on) {
view.setSoundEffectsEnabled(true);
} else {
view.setSoundEffectsEnabled(false);
}
}
}
If you are trying to save the ToggleButton's state when it is false, simply remove the if-statement in your OnClickListener:
if ((AT.isChecked()))

Android Using SharedPreferences to save and retrieve values - Counter

Hello I am new to android and actually i am developing a application whereby the user would be clicking on a button and the button should record the click event - the counter should be incremented at each time the button is clicked. The button would be displayed in one activity and once the user has clicked the button, another activity would be displayed whereby the results would be shown.
Actually i am having problems in assigning the sharedPreferences to the button and then displaying it into the next activity hence having the number of clicks.
The code i am using is as follows:
MainActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
/** Declare the variables being used */
public static final String GAME_PREFERENCES = "GamePrefs";
public static final String GAME_PREFERENCES_SCORE = "Score"; // Integer
int counter;
Button add;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
counter = 0;
add = (Button) findViewById (R.id.bAdd);
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
Intent openClickActivity2 = new Intent("com.android.jay.Results");
startActivity(openClickActivity2);
}
});
}
}
Results.java
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;
public class Results extends MainActivity{
public void onCreate(Bundle savedInstanceState) {
SharedPreferences mGameSettings;
super.onCreate(savedInstanceState);
mGameSettings = getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE);
setContentView(R.layout.results);
final TextView DisplayResults =
(TextView) findViewById(R.id.bAdd);
if (mGameSettings.contains(GAME_PREFERENCES_SCORE)) {
DisplayResults.setText(mGameSettings.getString(GAME_PREFERENCES_SCORE, “counter”));
}
}
}
Any help to guide me would be much appreciated.Thank you
You will have to set GAME_PREFERENCES_SCORE in MainActivity. Do something like this after counter++:
getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE).edit().setInt(GAME_PREFERENCES_SCORE, counter). commit();
Simply make a Preferences class
public class Preferences {
String MASTER_NAME = "mysticmatrix_master";
SharedPreferences mysticMatrixPref;
Preferences(Context context) {
mysticMatrixPref = context.getSharedPreferences(MASTER_NAME, 0);
}
public void setAddCount(int count) {
SharedPreferences.Editor prefEditor = mysticMatrixPref.edit();
prefEditor.putInt("count", count);
prefEditor.commit();
}
public int getAddCount() {
return mysticMatrixPref.getInt("count", 0);
}
}
and in your MainActivity.java put this code
public class MainActivity extends Activity implements OnClickListener {
ImageButton add;
Preferences cpObj;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
preferences = new Preferences(getApplicationContext());
/*
* getting the count variable and adding 1 in that to check the condition of showing rate activity and adds
*/
add = (Button) findViewById (R.id.bAdd);
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
cpObj = new Preferences(getApplicationContext());
cpObj.setAddCount(cpObj.getAddCount() + 1);
}
});
}
}
And in your result activity just get the count's value
import android.content.Context;
public class Results extends MainActivity{
Preferences cpObj;
public void onCreate(Bundle savedInstanceState) {
preferences = new Preferences(getApplicationContext());
setContentView(R.layout.results);
final TextView DisplayResults =
(TextView) findViewById(R.id.bAdd);
DisplayResults.setText(cpObj.getAddCount());
}
} }
By this you will get the default value of result as '0' and you can set that in your Preferences class
Use a method like this:
public static void SavePreference(Context context, String key, Integer value) {
SharedPreferences.Editor editor = PreferenceManager
.getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE)
.edit();
editor.putInt(key, value);
editor.commit();
}
and in you onclick after counter++ add this:
SavePereference(context, "GAME_PREFERENCES_SCORE", counter);

Categories

Resources