android textview value - android

I have some problem
I want to change my textview value. when my code change it will change
here is the code
public class SubMenuActivity extends Activity {
private static final int GALLERY = 0;
private static final int SUBMANU01 = 7;
private static final int MANU01 = 1;
private static final int MANU02 = 2;
private static final int MANU03 = 3;
private static final int MANU04 = 4;
private static final int MANU05 = 5;
TextView tx1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tx1 =(TextView)this.findViewById(R.id.textView1);
if(tx1.toString()=="1".toString())
{
tx1.setText("7");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
SubMenu fileMenu = menu.addSubMenu(GALLERY, SUBMANU01, Menu.NONE, "File");
fileMenu.add(GALLERY, MANU01, Menu.NONE, "new");
fileMenu.add(GALLERY, MANU02, Menu.NONE, "open");
fileMenu.add(GALLERY, MANU03, Menu.NONE, "save");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MANU01:
case MANU02:
case MANU03:
final String itemid = Integer.toString(item.getItemId());
tx1.setText(itemid);
return true;
}
return super.onOptionsItemSelected(item);
}
tx1.text value did not show 7 ,where is the problem?
I hope someone could tell me the problem.

compare like this
if(tx1.getText().toString().equals("1"))
{
tx1.setText("7");
}

Strings can not be compared with == operator they can be compared with .equals method
so change your code to this
if(tx1.toString().equals("1"))
{
tx1.setText("7");
}

Instead of
if(tx1.toString()=="1".toString()) {
tx1.setText("7");
}
try this
if(tx1.getText().toString().equals("1")) {
tx1.setText("7");
}

You need to Compare the variable like.equal(Object/String)
if(tx1.toString().equals("1"))
{
tx1.setText("7");
}

in java "==" means the address is the same, instead, you can use .equel() which comes from the
basic class "object".

first of you should print the value of txt1.
System.out.println("value of tx1:"+tx1.getText.toString());
if(tx1.getText().toString().equals("1"))
{
tx1.setText("7");
}

Related

Android checkboxes, how to implement if statement.

I am currently coding an android app but I encountered some difficulty.
I am able to receive some checkbox values from another activity using the getIntent().getExtras().getBoolean()function.
But my question is, how can i make sure that checkboxes with the characters 'wb' or 'ab' or 'alb' together with(or not) 'cs' appearing, a count is performed and the one with the greatest value between 'wb', 'ab' and 'alb' is chosen and a summary is displayed via a texfield.
e.g. if there appearances of 'wb' are greater than those of 'alb' and ab, then the result is displayed "you have a widened bronchus".
package com.example.vic.cdmes_;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class results extends AppCompatActivity {
private Button displayResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
viewResults();
}
private void viewResults() {
final Boolean wb1 = getIntent().getExtras().getBoolean("wb1");
final Boolean wb2 = getIntent().getExtras().getBoolean("wb2");
final Boolean wb3 = getIntent().getExtras().getBoolean("wb3");
final Boolean wb4 = getIntent().getExtras().getBoolean("wb4");
final Boolean wb5 = getIntent().getExtras().getBoolean("wb5");
final Boolean wb6 = getIntent().getExtras().getBoolean("wb6");
final Boolean wb7 = getIntent().getExtras().getBoolean("wb7");
final Boolean cs1 = getIntent().getExtras().getBoolean("cs1");
final Boolean cs2 = getIntent().getExtras().getBoolean("cs2");
final Boolean vb1 = getIntent().getExtras().getBoolean("vb1");
final Boolean vb2 = getIntent().getExtras().getBoolean("vb2");
final Boolean vb3 = getIntent().getExtras().getBoolean("vb3");
final Boolean vb4 = getIntent().getExtras().getBoolean("vb4");
final Boolean vb5 = getIntent().getExtras().getBoolean("vb5");
final Boolean alb1 = getIntent().getExtras().getBoolean("alb1");
final Boolean alb2 = getIntent().getExtras().getBoolean("alb2");
final Boolean alb3 = getIntent().getExtras().getBoolean("alb3");
final Boolean ab1 = getIntent().getExtras().getBoolean("ab1");
final Boolean ab2 = getIntent().getExtras().getBoolean("ab2");
final Boolean ab3 = getIntent().getExtras().getBoolean("ab3");
final Boolean ab4 = getIntent().getExtras().getBoolean("ab4");
displayResult = (Button)findViewById(R.id.displayResults);
displayResult.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(results.this,.toString(),
// Toast.LENGTH_SHORT).show();
if(wb1&&wb2&&wb3&&wb4&&wb5&&wb6&&wb7&&cs1&&cs2)
{
//if the number of checkboxes exceeds
}
else
if (vb1&&vb2&&vb3&&vb4&&vb5&&cs1&&cs2)
{
//display the person might be having a widened bronchus
}
else
if (alb1&&alb2&&alb3&&cs1&&cs2)
{
//display the person might be having a alb disease
}
else
if (ab1&&ab2&&ab3&&ab4&&cs1&&cs2)
{
//display the person might be having a airborne disease
}
}
});
}
}
thanks for the help in advance.
Set Default Boolean value. Like This
final Boolean wb1 = getIntent().getExtras().getBoolean("wb1",true);
You can get the count of wb, ab and alb below, using that you can write the if statement.
int wbCount = 0, abCount = 0, albCount = 0;
boolean cs = (cs1 && cs2);
for(int i=1; i <= 7; i++) {
if(getIntent().getExtras().getBoolean("wb"+i) && cs) {
wbCount++;
}
}
for(int i=1; i <= 3; i++) {
if(getIntent().getExtras().getBoolean("alb"+i) && cs) {
albCount++;
}
}
for(int i=1; i <= 4; i++) {
if(getIntent().getExtras().getBoolean("ab"+i) && cs) {
abCount++;
}
}

