in java code using savedInstanceState to save a reusable value - java

I am developing an android app and want to save a rand2(Double type) value using savedInstanceState so that i can use rand2 value whenever app is reopened but while retrieving rand2 value it always comes NULL, Either the value is not saving or value is not retrieving . Why it is happening and what should i do to save rand2 value so that i can reuse it when the app is reopened?
public class MainActivity extends AppCompatActivity {
double rand2;
private boolean started = false;
private Handler handler = new Handler();
public Runnable runnable = new Runnable() {
#Override
public void run() {
double rand1 = Math.random() * 5;
rand2 = rand2 + rand1 * 0.04;
DecimalFormat df = new DecimalFormat("0.00");
String message1 = "" + df.format(rand1);
DecimalFormat dff = new DecimalFormat("000000.00");
String message2 = "" + dff.format(rand2);
displayRate(message1);
displaySatoshi(message2);
if (started) {
start(started);
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// recovering the instance state
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
if (savedInstanceState != null) {
rand2 = savedInstanceState.getDouble("abc");
} else {
rand2 = 0.00;
}
setContentView(R.layout.activity_main);
// Find the View that shows the numbers category
TextView numbers = (TextView) findViewById(withdraw);
// Set a click listener on that View
numbers.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View view) {
Intent numbersIntent = new Intent(MainActivity.this, Withdraw.class);
startActivity(numbersIntent);
}
});
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putDouble("abc", rand2);
// call superclass to save any view hierarchy
super.onSaveInstanceState(savedInstanceState);
}
public void Start(View v) {
ToggleButton starStopTogglrButton = (ToggleButton) findViewById(R.id.start_stop);
boolean hasStartStop = starStopTogglrButton.isChecked();
if (hasStartStop) {
start(hasStartStop);
} else {
stop(hasStartStop);
}
}
public void stop(Boolean hasStartStop) {
//Checking start or stop
started = hasStartStop;
handler.removeCallbacks(runnable);
}
public void start(Boolean hasStartStop) {
started = hasStartStop;
handler.postDelayed(runnable, 1000);
}
private void displayRate(String message1) {
TextView orderSummaryTextView = (TextView) findViewById(R.id.rate);
orderSummaryTextView.setText(message1);
}
private void displaySatoshi(String message2) {
TextView orderSummaryView = (TextView) findViewById(R.id.satoshis);
orderSummaryView.setText(message2);
}
}

onSaveInstanceState is called when the app is closed, but onCreate is only called when the app is booted after it's been finished. Remember the acitvity lifecycle:
So since onSaveInstanceState is called at closing and onCreate only is called when the activity is (re)created, it is null because it isn't added at that time.
You're looking for onRestoreInstanceState. Override that method and grab the variable and assign it from there.
Remember that using the savedInstanceState does not save the data if the activity is completely destroyed. For persistent data storage, use sharedprefs, files or SQL

Related

how to show a dialog after 1 or 2 min after opning app for first time

