android how to program a stopwatch with SharedPreference - java

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

Related

passing data from a bottom sheet dialog in first Activity to second Activity

I have a problem with passing data in android. let me explain my problem.
there are two activities called MainActivity and ProductInformationActivity.
in mainActivity there is a settingButton and onClickListener of the button, a bottom sheet dialog will open up. in bottomSheetDialog there are saveButton and three editText. whenever a user click on saveButton it should pass editTexts data's as PercentageClass to productInformationActivity . (percentage Class is a model to save percentages and pass theme between activities).
I create an interface Called "OnPercentageClicked" then I created an instance of this interface and create setter for that (setOnAddPercentageClicked).
in saveButtonListener I create instance of percentege class and set EditTexts data to it and finally I add percentage to interface's method.
this is mainACtivity:
public class MainActivity extends AppCompatActivity {
private View bottomSheetView;
private BottomSheetDialog bottomSheetDialog;
private OnAddPercentageClicked onAddPercentageClicked;
public void setOnAddPercentageClicked(OnAddPercentageClicked onAddPercentageClicked) {
this.onAddPercentageClicked = onAddPercentageClicked;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar mainToolbar = findViewById(R.id.mainToolbar);
setSupportActionBar(mainToolbar);
ImageButton settingbtn = findViewById(R.id.activityMain_settingBTN);
ViewPager2 viewPager2 = findViewById(R.id.activityMain_viewpager);
TabLayout tabLayout = findViewById(R.id.activityMain_tabLayout);
MainViewPagerAdapter adapter = new MainViewPagerAdapter(this);
viewPager2.setAdapter(adapter);
createDialog();
TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(tabLayout, viewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
switch (position){
case 0 : tab.setText("کالا ها"); break;
case 1 : tab.setText("دسته بندی ها"); break;
}
}
});
tabLayoutMediator.attach();
settingbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bottomSheetDialog.show();
TextInputEditText firstPercentage = bottomSheetDialog.findViewById(R.id.priceIncrementPercentage_firstPercentageET);
TextInputEditText secondPercentage = bottomSheetDialog.findViewById(R.id.priceIncrementPercentage_secondPercentageET);
TextInputEditText thirdPercentage = bottomSheetDialog.findViewById(R.id.priceIncrementPercentage_thirdPercentageET);
Button percentageSaveButton = bottomSheetDialog.findViewById(R.id.priceIncrementPercentage_saveBTN);
assert percentageSaveButton != null;
percentageSaveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (firstPercentage.getText().length()>0 && secondPercentage.getText().length()>0 && thirdPercentage.getText().length()>0){
Percentage percentage = new Percentage();
percentage.setFirstPercentage(Integer.parseInt(firstPercentage.getText().toString()));
percentage.setSecondPercentage(Integer.parseInt(secondPercentage.getText().toString()));
percentage.setThirdPercentage(Integer.parseInt(thirdPercentage.getText().toString()));
onAddPercentageClicked.onButtonClicked(percentage);
bottomSheetDialog.dismiss();
Toast.makeText(MainActivity.this, "ذخیره شد", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this, "لطفا همه ی فیلد ها را پر کنید", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
public void createDialog(){
bottomSheetDialog = new BottomSheetDialog(MainActivity.this,R.style.bottom_sheet_dialog_theme);
bottomSheetDialog.setContentView(getLayoutInflater().inflate(R.layout.price_increment_percentage,(LinearLayout)findViewById(R.id.priceIncrementPercentage_container),false));
}
}
in productInfomation Activity i want to get the percentage class which i used in MainActivity.
so I implement OnAddPercentageClicked then I create an instance of main activity and call the setter which I created in MainActivity (setOnAddPercentageClicked).
this is productInformationActivity :
public class ProductInformation extends AppCompatActivity implements View.OnClickListener ,OnAddPercentageClicked{
private Percentage percentage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_information);
MainActivity mainActivity = new MainActivity();
mainActivity.setOnAddPercentageClicked(this);
TextView productName = findViewById(R.id.activityProductInformation_productNameTV);
TextView productPrice = findViewById(R.id.activityProductInformation_productPriceTV);
TextView productPriceFirstPercentage = findViewById(R.id.productPriceFirstPercentage);
TextView productPriceSecondPercentage = findViewById(R.id.productPriceSecondPercentage);
TextView productPriceThirdPercentage = findViewById(R.id.productPriceThirdPercentage);
TextView productCategoryName = findViewById(R.id.activityProductInformation_categoryNameTV);
ImageButton close = findViewById(R.id.activity_product_information_closeIB);
close.setOnClickListener(this);
if (percentage !=null){
productPriceFirstPercentage.setText("قیمت کالا +"+percentage.getFirstPercentage()+" درصد");
productPriceSecondPercentage.setText("قیمت کالا +"+percentage.getSecondPercentage()+" درصد");
productPriceThirdPercentage.setText("قیمت کالا +"+percentage.getThirdPercentage()+" درصد");
}
//
// }
if (getIntent().hasExtra("PRODUCT")){
Product product = getIntent().getParcelableExtra("PRODUCT");
productName.setText(product.getTitle());
productPrice.setText(String.valueOf(product.getPrice()));
productCategoryName.setText(String.valueOf(product.getCategoryId()));
}
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.activity_product_information_closeIB){
finish();
}
}
#Override
public void onButtonClicked(Percentage percentage) {
Log.i(TAG, "onButtonClicked: " + percentage);
this.percentage = percentage;
}
}
and when i run this code i get an error which says that the interface in MainActicvity is null.
would you please help me ?
thanks.

