Iam a new bee to android and I created a small app which should count number of days I attend the class and number of days I dont.But as soon as I kill the app and reopen the text in textview goes back to default
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
Button b1,b2,b3;
TextView tv1,tv2,tv3;
int i=0;
int j=0;
int nd=0;
Products products;
MyDBHandler myDBHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDBHandler = new MyDBHandler(MainActivity.this,null,null,1);
products = new Products("Present:"+i,"Absent:" + j,"Percentage" + nd + "%");
b1=(Button)findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);
b3=(Button)findViewById(R.id.calculate);
tv1=(TextView)findViewById(R.id.textView);
tv2=(TextView)findViewById(R.id.textView3);
tv3=(TextView)findViewById(R.id.percentage);
products.set_present("Present:"+i);
products.set_absent("Absent:" + j);
products.set_percentage("Percentage" + nd + "%");
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i++;
tv1.setText("Present:"+i);
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
j++;
tv2.setText("Absent:"+j);
}
});
b3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int dmator=i+j;
nd=(i*100)/dmator;
tv3.setText("Percentage:"+nd+"%");
if(nd>65)
Toast.makeText(MainActivity.this,"Chill you are safe",Toast.LENGTH_LONG).show();
if(nd<65)
Toast.makeText(MainActivity.this,"Attention youre attendance is less than 65",Toast.LENGTH_LONG).show();
}
});
}
}`//three buttons
//three text views
You can use Preference to save your data . Check if the app is running for first time or save a boo which check if any data was entered last time or not. Which ever way you like. Below is a short Preference class which I could come up with
public class PreferenceValues {
private boolean isFirstRun;
private String daysPresent;
private String daysAbsent;
private String percentage;
private Editor ed;
private static PreferenceValues mInstance = null;
private static SharedPreferences prefs;
private PreferenceValues(Context context) {
super();
}
/**
* Creating a singleton insatnce of the class
*
* #param ctx
* #return instance of the class
*/
public static PreferenceValues getInstance() {
Context ctx = MyApplication.getInstance().getApplicationContext();
if (mInstance == null) {
mInstance = new PreferenceValues(ctx);
}
prefs = ctx
.getSharedPreferences("MyPreferencess", Context.MODE_PRIVATE);
return mInstance;
}
/**
* To check if the application is running for the first time
*
* #return
*/
public boolean isFirstRun() {
return prefs.getBoolean("isfirstruns", true);
}
/**
* To update the flag for the first run
*
* #param isFirstRun
*/
public void setIsFirstRun(Boolean isFirstRun) {
this.isFirstRun = isFirstRun;
ed = prefs.edit();
ed.putBoolean("isfirstruns", this.isFirstRun);
ed.commit();
}
public String getDaysPresent() {
return prefs.getString("daysPresent", "0");
}
public void setDaysPresent(String daysPresent) {
this.daysPresent = daysPresent;
ed = prefs.edit();
ed.putString("daysPresent", this.daysPresent);
ed.commit();
}
public String getdaysAbsent() {
return prefs.getString("daysAbsent", "0");
}
public void setdaysAbsent(String daysAbsent) {
this.daysAbsent = daysAbsent;
ed = prefs.edit();
ed.putString("daysAbsent", this.daysAbsent);
ed.commit();
}
public String getpercentage() {
return prefs.getString("percentage", "0.00");
}
public void setpercentage(String percentage) {
this.percentage = percentage;
ed = prefs.edit();
ed.putString("percentage", this.percentage);
ed.commit();
}
}
Take this sample Activity code
public class MainActivity extends ActionBarActivity {
Button btn;
EditText t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button1);
t1 = (EditText) findViewById(R.id.textView1);
t1.setText(PreferenceValues.getInstance(getApplicationContext()).getDaysPresent());
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
PreferenceValues.getInstance(getApplicationContext()).setDaysPresent(t1.getText().toString());
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
PreferenceValues.getInstance(getApplicationContext()).setDaysPresent(t1.getText().toString());
}
}
If you need to store data after the app is closed, you need to use SharedPreferences.
See http://developer.android.com/training/basics/data-storage/shared-preferences.html
and
http://www.tutorialspoint.com/android/android_shared_preferences.htm
It happens because the activity is killed, so when it's created again, all objects are initialized again. You could cache this data in SharedPreferences, or in a database for example.
Related
I have a button. When I click the button, I want to change the value of the variable to 3. In another activity, I want to be able to get the value of the variable and do some computation based on that value.
I have tried using getters and setters methods and just traditionally changing the values and nothing seems to work.
//MainActivity.java
mButtonChoice2 = (Button)findViewById(R.id.choice2);
mButtonChoice2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
//My logic for Button goes in here
if (mButtonChoice2.getText() == "Three"){
setDays(3);
openActivity();
}
}
public int getDays() {
return days;
}
public void setDays(int value){
days = value;
}
public void openActivity() {
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
//SecondActivity.java
public class SecondActivity extends AppCompatActivity {
private TextView textview;
private MainActivity obj = new MainActivity();
Integer days = obj.getDays();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
textview = findViewById(R.id.program);
if (days == 3) {
textview.setText("Days is 3");
}
else {
textview.setText(days);
}
I want the textview in the SecondActivity to update the textview text with "days is 3"
However, it just errors out because it is not being able to correctly receive the value of the integer days.
try the following updated code:
//MainActivity.java
mButtonChoice2 = (Button)findViewById(R.id.choice2);
mButtonChoice2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
//My logic for Button goes in here
if (mButtonChoice2.getText() == "Three"){
setDays(3);
openActivity();
}
}
public int getDays() {
return days;
}
public void setDays(int value){
days = value;
}
public void openActivity() {
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra ("days",days);
startActivity(intent);
}
//SecondActivity.java
public class SecondActivity extends AppCompatActivity {
private TextView textview;
private MainActivity obj = new MainActivity();
// Integer days = obj.getDays();
int days=0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent intent=getIntent();days=intent.getIntExtra ("days",0);
textview = findViewById(R.id.program);
if (days == 3) {
textview.setText("Days is 3");
}
else {
textview.setText(days);
}
Reference :https://developer.android.com/reference/android/content/Intent
https://www.dev2qa.com/passing-data-between-activities-android-tutorial/
Just Declare a static variable in one activity and use it into the second activity.
I have listed the code below, What i am trying to achieve is the int i to be updated from a dialog box (dialog2). I then want to check in the main activity if it has changed and if it has changed then call a method. How would i do this?
Main Activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int i = 0;
Dialog1 dialog1 = new Dialog1(this, i);
dialog1.show();
}
//Want to call this method whenever I is modified
private void iModified(){
}
}
Dialog 1 Class (This dialog just passes it to dialog2)
public class Dialog1 extends Dialog{
int integerI;
Button button;
public Dialog1(final Activity activity, final int i){
super(activity);
setContentView(R.layout.dialog1);
integerI = i;
button = findViewById(R.id.dialog1Button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dialog2 dialog2 = new Dialog2(activity ,integerI);
dialog2.show();
closeDialog();
}
});
}
private void closeDialog(){
this.dismiss();
}
}
Dialog 2: This is where the integer is going to be changed and then i want it to be sent to the main activity and checked if it has changed and if so then replace the old integer with the new one.
public class Dialog2 extends Dialog {
int newI;
Button button;
public Dialog2(Activity activity, int i) {
super(activity);
setContentView(R.layout.dialog2);
newI= i + 12345;
button = findViewById(R.id.dialog2Button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
close();
}
});
}
private void close(){
this.dismiss();
}
}
You can use interface.
your activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int i = 0;
Dialog1 dialog1 = new Dialog1(this, i, new ModifiedListener() {
#Override
public void notify(int i) {
iModified();
}
});
dialog1.show();
}
//Want to call this method whenever I is modified
private void iModified(){
}
}
your dialog1:
public class Dialog1 extends Dialog {
int integerI;
Button button;
public Dialog1(final Activity activity, final int i, final ModifiedListener listener) {
super(activity);
setContentView(R.layout.dialog1);
integerI = i;
button = findViewById(R.id.dialog1Button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dialog2 dialog2 = new Dialog2(activity, integerI);
dialog2.show();
closeDialog();
}
});
}
private void closeDialog() {
this.dismiss();
}
}
your dialog 2:
public class Dialog2 extends Dialog {
int newI;
Button button;
public Dialog2(Activity activity, int i, final ModifiedListener listener) {
super(activity);
setContentView(R.layout.dialog2);
newI = i + 12345;
//when you modify int you have to call
listener.notify(newI);
button = findViewById(R.id.dialog2Button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
close();
}
});
}
private void close() {
this.dismiss();
}
}
define interface similar to class:
public interface ModifiedListener {
public void notify(int i);
}
I have a simple Android program that calculates how long it takes the phone to compute a certain mathematical problem. I want the mathematical problem to start when I hit the button, and while it is running I want a spinning progress bar to be displayed, and I want it to disappear after the math problem is done. This is the code I currently have:
public class main extends AppCompatActivity {
private TextView mScore;
private Button mRunButton;
private TextView mScoreText;
private ProgressBar mSpinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mScore = (TextView) findViewById(R.id.score);
mRunButton = (Button) findViewById(R.id.runbutton);
mScoreText = (TextView) findViewById(R.id.scoreText);
mSpinner = (ProgressBar) findViewById(R.id.progress);
mSpinner.setVisibility(View.GONE);
View.OnClickListener listener = new View.OnClickListener(){
#Override
public void onClick(View v) {
mSpinner.setVisibility(View.VISIBLE);
long startTime = System.nanoTime();
long start = System.currentTimeMillis();
long count = 0l;
for(long x=0;x<Integer.MAX_VALUE ;x++){
count+=1;
}
long end = System.currentTimeMillis();
long endTime = System.nanoTime();
long duration = ((endTime - startTime) / 1000000);
mScore.setText(duration + "");
mSpinner.setVisibility(View.GONE);
}
};
mRunButton.setOnClickListener(listener);
}
}
From what I can tell, nothing in the view of the app updates until after the phone is done with the entire onClick method, which is not what I want it to do. I want the progress bar to be displayed ONLY while the program is 'working'. How would I go about doing this?
Thank you
As Blackbelt and vilpe89 mentioned, you have to separate the threads. You can do this by having another class that extends ASyncTask which will handle the calculations. The problem with that is that the progress dialog needs to run on the UI thread. You can have an interface that changes the progress dialog in the main class.
Calculator class:
public final class Calculator extends AsyncTask<Void, Void, Void> {
Context context;
calcCallback mCallback;
public Calculator(Context c) {
this.context = c;
this.mCallback = (calcCallback) c;
}
//The main class needs to implement this interface
public interface calcCallback {
Void calcDone();
Void calcStarted();
//Other methods if necessary
}
#Override
protected Boolean doInBackground(Void... params) {
mCallback.calcStarted();
//Your calculations here
mCallback.calcDone();
return null;
}
}
MainActivity
public class MainActivity extends Activity implements Calculator.calcCallback, {
private TextView mScore;
private Button mRunButton;
private TextView mScoreText;
private ProgressBar mSpinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mScore = (TextView) findViewById(R.id.score);
mRunButton = (Button) findViewById(R.id.runbutton);
mScoreText = (TextView) findViewById(R.id.scoreText);
mSpinner = (ProgressBar) findViewById(R.id.progress);
mSpinner.setVisibility(View.GONE);
View.OnClickListener listener = new View.OnClickListener(){
#Override
public void onClick(View v) {
Calculator calculator = new Calculator(MainActivity.this);
calculator.execute();
}
};
mRunButton.setOnClickListener(listener);
}
#Override
public Void calcStarted() {
runOnUiThread(new Runnable() {
#Override
public void run() {
mSpinner.setVisibility(View.VISIBLE);
}
});
}
return null;
}
#Override
public Void calcDone() {
runOnUiThread(new Runnable() {
#Override
public void run() {
mSpinner.setVisibility(View.GONE);
}
});
}
return null;
}
}
You can also set up your calcDone() as calcDone(int duration) so that you can pass the calculated duration back to the main thread.
I'm programming a stopwatch in android sdk but I want to keep going even when I press back. I understand the activity lifecycle to some extent and I should overrive the onPause and onResume methods but have no idea how to go with that since SharePreference editor can't take in a Chronometer object
package com.example.taekwondobuddy.util;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.LinearLayout;
public class Time extends Activity {
Chronometer mChronometer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
mChronometer = new Chronometer(this);
layout.addView(mChronometer);
Button startButton = new Button(this);
startButton.setText("Start");
startButton.setOnClickListener(mStartListener);
layout.addView(startButton);
Button stopButton = new Button(this);
stopButton.setText("Stop");
stopButton.setOnClickListener(mStopListener);
layout.addView(stopButton);
Button resetButton = new Button(this);
resetButton.setText("Reset");
resetButton.setOnClickListener(mResetListener);
layout.addView(resetButton);
setContentView(layout);
}
View.OnClickListener mStartListener = new OnClickListener() {
public void onClick(View v) {
mChronometer.start();
}
};
View.OnClickListener mStopListener = new OnClickListener() {
public void onClick(View v) {
mChronometer.stop();
}
};
View.OnClickListener mResetListener = new OnClickListener() {
public void onClick(View v) {
mChronometer.setBase(SystemClock.elapsedRealtime());
}
};
}
any tips or advice? Help is appreciated!
// try this
public class Time extends Activity {
Chronometer mChronometer;
private SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
sharedPreferences = getSharedPreferences(getString(R.string.app_name), MODE_PRIVATE);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
mChronometer = new Chronometer(this);
layout.addView(mChronometer);
Button startButton = new Button(this);
startButton.setText("Start");
startButton.setOnClickListener(mStartListener);
layout.addView(startButton);
Button stopButton = new Button(this);
stopButton.setText("Stop");
stopButton.setOnClickListener(mStopListener);
layout.addView(stopButton);
Button resetButton = new Button(this);
resetButton.setText("Reset");
resetButton.setOnClickListener(mResetListener);
layout.addView(resetButton);
setContentView(layout);
}
private void showElapsedTime() {
long elapsedMillis = SystemClock.elapsedRealtime() - mChronometer.getBase();
Toast.makeText(MyActivity.this, "Elapsed milliseconds: " + elapsedMillis,
Toast.LENGTH_SHORT).show();
}
View.OnClickListener mStartListener = new View.OnClickListener() {
public void onClick(View v) {
int stoppedMilliseconds = 0;
String chronoText = mChronometer.getText().toString();
String array[] = chronoText.split(":");
if (array.length == 2) {
stoppedMilliseconds = Integer.parseInt(array[0]) * 60 * 1000
+ Integer.parseInt(array[1]) * 1000;
} else if (array.length == 3) {
stoppedMilliseconds = Integer.parseInt(array[0]) * 60 * 60 * 1000
+ Integer.parseInt(array[1]) * 60 * 1000
+ Integer.parseInt(array[2]) * 1000;
}
mChronometer.setBase(SystemClock.elapsedRealtime() - stoppedMilliseconds);
mChronometer.start();
}
};
View.OnClickListener mStopListener = new View.OnClickListener() {
public void onClick(View v) {
mChronometer.stop();
}
};
View.OnClickListener mResetListener = new View.OnClickListener() {
public void onClick(View v) {
mChronometer.setBase(SystemClock.elapsedRealtime());
}
};
#Override
public void onBackPressed() {
super.onBackPressed();
prepareSharedData();
}
#Override
protected void onResume() {
super.onResume();
mChronometer.setText(sharedPreferences.getString("time", "00:00"));
}
#Override
protected void onPause() {
super.onPause();
prepareSharedData();
}
public void prepareSharedData(){
String chronoText = mChronometer.getText().toString();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("time", chronoText);
editor.commit();
}
}
If you want to continue your countdown where you left it off than you need shared preferences other wise if you want to keep going stop watch even when user press back button you don't need Shared-Preference, shared-preference used to store primitive and string data types, You can use AsyncTask or Service to perform this operation,Still if you are using Chronometer you can not store Chronometer itself in shared preferences instead its values returned by elapsedRealtime() or from other methods of Chronometer
In AsyncTask or Service you can keep polling elapsedRealtime() , AsyncTask keep alive untill its doInBackground method finishes,even if you press back button AsyncTask keep alive
I'm having trouble switching views with button presses in my Android app. The code shows no errors in Eclipse, but the app quits unexpectedly in the emulator when the button is clicked. My code is below. Thanks
public class Main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button go = (Button)findViewById(R.id.goButton);
go.setOnClickListener(mGoListener);
}
private OnClickListener mGoListener = new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setClassName("android.taboo.Activities", "android.taboo.Activities.MainMenu");
startActivity(intent);
}
};
}
public class MainMenu extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainmenu);
TextView quickStart = (TextView)findViewById(R.id.quickStart);
quickStart.setOnClickListener(mQuickStartListener);
TextView gameSetup = (TextView)findViewById(R.id.gameSetup);
gameSetup.setOnClickListener(mGameSetupListener);
TextView settings = (TextView)findViewById(R.id.settings);
settings.setOnClickListener(mSettingsListener);
TextView wordEntry = (TextView)findViewById(R.id.wordEntry);
wordEntry.setOnClickListener(mWordEntryListener);
}
//Listeners for MainMenu navigation buttons
private OnClickListener mQuickStartListener = new OnClickListener() {
public void onClick(View v) {
setContentView(R.layout.quickstart);
}
};
private OnClickListener mGameSetupListener = new OnClickListener() {
public void onClick(View v) {
setContentView(R.layout.gamesetup);
}
};
private OnClickListener mSettingsListener = new OnClickListener() {
public void onClick(View v) {
setContentView(R.layout.settings);
}
};
private OnClickListener mWordEntryListener = new OnClickListener() {
public void onClick(View v) {
setContentView(R.layout.word);
}
};
}
Take a look at this code that i have here, this should help you out some.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
public class SmartApp extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.intro);
final Button firstTimeButton = (Button) findViewById(R.id.firstTimeButton);
firstTimeButton.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Intent userCreationIntent = new Intent(v.getContext(), UserCreation.class);
startActivityForResult(userCreationIntent, 0);
}
});
}
}
When the user clicks the "first time button" the user will be taken to the "user creation page". I believe in your code you have a few things wrong. Compare yours to what i provided and you should be able to see the differences and make the appropriate modifications. Let me know if this helps!