I want to show a custom XML dialog dialogue that will appear after a specific time in the first run, let's say after a min
how can I do it
but I'm confused about what should I do in a situation like below
if the user open the app for the first time and just spent 30 sec and just pause the app(screen lock or in onPause) or just close the app completely
Just as a note - I have already implemented a one time show dialog(directly in main activity without any layout file ) when the app runs for the first time already
Code
To view the already implemented dialog(shows up on the first run) please
go to the // Caution dialog (showDialog method)
MainActivity.java
public class MainActivity extends AppCompatActivity {
MediaPlayer player1;
MediaPlayer player2;
SeekBar seekBar1;
SeekBar seekBar2;
TextView elapsedTimeLable1;
TextView elapsedTimeLable2;
TextView remainingTimeLable1;
TextView remainingTimeLable2;
ImageView play1;
ImageView play2;
int totalTime1;
#SuppressLint("HandlerLeak")
private final Handler handler1 = new Handler() {
#SuppressLint("SetTextI18n")
#Override
public void handleMessage(#NonNull Message msg) {
int currentPosition1 = msg.what;
//Update SeekBar
seekBar1.setProgress(currentPosition1);
// Update Timelable
String elapsedTime1 = createTimerLable1(currentPosition1);
elapsedTimeLable1.setText(elapsedTime1);
String remainingTime1 = createTimerLable1(totalTime1 - currentPosition1);
remainingTimeLable1.setText("- " + remainingTime1);
}
};
int totalTime2;
#SuppressLint("HandlerLeak")
private final Handler handler2 = new Handler() {
#SuppressLint("SetTextI18n")
#Override
public void handleMessage(#NonNull Message msg) {
int currentPosition2 = msg.what;
// Update SeekBar
seekBar2.setProgress(currentPosition2);
// Update Timelable
String elapsedTime2 = createTimerLable2(currentPosition2);
elapsedTimeLable2.setText(elapsedTime2);
String remainingTime2 = createTimerLable2(totalTime2 - currentPosition2);
remainingTimeLable2.setText("- " + remainingTime2);
}
};
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#SuppressLint("ObsoleteSdkInt")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window w = getWindow();
// clear FLAG_TRANSLUCENT_STATUS flag:
w.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
w.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
// finally change the color
w.setStatusBarColor(ContextCompat.getColor(this, R.color.Card_Elevation_Color));
}
// PlayButton * The ButtonClick is in the last if you want to jump directly there *
play1 = findViewById(R.id.playbtn1);
play2 = findViewById(R.id.playbtn2);
// TimeLables
elapsedTimeLable1 = findViewById(R.id.cTime1);
elapsedTimeLable2 = findViewById(R.id.cTime2);
remainingTimeLable1 = findViewById(R.id.tTime1);
remainingTimeLable2 = findViewById(R.id.tTime2);
// MediaPlayer
player1 = MediaPlayer.create(this, R.raw.dog_howl);
player1.setLooping(true);
player1.seekTo(0);
totalTime1 = player1.getDuration();
player2 = MediaPlayer.create(this, R.raw.dog_bark);
player2.setLooping(true);
player2.seekTo(0);
totalTime2 = player2.getDuration();
//SeekBar
seekBar1 = findViewById(R.id.seekbar1);
seekBar2 = findViewById(R.id.seekbar2);
seekBar1.setMax(totalTime1);
seekBar2.setMax(totalTime2);
seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress1, boolean fromUser1) {
if (fromUser1) {
player1.seekTo(progress1);
seekBar1.setProgress(progress1);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
seekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress2, boolean fromUser2) {
if (fromUser2) {
player2.seekTo(progress2);
seekBar2.setProgress(progress2);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
// Thread (Update SeekBar & TimeLabel)
new Thread(() -> {
while (player1 != null) {
try {
Message msg = new Message();
msg.what = player1.getCurrentPosition();
handler1.sendMessage(msg);
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
}
}).start();
new Thread(() -> {
while (player2 != null) {
try {
Message msg = new Message();
msg.what = player2.getCurrentPosition();
handler2.sendMessage(msg);
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
}
}).start();
// Admob Banner Ad
MobileAds.initialize(this, initializationStatus -> {
});
AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
// Caution dialog
SharedPreferences preferences = getSharedPreferences("prefs", MODE_PRIVATE);
boolean firstStart = preferences.getBoolean("firstStart", true);
if (firstStart) {
showDialog();
}
}
// Caution dialog
private void showDialog() {
new AlertDialog.Builder(this)
.setTitle("Caution!")
.setMessage("In case you're wearing any kind of headphones please remove it before playing the ' Howl ' audio")
.setPositiveButton("ok", (dialogInterface, i) -> dialogInterface.dismiss())
.create().show();
SharedPreferences preferences = getSharedPreferences("prefs", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("firstStart", false);
editor.apply();
}
public String createTimerLable1(int duration) {
String timerLabel1 = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel1 += min + ":";
if (sec < 10) timerLabel1 += "0";
timerLabel1 += sec;
return timerLabel1;
}
public String createTimerLable2(int duration) {
String timerLabel2 = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel2 += min + ":";
if (sec < 10) timerLabel2 += "0";
timerLabel2 += sec;
return timerLabel2;
}
public void playBtnClick1(View view) {
if (player2.isPlaying()) {
player2.pause();
play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
if (!player1.isPlaying()) {
// Stoping
player1.start();
play1.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
} else {
// Playing
player1.pause();
play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
}
public void playBtnClick2(View view) {
if (player1.isPlaying()) {
player1.pause();
play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
if (!player2.isPlaying()) {
// Stoping
player2.start();
play2.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
} else {
// Playing
player2.pause();
play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
}
#Override
protected void onPause() {
super.onPause();
if (player1 != null) {
player1.pause();
play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
if (player2 != null) {
player2.pause();
play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
}
}
but I'm confused about what should I do in a situation like below
if the user open the app for the first time and just spent 30 sec and just pause the app(screen lock or in onPause) or just close the
app completely
This is impossible to do if your app is closed.My suggestion would be to create a service on another process that does this dialog such that even if the app process is closed,the service process will still be running unless it is stopped explicitly.
Defining a Process of a Service
The android:process field defines the name of the process where the
service is to run. Normally, all components of an application run in
the default process created for the application. However, a component
can override the default with its own process attribute, allowing you
to spread your application across multiple processes.
If the name assigned to this attribute begins with a colon (':'), the
service will run in its own separate process.
<service android:name="com.example.appName" android:process=":externalProcess" />
This is of course in the manifest file .
You might also need to show a system dialog thus you will need a system Alert Window permission i your manifest and request for the permision on runtime.
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
Then on runtime request like this:
public static void openOverlaySettings(Activity activity) {
final Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + activity.getPackageName()));
try {
activity.startActivityForResult(intent, 6);
} catch (ActivityNotFoundException e) {
Log.e("Drawers permission :", e.getMessage());
}
}
To check if granted use :
if(!Settings.canDrawOverlays(context)) {
openOverlaySettings(context);
ok=false;
}
Then in your service you should create the dialog like below
View aldv= LayoutInflater.from(act).inflate(R.layout.your_layout,null);
ald=new AlertDialog.Builder(act,R.style.AppTheme)
.setView(aldv)
.setCancelable(true)
.create();
ald.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);

malfunction of an instance

The goal is to implement the following functionality. Three EditText fields. Each of them should be filled with its custom keyboard.
1. English
2. Russian
3. transcription
Keyboards I implemented with the help of this class
public class CustomKeyboard {
/** A link to the KeyboardView that is used to render this CustomKeyboard. */
private KeyboardView mKeyboardView;
/** A link to the activity that hosts the {#link #mKeyboardView}. */
private Activity mHostActivity;
/** The key (code) handler. */
private OnKeyboardActionListener mOnKeyboardActionListener = new OnKeyboardActionListener() {
public final static int CodeDelete = -5; // Keyboard.KEYCODE_DELETE
public final static int CodeCancel = -3; // Keyboard.KEYCODE_CANCEL
public final static int CodePrev = 55000;
public final static int CodeAllLeft = 55001;
public final static int CodeLeft = 55002;
public final static int CodeRight = 55003;
public final static int CodeAllRight = 55004;
public final static int CodeNext = 55005;
public final static int CodeClear = 55006;
#Override public void onKey(int primaryCode, int[] keyCodes) {
// NOTE We can say '<Key android:codes="49,50" ... >' in the xml file; all codes come in keyCodes, the first in this list in primaryCode
// Get the EditText and its Editable
View focusCurrent = mHostActivity.getWindow().getCurrentFocus();
if( focusCurrent==null || focusCurrent.getClass()!=EditText.class ) return;
EditText edittext = (EditText) focusCurrent;
Editable editable = edittext.getText();
int start = edittext.getSelectionStart();
// Apply the key to the edittext
if( primaryCode==CodeCancel ) {
hideCustomKeyboard();
} else if( primaryCode==CodeDelete ) {
if( editable!=null && start>0 ) editable.delete(start - 1, start);
} else if( primaryCode==CodeClear ) {
if( editable!=null ) editable.clear();
} else if( primaryCode==CodeLeft ) {
if( start>0 ) edittext.setSelection(start - 1);
} else if( primaryCode==CodeRight ) {
if (start < edittext.length()) edittext.setSelection(start + 1);
} else if( primaryCode==CodeAllLeft ) {
edittext.setSelection(0);
} else if( primaryCode==CodeAllRight ) {
edittext.setSelection(edittext.length());
} else if( primaryCode==CodePrev ) {
View focusNew= edittext.focusSearch(View.FOCUS_BACKWARD);
if( focusNew!=null ) focusNew.requestFocus();
} else if( primaryCode==CodeNext ) {
View focusNew= edittext.focusSearch(View.FOCUS_FORWARD);
if( focusNew!=null ) focusNew.requestFocus();
} else { // insert character
editable.insert(start, Character.toString((char) primaryCode));
}
}
#Override public void onPress(int arg0) {
}
#Override public void onRelease(int primaryCode) {
}
#Override public void onText(CharSequence text) {
}
#Override public void swipeDown() {
}
#Override public void swipeLeft() {
}
#Override public void swipeRight() {
}
#Override public void swipeUp() {
}
};
/**
* Create a custom keyboard, that uses the KeyboardView (with resource id <var>viewid</var>) of the <var>host</var> activity,
* and load the keyboard layout from xml file <var>layoutid</var> (see {#link Keyboard} for description).
* Note that the <var>host</var> activity must have a <var>KeyboardView</var> in its layout (typically aligned with the bottom of the activity).
* Note that the keyboard layout xml file may include key codes for navigation; see the constants in this class for their values.
* Note that to enable EditText's to use this custom keyboard, call the {#link #registerEditText(int)}.
*
* #param host The hosting activity.
* #param viewid The id of the KeyboardView.
* #param layoutid The id of the xml file containing the keyboard layout.
*/
public CustomKeyboard(Activity host, int viewid, int layoutid) {
mHostActivity= host;
mKeyboardView= (KeyboardView)mHostActivity.findViewById(viewid);
mKeyboardView.setKeyboard(new Keyboard(mHostActivity, layoutid));
mKeyboardView.setPreviewEnabled(false); // NOTE Do not show the preview balloons
mKeyboardView.setOnKeyboardActionListener(mOnKeyboardActionListener);
// Hide the standard keyboard initially
mHostActivity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
/** Returns whether the CustomKeyboard is visible. */
public boolean isCustomKeyboardVisible() {
return mKeyboardView.getVisibility() == View.VISIBLE;
}
/** Make the CustomKeyboard visible, and hide the system keyboard for view v. */
public void showCustomKeyboard( View v ) {
mKeyboardView.setVisibility(View.VISIBLE);
mKeyboardView.setEnabled(true);
if( v!=null ) ((InputMethodManager)mHostActivity.getSystemService(Activity.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(v.getWindowToken(), 0);
}
/** Make the CustomKeyboard invisible. */
public void hideCustomKeyboard() {
mKeyboardView.setVisibility(View.GONE);
mKeyboardView.setEnabled(false);
}
/**
* Register <var>EditText<var> with resource id <var>resid</var> (on the hosting activity) for using this custom keyboard.
*
* #param resid The resource id of the EditText that registers to the custom keyboard.
*/
public void registerEditText(int resid) {
// Find the EditText 'resid'
//TextInputEditText edittext= (TextInputEditText)mHostActivity.findViewById(resid);
EditText edittext= (EditText)mHostActivity.findViewById(resid);
// Make the custom keyboard appear
edittext.setOnFocusChangeListener(new OnFocusChangeListener() {
// NOTE By setting the on focus listener, we can show the custom keyboard when the edit box gets focus, but also hide it when the edit box loses focus
#Override public void onFocusChange(View v, boolean hasFocus) {
if( hasFocus ) showCustomKeyboard(v); else hideCustomKeyboard();
}
});
edittext.setOnClickListener(new OnClickListener() {
// NOTE By setting the on click listener, we can show the custom keyboard again, by tapping on an edit box that already had focus (but that had the keyboard hidden).
#Override public void onClick(View v) {
showCustomKeyboard(v);
}
});
// Disable standard keyboard hard way
// NOTE There is also an easy way: 'edittext.setInputType(InputType.TYPE_NULL)' (but you will not have a cursor, and no 'edittext.setCursorVisible(true)' doesn't work )
edittext.setOnTouchListener(new OnTouchListener() {
#Override public boolean onTouch(View v, MotionEvent event) {
EditText edittext = (EditText) v;
int inType = edittext.getInputType(); // Backup the input type
edittext.setInputType(InputType.TYPE_NULL); // Disable standard keyboard
edittext.onTouchEvent(event); // Call native handler
edittext.setInputType(inType); // Restore input type
return true; // Consume touch event
}
});
// Disable spell check (hex strings look like words to Android)
edittext.setInputType(edittext.getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
}
}
and three different xml-layouts
The Activity I create three copies keyboard class. With different layouts. Register each of them their field.
public class WordsListActivity extends Activity {
public static final String LOG_TAG = "WordsListActivity";
protected RecyclerView mRecyclerView;
protected Button btnAddWord;
protected WordViewAdapter mAdapter;
protected RecyclerView.LayoutManager mLayoutManager;
protected WordsListActivity.LayoutManagerType mCurrentLayoutManagerType;
protected List<Word> wordsList;
protected int categoryId;
protected CustomKeyboard mCustomKeyboardEN, mCustomKeyboardRU, mCustomKeyboardTrancroption;
protected ForegroundLinearLayout addWordLyout;
protected Button okButton, cancelButton;
protected EditText etWordOrigin, etWordTranslate, etWordTranscription;
private enum LayoutManagerType {
GRID_LAYOUT_MANAGER,
LINEAR_LAYOUT_MANAGER
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_words_list);
Intent intent = getIntent();
categoryId = (int) intent.getLongExtra("categoryId",0);
View rootView = getLayoutInflater().inflate(R.layout.content_main, null).getRootView();
mRecyclerView = (RecyclerView)findViewById(R.id.wrodsRecyclerView);
btnAddWord = (Button)findViewById(R.id.btnAddNewWord);
mLayoutManager = new LinearLayoutManager(this);
mCurrentLayoutManagerType = WordsListActivity.LayoutManagerType.LINEAR_LAYOUT_MANAGER;
setRecyclerViewLayoutManager(mCurrentLayoutManagerType);
addWordLyout =(ForegroundLinearLayout)findViewById(R.id.inputWordLayout);
addWordLyout.setVisibility(View.INVISIBLE);
etWordOrigin = (EditText)findViewById(R.id.etWordOrigin);
etWordTranslate = (EditText)findViewById(R.id.etWordTranslate);
etWordTranscription = (EditText)findViewById(R.id.etWordTrancription);
okButton = (Button) findViewById(R.id.addButton);
cancelButton = (Button) findViewById(R.id.cancelButton);
/* creting keybords*/
mCustomKeyboardRU = new CustomKeyboard(this, R.id.keyboardviewWords, R.xml.kbd_ru);//russian
mCustomKeyboardRU.registerEditText(R.id.etWordOrigin);
mCustomKeyboardEN = new CustomKeyboard(this, R.id.keyboardviewWords, R.xml.kbd_en);//english
mCustomKeyboardEN.registerEditText(R.id.etWordTranslate);
/*in all EditText field showing this last keyboard copy*/
mCustomKeyboardTrancroption = new CustomKeyboard(this, R.id.keyboardviewWords, R.xml.kbd_transcription);//transcription
mCustomKeyboardTrancroption.registerEditText(R.id.etWordTrancription);
btnAddWord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addWordLyout.setVisibility(View.VISIBLE);
}
});
}
#Override public void onBackPressed() {
// NOTE Trap the back key: when the CustomKeyboard is still visible hide it, only when it is invisible, finish activity
if( mCustomKeyboardRU.isCustomKeyboardVisible() ) mCustomKeyboardRU.hideCustomKeyboard(); else this.finish();
}
public void setRecyclerViewLayoutManager(WordsListActivity.LayoutManagerType layoutManagerType) {
/*
mLayoutManager = new GridLayoutManager(this, SPAN_COUNT);
mCurrentLayoutManagerType = LayoutManagerType.GRID_LAYOUT_MANAGER;*/
mLayoutManager = new LinearLayoutManager(this);
mCurrentLayoutManagerType = WordsListActivity.LayoutManagerType.LINEAR_LAYOUT_MANAGER;
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.scrollToPosition(0);
initDataset();
}
private void initDataset() {
wordsList = new DataBase(this).getWordsList(categoryId);
mAdapter = new WordViewAdapter(wordsList, this);
mRecyclerView.setAdapter(mAdapter);
if(wordsList.size()==0){
Toast.makeText(this, "nothing to Show", Toast.LENGTH_LONG).show();
}
}
}
but when you run applications with focus on all fields it shows the last keyboard. in this case transcription.