How do I pass the string from a textview to another texview on the same activity?

I am working with this bingo callboard project in Android Studio. The principle is when I click a number button, it will show on the first textview. When I click the second number button, the first textview will show the current number pressed and the previous string will be passed to the second textview. How would I do this? Screenshot of app included. A sample of the MainActivity.java code is here:
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Activity mainActivity;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainActivity = MainActivity.this;
final Button button1 = findViewById(R.id.b1);
final Button button2 = findViewById(R.id.b2);
final Button button3 = findViewById(R.id.b3);
final Button button4 = findViewById(R.id.b4);
final Button button5 = findViewById(R.id.b5);
final TextView txt = (TextView) findViewById(R.id.presentcall);
final TextView lst = (TextView) findViewById(R.id.lastcall);
button1.setOnClickListener(new View.OnClickListener() {
Drawable background = button1.getBackground();
#Override
public void onClick(View v) {
txt.setText("B1");
if (button1.getText().equals("1"))
{
button1.setText(" 1 ");
button1.setBackgroundResource(R.drawable.onclick_border);
}
else if (button1.getText().equals(" 1 "))
{
button1.setText("1");
button1.setBackground(background);
}
}
});
button2.setOnClickListener(new View.OnClickListener() {
Drawable background = button2.getBackground();
#Override
public void onClick(View v) {
txt.setText("B2");
if (button2.getText().equals("2"))
{
button2.setText(" 2 ");
button2.setBackgroundResource(R.drawable.onclick_border);
}
else if (button2.getText().equals(" 2 "))
{
button2.setText("2");
button2.setBackground(background);
}
}
});
button3.setOnClickListener(new View.OnClickListener() {
Drawable background = button3.getBackground();
#Override
public void onClick(View v) {
txt.setText("B3");
if (button3.getText().equals("3"))
{
button3.setText(" 3 ");
button3.setBackgroundResource(R.drawable.onclick_border);
}
else if (button3.getText().equals(" 3 "))
{
button3.setText("3");
button3.setBackground(background);
}
}
});
button4.setOnClickListener(new View.OnClickListener() {
Drawable background = button4.getBackground();
#Override
public void onClick(View v) {
txt.setText("B4");
if (button4.getText().equals("4"))
{
button4.setText(" 4 ");
button4.setBackgroundResource(R.drawable.onclick_border);
}
else if (button4.getText().equals(" 4 "))
{
button4.setText("4");
button4.setBackground(background);
}
}
});
button5.setOnClickListener(new View.OnClickListener() {
Drawable background = button5.getBackground();
#Override
public void onClick(View v) {
txt.setText("B5");
if (button5.getText().equals("5"))
{
button5.setText(" 5 ");
button5.setBackgroundResource(R.drawable.onclick_border);
}
else if (button5.getText().equals(" 5 "))
{
button5.setText("5");
button5.setBackground(background);
}
}
});
Screenshot
Hey so from what I understand you need to update the lst textview with the data of txt textView. Well you can write a common method which can be called from any button click with the new data. something like this:
public class MainActivity extends AppCompatActivity {
private Activity mainActivity;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainActivity = MainActivity.this;
final Button button1 = findViewById(R.id.b1);
final Button button2 = findViewById(R.id.b2);
final Button button3 = findViewById(R.id.b3);
final Button button4 = findViewById(R.id.b4);
final Button button5 = findViewById(R.id.b5);
final TextView txt = (TextView) findViewById(R.id.presentcall);
final TextView lst = (TextView) findViewById(R.id.lastcall);
button1.setOnClickListener(new View.OnClickListener() {
Drawable background = button1.getBackground();
#Override
public void onClick(View v) {
txt.setText("B1");
updateTextView("B1");
if (button1.getText().equals("1"))
{
button1.setText(" 1 ");
button1.setBackgroundResource(R.drawable.onclick_border);
}
else if (button1.getText().equals(" 1 "))
{
button1.setText("1");
button1.setBackground(background);
}
}
});
button2.setOnClickListener(new View.OnClickListener() {
Drawable background = button2.getBackground();
#Override
public void onClick(View v) {
txt.setText("B2");
updateTextView("B2");
if (button2.getText().equals("2"))
{
button2.setText(" 2 ");
button2.setBackgroundResource(R.drawable.onclick_border);
}
else if (button2.getText().equals(" 2 "))
{
button2.setText("2");
button2.setBackground(background);
}
}
});
button3.setOnClickListener(new View.OnClickListener() {
Drawable background = button3.getBackground();
#Override
public void onClick(View v) {
txt.setText("B3");
updateTextView("B3");
if (button3.getText().equals("3"))
{
button3.setText(" 3 ");
button3.setBackgroundResource(R.drawable.onclick_border);
}
else if (button3.getText().equals(" 3 "))
{
button3.setText("3");
button3.setBackground(background);
}
}
});
button4.setOnClickListener(new View.OnClickListener() {
Drawable background = button4.getBackground();
#Override
public void onClick(View v) {
txt.setText("B4");
updateTextView("B4");
if (button4.getText().equals("4"))
{
button4.setText(" 4 ");
button4.setBackgroundResource(R.drawable.onclick_border);
}
else if (button4.getText().equals(" 4 "))
{
button4.setText("4");
button4.setBackground(background);
}
}
});
button5.setOnClickListener(new View.OnClickListener() {
Drawable background = button5.getBackground();
#Override
public void onClick(View v) {
txt.setText("B5");
updateTextView("B5");
if (button5.getText().equals("5"))
{
button5.setText(" 5 ");
button5.setBackgroundResource(R.drawable.onclick_border);
}
else if (button5.getText().equals(" 5 "))
{
button5.setText("5");
button5.setBackground(background);
}
}
});
}
private void updateTextView(String newData){
String oldData = txt.getText().toString();
lst.setText(oldData);
txt.setText(newData);
}
}
This will update your last textview with your txt textview data. YOu can call this method from your button clicks with the new data as a parameter . Hope this helps you
There is nothing wrong with p.matthew13's code. The problem is with the code sequence. I may also have to delete a line on my code because it's already redundant.
The redundant code is txt.setText(""); which contradicts txt.setText(newData);
I have to delete my setText code and replace it with the updateTextView("");
Also, I did place p.matthew13's code before my public void.
And that fixes my problem, after trying to shuffle up the code execution sequence.
Thanks very much!