Highlighting textview with color like Adobe PDF

I'm trying to add menu to focus textview to highlight a word or phrase.
Currently my code has issues
1. highlights more than one word if the word appears more than once
2. Highlighted color disappears on app exit.
TextView textView = (TextView) findViewById(R.id.textView);
textView.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
getMenuInflater().inflate(R.menu.h_menu, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.highlight:
setTextBG();
return true;
default:
break;
}
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
});
}
private void setTextBG() {
String selectedText = "";
if (textView.isFocused()) {
final int textStartIndex = textView.getSelectionStart();
final int textEndIndex = textView.getSelectionEnd();
int min = 0;
int max = textView.getText().length();
min = Math.max(0, Math.min(textStartIndex, textEndIndex));
max = Math.max(0, Math.max(textStartIndex, textEndIndex));
selectedText = textView.getText().subSequence(min, max).toString().trim();
}
int txt = textView.getText().toString().indexOf(selectedText, 0);
Spannable mywords = new SpannableString(textView.getText().toString());
for (int i = 0; i < textView.getText().toString().length() && whateva != -1;
i = whateva+1) {
txt = textView.getText().toString().indexOf(selectedText, i);
if (txt == -1) break;
else {
mywords.setSpan(new BackgroundColorSpan(Color.YELLOW), txt, txt+selectedText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(mywords, TextView.BufferType.SPANNABLE);
}
}
Toast.makeText(getApplicationContext(), selectedText, Toast.LENGTH_SHORT).show();
}
Please find below example for highlighting more than one word in content.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private TextView textContent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textContent = (TextView) findViewById(R.id.txtContent);
highlightWords();
}
private void highlightWords() {
String content = "This is just a demo of how to highlight more than one word in Android";
textContent.setText(getSpannableWord(content));
}
private Spannable getSpannableWord(String content) {
Spannable spannableString = new SpannableString(content);
// Create list of highlighted word and add to list every time user highlights
ArrayList<HighlightedWord> words = new ArrayList<>();
//1st highlighted word
HighlightedWord highlightedWord1 = new HighlightedWord("demo", 15);
words.add(highlightedWord1);
//2nd highlighted word
HighlightedWord highlightedWord2 = new HighlightedWord("highlight", 30);
words.add(highlightedWord2);
for (HighlightedWord highlightedWord : words) {
spannableString.setSpan(new BackgroundColorSpan(Color.YELLOW), highlightedWord.getStartIndex(),
highlightedWord.getStartIndex()+ highlightedWord.getWord().length(), Spannable
.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return spannableString;
}
}
Thanks!

CountDownTimer switch background of RelativeLayouts (1&2)

I trying to run a timer to switch Backgrounds of two relative layouts in loop if user set or unset it while app is running.
Not enough I tried to work with drawable_image.setAlpha(x) to let the Background vanish slowly while the relative layout 2 behind has an other image (afterwords switch position).
My method private void switchBackground(){} do it right well. BUT it is too much work for the device and I lose a lot of frames (15-39) so that the "slow vanish" by .setAlph(x) sometimes totally fail and not working (the pics switch just by time, like the onTick() method do not exists anymore).
I think one reason for this is the countDownTimer itself and a second that the method is (should) running in the main Activity Class. May be the third reason is the problem that I choose "setBackground" of relative Layouts instead of image showing stuff?!
I tried adding a new Class to do the "switchBackground .."- method outside, but this failed cause of "nullpointerexception" and "non-static / static" problems.
Which classes and methods would be better, so as not to lose too much frames / memory.
//"/---/" short up stuff which isn't important, but still much do there
public class MainActivity extends AppCompatActivity {
//class value
//private static final String TAG = "App";
private RelativeLayout layout_behind;
private RelativeLayout layout_front;
private CountDownTimer myCountdown;
private final int[][] matrix = new int[9][9];
private EditText sumNum;
private MediaPlayer music;
private SoundPool multiTon;
private int whoopId;
private int failId;
private int winId;
private boolean soundOn =WelcomeScreen.soundCheck;
//class MathThing, Welcome_Screen exists too
private final int[][] detected = MathThing.detected;
private final ArrayList<int[][]> returnArr = new ArrayList<>();
private int switch_draw=0;
private boolean switchDraw;
private Drawable image_2;
private Drawable image_1;
private Drawable image_3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Music
multiTon = new SoundPool(1,AudioManager.STREAM_MUSIC,0);
whoopId = multiTon.load(this, R.raw.whoop,1);
failId = multiTon.load(this, R.raw.fail, 1);
winId = multiTon.load(this, R.raw.win,1);
music = MediaPlayer.create(MainActivity.this, R.raw.backgroundmusic);
if(WelcomeScreen.musicCheck) {
music.setVolume(1, 1);
music.setLooping(true);
music.start();
}
//create/initialize some stuff and initialize layouts and images
hideAndCreate();
//switch Background
switchBackground(); switchDraw=true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// . . . settings in Toolbar
int id = item.getItemId();
switch(id){
case R.id.bla: //just cut some here to do it shorter
break;// /.../
}
return super.onOptionsItemSelected(item);
}
private void hideAndCreate(){
// /----/ create a lot of edittexts / textviews/ buttons
//initialize layouts / images
}
protected void onPause(){
super.onPause();
if(switchDraw){
myCountdown.cancel();}
music.release();
finish();
}
//method with CountDownTimer
private void switchBackground(){
//Layout Background
switch_draw=0;
layout_behind.setBackground(image_2);
int duration=15000;
int tick=250;
myCountdown = new CountDownTimer(duration, tick){
int a = 255;
public void onTick(long millisUntilFinished) {
if(switch_draw==0){
image_1.setAlpha(a);
layout_front.setBackground(image_1);
if(a>=4){a=a-4;}
}else if(switch_draw==1){
image_2.setAlpha(a);
layout_front.setBackground(image_2);
if(a>=4){a=a-4;}
}else{
image_3.setAlpha(a);
layout_front.setBackground(image_3);
if(a>=4){a=a-4;}
}
}
public void onFinish() {
if(switch_draw==0){
image_2.setAlpha(255);
layout_front.setBackground(image_2);
image_3.setAlpha(255);
layout_behind.setBackground(image_3);
switch_draw=1;
}else if(switch_draw==1){
image_3.setAlpha(255);
layout_front.setBackground(image_3);
image_1.setAlpha(255);
layout_behind.setBackground(image_1);
switch_draw=2;
}else{
image_1.setAlpha(255);
layout_front.setBackground(image_1);
image_2.setAlpha(255);
layout_behind.setBackground(image_2);
switch_draw=0;
}
a=255;
start();//loop stuff
}
}.start();
}
public void StartOnClick(View v){
//do something when the button is clicked
if(v.getId()==R.id.button1){
/---/
}else if(v.getId()==R.id.button2){
/---/
}else if(v.getId()==R.id.buttonw1){
/---/
}else if(v.getId()==R.id.buttonw2){
/---/
}else if(v.getId()==R.id.buttonw3){
/---/
}
}
private void setReset(){
/---/ //clear all
}
private void againRestart(){
/---/ //reset entries only
}
// main Method
private void numInput(){
int[][]found;
int n = 81;
int mini=1;
while(mini==1 && n>0){
TextView text;
Button but1;
int[][]nul=new int[2][81];
int[][]value=new int[3][81];
int i=-1;
int j=-1;
int a=0;
int b=0;
for(int idN=0; idN<81; idN++) {
int iDn=idN +1;
String editTextId = "editText" + iDn;
int resID = getResources().getIdentifier(editTextId, "id",
getPackageName());
sumNum=((EditText)findViewById(resID) );
if(idN%9 == 0){
i=i+1;
j=0;
}else{
j=j+1;
}if(!TextUtils.isDigitsOnly(sumNum.getText()) ||
sumNum.getText ().toString().equals("0") ){
sumNum.setText("");
}
if(sumNum.getText().toString().trim().length()==0){
matrix[i][j]= 0;
nul[0][a]=i;
nul[1][a]=j;
a=a+1;
}else {
matrix[i][j] = Integer.parseInt(sumNum.getText().toString());
value[0][b]=i;
value[1][b]=j;
value[2][b]=matrix[i][j];
b=b+1;
}
}
//copy array
int[][]nuL=new int[2][a];
int[][]val=new int[3][b];
for(int u=0;u<b;u++){
val[0][u]=value[0][u];
val[1][u]=value[1][u];
val[2][u]=value[2][u];
}
for(int nu=0;nu<a;nu++){
nuL[0][nu]=nul[0][nu];
nuL[1][nu]=nul[1][nu];
}
n = nuL[0].length;
// matrix check
if(MathThing.matrixIsGood(val) && n>0){
//method matrixCheck
found = MathThing.matrixCheck(matrix, nuL);
//cut method
found = MathThing.zeroCut(found, n);
// method
int[] min = MathThing.minSearch(found);
mini = min[0];
if(min[0]==1 && n>0) {
/---/
}else if(min[0]==2 && n>0 ){
/---/
}else if(min[0]>2 && n>0 || n==81){
/---/
}else if(min[0]==0 && n>0) {
/---/
}}else if(n!=0){
/---/
}
if(n==0){
/---/
}
}
}

How do I make my ArrayList<ColorSaver> persistent in android?

I have the ArrayList...
ArrayList<ColorSaver> tempList = new ArrayList<ColorSaver>();
and I want it so that when the user closes the app or leaves the app, all the ColorSaver objects in the ArrayList will be there when the user reopens the app. I would prefer to use the SharedPreferences but I can't do that because the list is a custom object...
I have looked around and found out that I can do a serializable but I tried that and failed horribly, so if somebody could guide me through the serializable deal that would be great. Oh and where do I put the code, like in onCreate() in my mainActivity or in the activity that is displaying the ArrayList
My mainActivity class
public class MainActivity extends Activity {
ArrayList<ColorSaver> tempList = new ArrayList<ColorSaver>();
private static final String TAG = "Main Activity";
public static final String PREFS_NAME = "MyPrefsFile";
final Intent intent = new Intent();
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
final NumberPicker rednp = (NumberPicker) findViewById(R.id.redNumberPicker1);
final NumberPicker bluenp = (NumberPicker) findViewById(R.id.blueNumberPicker);
final NumberPicker greennp = (NumberPicker) findViewById(R.id.greenNumberPicker);
switch(item.getItemId())
{
case R.id.save:
Log.i(TAG, "Save item clicked!");
Intent intent = new Intent(this, SaveActivity.class);
intent.putExtra("RedValue", rednp.getValue());
intent.putExtra("BlueValue", bluenp.getValue());
intent.putExtra("GreenValue", greennp.getValue());
intent.putExtra("temparray", tempList);
startActivity(intent);
return true;
case R.id.recall:
Log.i(TAG, "Recall item clicked!");
Intent intent2 = new Intent(this, RecallActivity.class);
intent2.putExtra("temparray", tempList);
startActivity(intent2);
return true;
default:
return super.onOptionsItemSelected(item);
}//End Switch
}
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//ArrayList<ColorSaver> tempList = new ArrayList<ColorSaver>();
Bundle extras = getIntent().getExtras();
final SurfaceView sView = (SurfaceView) findViewById(R.id.surfaceView1);
final NumberPicker np = (NumberPicker) findViewById(R.id.redNumberPicker1);
np.setMaxValue(255);
np.setMinValue(0);
final NumberPicker np2 = (NumberPicker) findViewById(R.id.greenNumberPicker);
np2.setMaxValue(255);
np2.setMinValue(0);
final NumberPicker np3 = (NumberPicker) findViewById(R.id.blueNumberPicker);
np3.setMaxValue(255);
np3.setMinValue(0);
if( extras != null )
{
np.setValue(extras.getInt("savedRValue"));
//np.setValue(intent.getIntExtra("savedRValue", 255));
np2.setValue(extras.getInt("savedGValue"));
//np2.setValue(intent.getIntExtra("savedGValue", 255));
np3.setValue(extras.getInt("savedBValue"));
//np3.setValue(intent.getIntExtra("savedBValue", 255));
tempList = (ArrayList<ColorSaver>) extras.getSerializable("array");
sView.setBackgroundColor(Color.argb(255, np.getValue(), np2.getValue(), np3.getValue()));
}
else
{
Log.i(TAG, "I just don't get it...WTF");
}
np.setOnValueChangedListener( new NumberPicker.
OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal)
{
int rednum, greennum, bluenum;
rednum = np.getValue();
greennum = np2.getValue();
bluenum = np3.getValue();
sView.setBackgroundColor(Color.argb(255, rednum, greennum, bluenum));
}
});
//GREEN NUMBERPICKER LISTENER
np2.setOnValueChangedListener( new NumberPicker.
OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal)
{
int rednum, greennum, bluenum;
rednum = np.getValue();
greennum = np2.getValue();
bluenum = np3.getValue();
sView.setBackgroundColor(Color.argb(255, rednum, greennum, bluenum));
}
});
np3.setOnValueChangedListener( new NumberPicker.
OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal)
{
int rednum, greennum, bluenum;
rednum = np.getValue();
greennum = np2.getValue();
bluenum = np3.getValue();
sView.setBackgroundColor(Color.argb(255, rednum, greennum, bluenum));
}
});
}//End onCreate()
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}//END onCreateOptionsMenu()
}//END CLASS
My saveActivity, where the user saves their color combo to the ArrayList...
public class SaveActivity extends Activity implements Serializable {
private static final String TAG = "Save Activity";
public ArrayList<ColorSaver> savedColors = new ArrayList<ColorSaver>();
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save);
// Show the Up button in the action bar.
setupActionBar();
Bundle extras = getIntent().getExtras();
final Intent intent1 = new Intent(this, MainActivity.class);
Button saveButton = (Button) findViewById(R.id.saveButton1);
final EditText nameField = (EditText) findViewById(R.id.colorNameField);
//final Intent intent = new Intent();
savedColors = (ArrayList<ColorSaver>) extras.getSerializable("temparray");
//Making sure the savedColors arrayList has something in it.
if( savedColors.isEmpty() )
{
ColorSaver temp = new ColorSaver("Rockies Purple", 180, 80, 255);
savedColors.add(temp);
}
saveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Bundle extras = getIntent().getExtras();
int redcolor, greencolor, bluecolor;
redcolor = extras.getInt("RedValue");
greencolor = extras.getInt("GreenValue");
bluecolor = extras.getInt("BlueValue");
String colorName = nameField.getText().toString();
//Build the new color and add it to the arrayList
ColorSaver saver = new ColorSaver(colorName, redcolor, greencolor, bluecolor);
savedColors.add(saver);
intent1.putExtra("array", savedColors);
Log.i(TAG, savedColors.get(savedColors.size()-1).getColorName());
startActivity(intent1);
}
});
}//END OnCreate()
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.save, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}//END CLASS
My recallActivity where the user recalls their color combos...
public class RecallActivity extends SaveActivity {
private static final String TAG = "Recall Activity";
ArrayList<ColorSaver> colorsArray = new ArrayList<ColorSaver>();
SaveActivity sActivity = new SaveActivity();
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recall);
// Show the Up button in the action bar.
setupActionBar();
final Intent intent1 = new Intent(this, MainActivity.class);
final Spinner colorList = (Spinner) findViewById(R.id.colorsSpinner);
Button grabButton = (Button) findViewById(R.id.grabButton);
Bundle extras = getIntent().getExtras();
colorsArray = (ArrayList<ColorSaver>) extras.getSerializable("temparray");
//Load the spinner with the saved colors
addColorNames(colorsArray);
grabButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
ColorSaver selectedItem = (ColorSaver) colorList.getSelectedItem();
int redValue, greenValue, blueValue;
String name;
redValue = selectedItem.getRedValue();
greenValue = selectedItem.getGreenValue();
blueValue = selectedItem.getBlueValue();
name = selectedItem.getColorName();
intent1.putExtra("savedRValue", redValue);
intent1.putExtra("savedGValue", greenValue);
intent1.putExtra("savedBValue", blueValue);
intent1.putExtra("savedName", name);
intent1.putExtra("array", colorsArray);
startActivity(intent1);
}//END onClick
});
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.recall, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}// END onOptionsItemSelected(MenuItem item)
public void addColorNames(ArrayList<ColorSaver> colorsArray1)
{
colorsArray = colorsArray1;
//if( !colorsArray.isEmpty() )
//{
Spinner colorsSpinner = (Spinner) findViewById(R.id.colorsSpinner);
ArrayAdapter<ColorSaver> dataAdapter
= new ArrayAdapter<ColorSaver>
(RecallActivity.this, android.R.layout.simple_spinner_item, colorsArray);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
colorsSpinner.setAdapter(dataAdapter);
Log.i(TAG, savedColors.get(savedColors.size() - 1).toString());
//}
//else
//{
// Log.i(TAG, "colorsSpinner came out to be null....WTF???");
//}
}//End addColorNames()
}//END CLASS
I am greatful of any help!
Take a look at Android's Parcelable implementation.
So, I'm just guessing on your ColorSaver class since it wasn't posted, but you would implement it the following way:
ColorSaver.java
public class ColorSaver implements Parcelable {
private String mName;
private int mRed;
private int mGreen;
private int mBlue;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeString(mName);
out.writeInt(mRed);
out.writeInt(mGreen);
out.writeInt(mBlue);
}
public static final Parcelable.Creator<ColorSaver> CREATOR
= new Parcelable.Creator<ColorSaver>() {
public ColorSaver createFromParcel(Parcel in) {
return new ColorSaver(in);
}
public ColorSaver[] newArray(int size) {
return new ColorSaver[size];
}
};
private ColorSaver(Parcel in) {
mName = in.readString();
mRed = in.readInt();
mGreen = in.readInt();
mBlue = in.readInt();
}
}
MyActivity.java
public class MyActivity extends Activity {
private static final String COLOR_SAVER_LIST = "com.example.android.ColorSaverList";
private List<ColorSaver> colorSaverList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null && savedInstanceState.containsKey(COLOR_SAVER_LIST)) {
colorSaverList = new ArrayList<ColorSaver>();
colorSaverList = savedInstanceState.getParcelableArrayList(COLOR_SAVER_LIST);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(COLOR_SAVER_LIST, colorSaverList);
}
}