How do I iteratively add to a List on button click in java?

I want to add values to an array/list and then store these in shared preferences, to then display on another activity.
When I try my code it only seems to save the first value, and if I add more it just overwrites the value.
I do not want to create the List each time I click the button so I have put it at the very beginning.
If there isn't an existing value then the message should be added to the List and stored in shared preferences as Status_0, if there is an existing value then it should be added as Status_1 - but it's not. I think it is because it is not saving properly in the List but I'm not sure how to do that.
Here's my code:
public class EnterReadingsActivity extends AppCompatActivity implements View.OnClickListener {
private EditText erTemperatureEditText;
private Button erSubmitBtn;
public List<String> values = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utils.onActivityCreateSetTheme(this);
setContentView(R.layout.activity_enterreadings);
init();
}
private void init() {
erTemperatureEditText = (EditText) findViewById(R.id.erTemperatureEditText);
erSubmitBtn = (Button) findViewById(R.id.erSubmitBtn);
erSubmitBtn.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view.getId()==R.id.erSubmitBtn) {
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
String message = erTemperatureEditText.getText().toString();
editor.putInt("Status_size", values.size());
int status_size = values.size();
for (int i = status_size; i < status_size + 1; i++) {
editor.putString("Status_" + i, message);
values.add(message);
editor.commit();
}
}
}
}
Edit:
int status_size = values.size();
for(int i = 0; i < status_size + 1; i++)
{
String value = values.get(i);
if (value != null) {
values.add(value);
status_size++;
String textView_i = "textView" + i;
TextView textView_i = new TextView(this);
textView_i.setLayoutParams(new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.WRAP_CONTENT));
textView_i.setText(value);
historyBackgroundInside.addView(textView_i);
}
}
It is incorrect to use the sharedPreferences to pass data from one activity to another.
The data are usually entered into an object (Bundle) which will be passed in the intent and then taken up in the next activity.
another way is to use the extras that works like Bundle
public class EnterReadingsActivity extends AppCompatActivity implements View.OnClickListener {
private EditText erTemperatureEditText;
private Button erSubmitBtn;
public List<String> values = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utils.onActivityCreateSetTheme(this);
setContentView(R.layout.activity_enterreadings);
init();
}
private void init() {
erTemperatureEditText = (EditText) findViewById(R.id.erTemperatureEditText);
erSubmitBtn = (Button) findViewById(R.id.erSubmitBtn);
erSubmitBtn.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view.getId()==R.id.erSubmitBtn) {
String message = erTemperatureEditText.getText().toString();
values.add(message);
}
//Here you should enter the condition that allows you to
//call the method to go to the next activity
//ex: click of a button, I have the list reaches a size
//Add a example code
if (values.size() == 10) {
passDataAndGoInAnotherActivity();
}
}
public void passDataAndGoInAnotherActivity () {
Intent i = new Intent (this, NameOfYouNextActivity.class);
i.putExtra("status_list", values);
// Or use Bundle
// Bundle bundle = new Bundle();
// bundle.putSerializable("status_list", values);
// i.putExtra("bundle", values)
startActivity(i)
}
}
to take in the other activity values using this code
public class NameOfYourNextActivity extends AppCompatActivity {
public List<String> values;
public ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utils.onActivityCreateSetTheme(this);
setContentView(R.layout.activity_nameoflayout);
listview = (ListView) findViewById(R.id.listView);
Intent intent = getIntent();
//If you first method
if (intent != null && intent.hasExtra("status_list")) {
List<String> values = (List<String>)intent.getSerializableExtra("status_list")
}
//If you second method (Bundle)
// if (intent != null && intent.hasExtra("Bundle")) {
// Bundle bundle = intent. getBundleExtra("Bundle")
// if (bundle != null && bundle.containsKey("status_list")) {
// List<String> values = (List<String>)intent.getSerializableExtra(String name)
// }
if (values != null) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
listview.setAdapter(adapter);
}
}
}
I did the update of the code to give you a solution that comes close to what you need..
Remember to create the next activity and insert it in the manifest.
Change the name of the class based on your activity and enter the correct layout name.
Remember to include in your layout a list view (change id in my code) that will allow you to print your values.
In this example it uses a simple adapter with a layout provided by Android, but you can create something custom.
Here you will find an excellent guide