Edit the TextView in custom AlertDialog

I have a layout with 10 buttons. When I click one of them a custom dialog shows up, that has 2 textviews - one for the title and one for the quote.
There's always an instant crash when I try to edit the TextView programmatically. The program crashes when I call tv1.setText.
I tried to create an another function called Qdialog. When I call it the program crashes as well.
package com.example.lud.fortunecookie;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Menuslection extends AppCompatActivity {
Button btback, bt1, bt2, bt3, bt4, bt5, bt6, bt7, bt8, bt9, bt10;
TextView tv1,tv2;
AlertDialog quotesalert;
AlertDialog.Builder quitbuilder,quotesbuilder;
int numb = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menuslecton);
char stline;
bt1 = (Button) findViewById(R.id.button1);
bt2 = (Button) findViewById(R.id.button2);
bt3 = (Button) findViewById(R.id.button3);
bt4 = (Button) findViewById(R.id.button4);
bt5 = (Button) findViewById(R.id.button5);
bt6 = (Button) findViewById(R.id.button6);
bt7 = (Button) findViewById(R.id.button7);
bt8 = (Button) findViewById(R.id.button8);
bt9 = (Button) findViewById(R.id.button9);
bt10 = (Button) findViewById(R.id.button10);
btback = (Button) findViewById(R.id.buttonback);
btback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quitbuilder = new AlertDialog.Builder(Menuslection.this);
quitbuilder.setMessage("Are you sure to quit ?");
quitbuilder.setTitle("Are you already got my advise.");
quitbuilder.setCancelable(false);
quitbuilder.setNegativeButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//finish(); //dung de thoat khoi activity hien tai
Intent iquit = new Intent(getApplicationContext(), MainActivity.class);
startActivity(iquit);
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startActivity(startMain);
finish();
}
});
quitbuilder.setPositiveButton("no", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog Alertquit = quitbuilder.create();
Alertquit.show();
}
});
//View layout = inflater.inflate(R.layout.dialoglayouttest,null);
//View layout = inflater.inflate(R.layout.customdialog, null);
// quotesbuilder.setView(tv1);
// View content = inflater.inflate(R.layout.dialoglayouttest, null);
// quotesbuilder.setView(content);
//TextView tv1 = (TextView) content.findViewById(R.id.dia_tit);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numb=1;
Qdialog();
quotesalert.show();
}
});
bt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numbslection(2);
quotesalert.show();
}
});
bt3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numbslection(3);
quotesalert.show();
}
});
bt4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numbslection(4);
quotesalert.show();
}
});
bt5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numbslection(5);
quotesalert.show();
}
});
bt6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numbslection(6);
quotesalert.show();
}
});
bt7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numbslection(7);
quotesalert.show();
}
});
bt8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numbslection(8);
quotesalert.show();
}
});
bt9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numbslection(9);
quotesalert.show();
}
});
bt10.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Qdialog();
// numb=10;
// quotesalert.show();
}
});
}
public int numbslection(int numb)
{//Slection Tittle Classic setup
if(numb==10)
numb=1;
//tv1.setText("");
else
if(numb==1||numb==2)
tv1.setText(R.string.Pgud);
else
if(numb<7&&numb>2)
tv1.setText(R.string.OK);
else
tv1.setText(R.string.Upset);
return numb;
}
public void Qdialog()
{
quotesalert.setContentView(R.layout.dialoglayouttest);
tv1 =(TextView) findViewById(R.id.dia_tit);
numbslection(numb);
quotesbuilder = new AlertDialog.Builder(Menuslection.this);
quotesalert=quotesbuilder.create();
}
}
To use custom layout to AlertDialog, you have to inflate layout and set view to AlertDiaolog:
public void Qdialog()
{
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.dialoglayouttest, null);
quotesbuilder = new AlertDialog.Builder(Menuslection.this);
quotesbuilder.setView(dialogView);
EditText editText = (EditText) dialogView.findViewById(R.id.dia_tit);
quotesalert = quotesbuilder.create();
quotesalert.show();
}
ALTERNATIVE:
If you want to use custom layout, use **Dialog** instead of **AlertDialog** :
public void Qdialog()
{
Dialog dialog = new Dialog(this)
dialog.setContentView(R.layout.dialoglayouttest);
dialog.setTitle("Title...");
TextView text = (TextView) dialog.findViewById(R.id.dia_tit);
dialog.show();
}
Hope this helps.

text in textview is not saving if i kill the activity?

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.

Using buttons to switch views with Android SDK

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!

Categories

Resources