Saving Option Menu Shared Preferences

I have a option menu. When the activity loses focus, the selected option menu item(s) retain state, but when my activity is destroyed, all the options are reset.
How can I save the state of the selected preference after resuming from a destroyed state? Having problem visualizing how to implement Shared Preferences for the code.
(Only needed for the boolean values but I have included the static menu items.)
public final static int MENU_SOMETHING_MODE_ON = 1;
public final static int MENU_SOMETHING_MODE_OFF = 2;
public final static int MENU_FULLSCREEN_ON = 3;
public final static int MENU_FULLSCREEN_OFF = 4;
public final static int MENU_SOUND_ON = 5;
public final static int MENU_SOUND_OFF = 6;
public final static int MENU_FASTER = 7;
public final static int MENU_SLOWER = 8;
public final static int MENU_SOMETHING = 9;
public final static int MENU_EXTRAS = 10;
private static boolean soundOn = true;
private static boolean mFaster = true;
private boolean fullscreen = true;
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_SOMETHING, 0, R.string.menu_new_something);
menu.add(0, MENU_SOMETHING_MODE_ON, 0,
R.string.menu_something_on);
menu.add(0, MENU_SOMETHING_MODE_OFF, 0,
R.string.menu_something_off);
menu.add(0, MENU_FULLSCREEN_ON, 0, R.string.menu_fullscreen_on);
menu.add(0, MENU_FULLSCREEN_OFF, 0, R.string.menu_fullscreen_off);
menu.add(0, MENU_SOUND_ON, 0, R.string.menu_sound_on);
menu.add(0, MENU_SOUND_OFF, 0, R.string.menu_sound_off);
menu.add(0, MENU_FASTER, 0, R.string.menu_faster);
menu.add(0, MENU_SLOWER, 0, R.string.menu_slower);
menu.add(0, MENU_EXTRAS, 0, R.string.menu_extras);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
super.onPrepareOptionsMenu(menu);
menu.findItem(MENU_SOUND_ON).setVisible(!getSoundOn());
menu.findItem(MENU_SOUND_OFF).setVisible(getSoundOn());
menu.findItem(MENU_SOMETHING_ON).setVisible(
getMode() == SOMETHING_NORMAL);
menu.findItem(MENU_SOMETHING_OFF).setVisible(
getMode() != SOMETHING_NORMAL);
menu.findItem(MENU_FULLSCREEN_ON).setVisible(!fullscreen);
menu.findItem(MENU_FULLSCREEN_OFF).setVisible(fullscreen);
menu.findItem(MENU_FASTER).setVisible(getFaster());
menu.findItem(MENU_SLOWER).setVisible(!getFaster());
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {
case MENU_SOMETHING:
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setMessage("Are you sure?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'YES' Button
something.new();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("Something");
// Icon for AlertDialog
alert.setIcon(R.drawable.dialog);
alert.show();
return true;
case MENU_SOMETHING_ON:
setMode(THIS_SOMETHING);
return true;
case MENU_SOMETHING_OFF:
setMode(THIS_NORMAL);
return true;
case MENU_FULLSCREEN_ON:
fullscreen = true;
setFullscreen();
return true;
case MENU_FULLSCREEN_OFF:
fullscreen = false;
setFullscreen();
return true;
case MENU_SOUND_ON:
setSoundOn(true);
return true;
case MENU_SOUND_OFF:
setSoundOn(false);
return true;
case MENU_FASTER:
setFaster(false);
return true;
case MENU_SLOWER:
setSlower(true);
return true;
case MENU_EXTRAS:
startExtras();
return true;
}
return false;
}
private void setFullscreen()
{
if (fullscreen) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().addFlags(
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
}
mView.requestLayout();
}
public synchronized static void setMode(int newMode)
{
Mode = newMode;
}
public synchronized static int getMode()
{
return Mode;
}
public synchronized static boolean getSoundOn()
{
return soundOn;
}
public synchronized static void setSoundOn(boolean so)
{
soundOn = so;
}
public synchronized static boolean getFaster()
{
return Faster;
}
public synchronized static void setFaster(boolean dont)
{
Faster = dont;
}
This is a fantastic tutorial on how to create a preference activity along with how to get/set these preferences. It will also show you how to use shared preferences if you choose not to implement a preference activity.
Almost all users are familiar with a preference activity because it is how they adjust settings on their phone.
While not the only way to implement "options," or possibly perhaps not even the best way, it works great, has a ton of flexibility, and is simple and quick to implement.

Categories

Resources