Application always calls onCreate() when the phone is locked and unlocked

Is there any way to save the state of the application because the application calls onCreate() everytime the android phone is locked. When I unlocked it, the app calls the onCreate() method and start again.. BTW my app is like text twist. When I unlock the screen a new word is shown, instead of the current one.. The score is also reset as well as the time.. How can I work on this? Please help.. It's still unanswered..
This is the whole code of my activity..
public class friend extends Activity {
//score
ScoreHandler scHandler;
Score sc;
int totalScore;
//words
//DatabaseHelper dbHelp;
DBHelper dbHelp;
public String randomWord;
//speech
protected static final int RESULT_SPEECH = 1;
private ImageButton btnSpeak;
private TextView txtText;
//shake
private SensorManager mSensorManager;
private ShakeEventListener mSensorListener;
//timer
private CountDownTimer countDownTimer;
private boolean timerHasStarted = false;
private TextView timeText;
private final long startTime = 180 * 1000;
private final long interval = 1 * 1000;
private long timeLeft;
private int gameScore;
private TextView shuffleView;
TextView scoreView;
//Animation
Animation myFadeInAnimation;
Animation myFadeOutAnimation;
Animation leftToRight;
//sliding
Button mCloseButton;
Button mOpenButton;
MultiDirectionSlidingDrawer mDrawer;
Context context;
static final String STATE_SCORE = "currentScore";
static final String STATE_WORD = "currentWord";
static final String STATE_TIME = "currentTime";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
gameScore = savedInstanceState.getInt(STATE_SCORE);
timeLeft = savedInstanceState.getLong(STATE_TIME);
randomWord = savedInstanceState.getString(STATE_WORD);
} else {
// Probably initialize members with default values for a new instance
}
setContentView(R.layout.friend);
leftToRight = AnimationUtils.loadAnimation(this, R.anim.left_to_right);
ImageButton next = (ImageButton) findViewById(R.id.nextround_game);
next.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setClass(friend.this, friend1.class);
startActivity(intent);
}
});
ImageButton giveUp = (ImageButton) findViewById(R.id.surrender_game);
giveUp.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setClass(friend.this, GameOverActivity.class);
startActivity(intent);
}
});
//score
//timer
timeText = (TextView) this.findViewById(R.id.timer);
countDownTimer = new MyCountDownTimer(startTime, interval);
timeText.setText(timeText.getText() + String.valueOf(startTime/1000));
countDownTimer.start();
timerHasStarted = true;
this.removeAll();
dbHelp = new DBHelper(this);
randomWord = dbHelp.random();
System.out.println(randomWord);
String wordCaps = randomWord.toUpperCase();
final String finalWord = shuffle(wordCaps);
shuffleView = (TextView) findViewById(R.id.jumble);
Typeface type = Typeface.createFromAsset(getAssets(),"fonts/American Captain.ttf");
shuffleView.setTypeface(type);
shuffleView.setText(finalWord);
//shake
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorListener = new ShakeEventListener();
mSensorListener.setOnShakeListener(new ShakeEventListener.OnShakeListener() {
public void onShake() {
//String str = (String) stringList.remove(selectedWord);
String wordOutput = shuffle(finalWord);
TextView tv = (TextView) findViewById(R.id.jumble);
tv.setText(wordOutput);
}
});
//speech
txtText = (TextView) findViewById(R.id.txtText);
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(intent, RESULT_SPEECH);
txtText.setText("");
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(),
"Opps! Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT);
t.show();
}
}
});
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
timeText.setText("0:00");
playSound(R.raw.clock_whistle);
ImageView timeIsUp = (ImageView) findViewById(R.id.time_is_up);
timeIsUp.startAnimation(leftToRight);
}
#Override
public void onTick(long millisUntilFinished) {
long minutes = (millisUntilFinished / (1000*60)) % 60;
long seconds = (millisUntilFinished / 1000) % 60 ;
timeLeft = millisUntilFinished/1000;
timeText.setText("" + minutes + ":" + seconds );
if (timeLeft <= 10) {
playSound(R.raw.clock_beep);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtText.setText(text.get(0));
System.out.println(""+text.get(0));
String spoken = text.get(0);
if(dbHelp.exists(spoken)){
if(dbHelp.isLongest(spoken)){
Toast.makeText(getApplicationContext(), "You have guessed the longest word! ", Toast.LENGTH_SHORT).show();
}
gameScore = text.get(0).length()*10;
scoreView = (TextView) findViewById(R.id.scoreView);
scoreView.setText(""+gameScore);
scHandler = new ScoreHandler(this);
scHandler.addScore(new Score(1,gameScore));
int cumulativeScore = scHandler.accumulateScores();
scoreView.setText(""+cumulativeScore);
playSound(R.raw.correct);
WordGuessedHandler guessedWord = new WordGuessedHandler(this);
guessedWord.addGuessedWord(new Words(1,spoken));
ImageView img = (ImageView) findViewById(R.id.awesome);
myFadeInAnimation = AnimationUtils.loadAnimation(this, R.layout.fade_in);
myFadeOutAnimation = AnimationUtils.loadAnimation(this, R.layout.fade_out);
img.startAnimation(myFadeInAnimation);
img.startAnimation(myFadeOutAnimation);
}else{
playSound(R.raw.poweng);
ImageView image = (ImageView) findViewById(R.id.wrong);
myFadeInAnimation = AnimationUtils.loadAnimation(this, R.layout.fade_in);
myFadeOutAnimation = AnimationUtils.loadAnimation(this, R.layout.fade_out);
image.startAnimation(myFadeInAnimation);
image.startAnimation(myFadeOutAnimation);
}
}
}
}
}
public String shuffle(String input){
List<Character> characters = new ArrayList<Character>();
for(char c:input.toCharArray()){
characters.add(c);
}
StringBuilder output = new StringBuilder(input.length());
while(characters.size()!=0){
int randPicker = (int)(Math.random()*characters.size());
output.append(characters.remove(randPicker));
}
System.out.println(output.toString());
return output.toString();
}
#Override
public void onBackPressed()
{
Intent inMain=new Intent(friend.this, MainActivity.class);
inMain.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(inMain);
countDownTimer.cancel();
}
#Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(mSensorListener,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
}
#Override
protected void onPause() {
mSensorManager.unregisterListener(mSensorListener);
super.onStop();
}
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE,gameScore);
savedInstanceState.putLong(STATE_TIME,timeLeft);
savedInstanceState.putString(STATE_TIME,randomWord);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
gameScore = savedInstanceState.getInt(STATE_SCORE);
timeLeft = savedInstanceState.getLong(STATE_TIME);
randomWord = savedInstanceState.getString(STATE_WORD);
}
//sliding menu onChange
#Override
public void onContentChanged()
{
super.onContentChanged();
mOpenButton = (Button) findViewById( R.id.button_open );
mDrawer = (MultiDirectionSlidingDrawer) findViewById( R.id.drawer);
/* GridView gridView;
ArrayList ArrayofName = new ArrayList();
WordHandler db = new WordHandler(this);*/
TextView txt = (TextView) findViewById(R.id.text);
txt.setText("Hello There!");
GridView gridview = (GridView) findViewById(R.id.gridView1);
WordGuessedHandler guessed = new WordGuessedHandler(this);
List <WordGuessed> guessedList = guessed.getAllWordGuessed();
List<String> wordsList = new ArrayList<String>();
for(WordGuessed wg:guessedList){
wordsList.add(wg.getWord());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, wordsList);
gridview.setAdapter(adapter);
}
public void playSound(int sound) {
MediaPlayer mp = MediaPlayer.create(getBaseContext(), sound);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mp.setLooping(false);
mp.setVolume(1,1);
mp.start();
}
public void removeAll()
{
ScoreHandler scHandler = new ScoreHandler(this);
// db.delete(String tableName, String whereClause, String[] whereArgs);
// If whereClause is null, it will delete all rows.
SQLiteDatabase db = scHandler.getWritableDatabase(); // helper is object extends SQLiteOpenHelper
db.delete("scores_table", null, null);
db.close();
}
}
This question answers your question.
https://developer.android.com/training/basics/activity-lifecycle/index.html
Please use the onPause() and onResume() methods in your main Activity to solve this problem. If both method aren't defined, your app will go to the next methods in the lifecycle, which will be onCreate() and other methods. Read more here.
It is also possible to save your current instance by using onSaveInstance(Bundle b) and onRestoreInstance(Bundle b)
PS: someone has asked it earlier, and wrote a small example to use the onSaveInstance and onRestoreInstance (if you want to use it) here.

Android SQLite database seems to clear every time i open a new activity

I've been trying to fix these two bugs for a while and I feel like it has to do with a fundamental misunderstanding of what happens when I open up a new activity. Basically the program is a task management program. It works fine when I add new tasks without modifying the category, and the database updates fine and the main page of the application updates as I add new tasks to display these new tasks.
However, I recently added functionality for an "add categories" button. The purpose of this button is to open up a new listactivity that allows users to add new categories of tasks. Every time I open this from the task editing activity and then press the back button to get back to the main page, all of the tasks in the database get cleared. Wondering if anyone can tell me what's going on and why the data is getting wiped out.
here's the relevant code snippet from the front page (the list view showing all of the tasks:
private RemindersDbAdapter mDbHelper;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reminder_list);
mDbHelper = new RemindersDbAdapter(this);
mDbHelper.open();
fillData();
registerForContextMenu(getListView());
}
private void fillData() {
Cursor remindersCursor = mDbHelper.fetchAllReminders();
startManagingCursor(remindersCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{RemindersDbAdapter.KEY_TITLE};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.text1};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter reminders =
new SimpleCursorAdapter(this, R.layout.reminder_row, remindersCursor, from, to);
setListAdapter(reminders);
}
Here's some of the code for my task editing view (the one calling the activity for the category listing):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new RemindersDbAdapter(this);
//mCatDbHelper = new CategoriesDbAdapter(this);
setContentView(R.layout.reminder_edit);
mCalendar = Calendar.getInstance();
mTitleText = (EditText) findViewById(R.id.title);
//mBodyText = (EditText) findViewById(R.id.body);
mDateButton = (Button) findViewById(R.id.reminder_date);
mTimeButton = (Button) findViewById(R.id.reminder_time);
mLowPriorityButton = (Button) findViewById(R.id.low_priority);
mMedPriorityButton = (Button) findViewById(R.id.med_priority);
mHighPriorityButton = (Button) findViewById(R.id.high_priority);
mManageCategories = (Button) findViewById(R.id.manage_categories);
mSchoolRadio = (RadioButton)findViewById(R.id.radio_schoolwork);
mFamilyRadio = (RadioButton)findViewById(R.id.radio_family);
mOtherRadio = (RadioButton)findViewById(R.id.radio_other);
mContext = this;
priority = "Low";
category = "Other";
mConfirmButton = (Button) findViewById(R.id.confirm);
mRowId = savedInstanceState != null ? savedInstanceState.getLong(RemindersDbAdapter.KEY_ROWID)
: -1L;
registerButtonListenersAndSetDefaultText();
}
private void setRowIdFromIntent() {
if (mRowId == -1L) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(RemindersDbAdapter.KEY_ROWID)
: -1L;
}
}
#Override
protected void onPause() {
super.onPause();
mDbHelper.close();
}
#Override
protected void onResume() {
super.onResume();
mDbHelper.open();
setRowIdFromIntent();
//if(mRowId != -1L)
populateFields();
}
#Override
protected Dialog onCreateDialog(int id) {
switch(id) {
case DATE_PICKER_DIALOG:
return showDatePicker();
case TIME_PICKER_DIALOG:
return showTimePicker();
}
return super.onCreateDialog(id);
}
private void populateFields() {
// Only populate the text boxes and change the calendar date
// if the row is not null from the database.
if (mRowId != -1L) {
Cursor reminder = mDbHelper.fetchReminder(mRowId);
startManagingCursor(reminder);
mTitleText.setText(reminder.getString(
reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_TITLE)));
category = reminder.getString(reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_CATEGORY));
if(category.equals("School"))
mSchoolRadio.setChecked(true);
else if(category.equals("Family"))
mFamilyRadio.setChecked(true);
else
mOtherRadio.setChecked(true);
// Get the date from the database and format it for our use.
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
Date date = null;
try {
String dateString = reminder.getString(reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_DATE_TIME));
date = dateTimeFormat.parse(dateString);
mCalendar.setTime(date);
} catch (ParseException e) {
Log.e("ReminderEditActivity", e.getMessage(), e);
}
} else {
// This is a new task - add defaults from preferences if set.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String defaultTitleKey = getString(R.string.pref_task_title_key);
String defaultTimeKey = getString(R.string.pref_default_time_from_now_key);
String defaultTitle = prefs.getString(defaultTitleKey, null);
String defaultTime = prefs.getString(defaultTimeKey, null);
if(defaultTitle != null)
mTitleText.setText(defaultTitle);
if(defaultTime != null)
mCalendar.add(Calendar.MINUTE, Integer.parseInt(defaultTime));
}
updateDateButtonText();
updateTimeButtonText();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if(mRowId == -1L)
mRowId = -1L;
outState.putLong(RemindersDbAdapter.KEY_ROWID, mRowId);
}
/*
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
mRowId = savedInstanceState != null ? savedInstanceState.getLong(RemindersDbAdapter.KEY_ROWID)
: -1L;
}
*/
private void saveState() {
String title = mTitleText.getText().toString();
//String body = mBodyText.getText().toString();
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
String reminderDateTime = dateTimeFormat.format(mCalendar.getTime());
if (mRowId == -1L) {
long id = mDbHelper.createReminder(title, priority, category, reminderDateTime);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateReminder(mRowId, title, priority, category, reminderDateTime);
}
new ReminderManager(this).setReminder(mRowId, mCalendar);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
}
Here's the call (in the same class as the above code) to the new CategoryListActivity activity that's causing the problems:
mManageCategories.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(mContext, CategoryListActivity.class);
startActivity(i);
//populateFields();
}
});
I left out a lot of the less relevant code. Anyway like I said above... the main problem is that as soon as I start this new CategoryListActivity activity, the database and all the tasks get wiped out. weirdly, even if I restart the emulator the tasks don't get wiped as long as I don't start the CategoryListActivity. If anyone has any idea what's going on please help.
Andrew checkout this two links that will explain you everything about database integration.
http://www.devx.com/wireless/Article/40842/1954
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

Categories