Related
There is a lot of countries in this app including India, Pakistan, UAE, South Africa..etc. When clicking on name of a country, a new activity will be opened. It will be saved by share preference and when we open the app, the last activity will be opened. I created an app like this. I want to add one more thing to this app.
I want to go to countries list view by a button from the opened activity. The user can change the country here and when opening the app, the changed country's activity must be opened. If all countries are opened like this, there must be a option for choosing another country. I hope you will do this for me.
The project code which is done by me is given below.
The share preference will work on it. I want an option to change the country option.
** countries Listview (MainActivity)**
public class MainActivity extends AppCompatActivity {
CardView ind,pak,uae,south;
String clickedCard;
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
ind = (CardView) findViewById(R.id.ind);
pak = (CardView) findViewById(R.id.pak);
ind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent CltButton = new Intent(MainActivity.this, India.class);
clickedCard = "Button 1";
CltButton.putExtra("fromMain", clickedCard);
startActivity(CltButton);
}
});
pak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mgButton = new Intent(MainActivity.this,Pak .class);
clickedCard = "Button 2";
mgButton.putExtra("fromMain2", clickedCard);
startActivity(mgButton);
}
});
}
private void checkPreferences() {
////INDIA Preference
prefs = getSharedPreferences("pref", MODE_PRIVATE);
if (prefs.getString("txt", "").equals("") || prefs.getString("lastActivity", "").equals("")) {
} else {
String txt = prefs.getString("txt", "");
String activity = prefs.getString("lastActivity", "");
Intent CltButton = new Intent(MainActivity.this, India.class);
CltButton.putExtra("fromMain", txt);
startActivity(CltButton);
finish();
}
////PAKISTAN Preference
prefs = getSharedPreferences("pref2", MODE_PRIVATE);
if (prefs.getString("txt2", "").equals("") || prefs.getString("lastActivity2", "").equals("")) {
} else {
String txt2 = prefs.getString("txt2", "");
String activity = prefs.getString("lastActivity", "");
Intent mgButton =MainActivity new Intent(MainActivity.this, Pak.class);
mgButton.putExtra("fromMain2", txt2);
startActivity(mgButton);
finish();
}
}
}
India Activity code
public class India extends AppCompatActivity {
String s;
SharedPreferences prefs;
Button buttonind;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_india);
buttonind = (Button) findViewById(R.id.buttonind);
buttonind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mgButton = new Intent(India.this, Main2Activity.class);
startActivity(mgButton);
}
});
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle == null) {
s = "no data received";
} else {
s = bundle.getString("fromMain");
}
}
#Override
protected void onPause() {
super.onPause();
prefs = getSharedPreferences("pref", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("txt", s);
editor.putString("lastActivity", getClass().getName());
editor.apply();
}
}
Pak Activity Code
public class Pak extends AppCompatActivity {
String s;
SharedPreferences prefs;
Button buttonpak;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pak);
buttonpak = (Button) findViewById(R.id.buttonpak);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle == null) {
s = "no data received";
} else {
s = bundle.getString("fromMain2");
}
buttonpak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mgButton1 = new Intent(Pak.this, Main2Activity.class);
startActivity(mgButton1);
}
});
}
#Override
protected void onPause() {
super.onPause();
prefs = getSharedPreferences("pref2", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("txt2", s);
editor.putString("lastActivity2", getClass().getName());
editor.apply();
}
}
You are very welcome for this - It took me some time to do and it is working exactly like you want it to.
MainActivity:
public class MainActivity extends AppCompatActivity {
CardView ind,pak,uae,south;
String clickedCard;
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
ind = (CardView) findViewById(R.id.ind);
pak = (CardView) findViewById(R.id.pak);
uae = (CardView) findViewById(R.id.uae);
south = (CardView) findViewById(R.id.south);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle!= null) {
SharedPreferences preferences,preferences1,preferences2,preferences3,preferences4;
SharedPreferences.Editor editor,editor1,editor2,editor3,editor4;
preferences = getSharedPreferences("pref", Context.MODE_PRIVATE);
editor = preferences.edit();
editor.clear();
editor.apply();
preferences1 = getSharedPreferences("pref1", Context.MODE_PRIVATE);
editor1 = preferences1.edit();
editor1.clear();
editor1.apply();
preferences2 = getSharedPreferences("pref2", Context.MODE_PRIVATE);
editor2 = preferences2.edit();
editor2.clear();
editor2.apply();
preferences3 = getSharedPreferences("pref3", Context.MODE_PRIVATE);
editor3 = preferences3.edit();
editor3.clear();
editor3.apply();
preferences4 = getSharedPreferences("pref4", Context.MODE_PRIVATE);
editor4 = preferences4.edit();
editor4.clear();
editor4.apply();
} else {
checkPreferences();
}
//checkPreferences();
ind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent CltButton = new Intent(MainActivity.this, India.class);
clickedCard = "Button 1";
CltButton.putExtra("fromMain", clickedCard);
startActivity(CltButton);
finish();
}
});
pak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mgButton = new Intent(MainActivity.this,Pak.class);
clickedCard = "Button 2";
mgButton.putExtra("fromMain2", clickedCard);
startActivity(mgButton);
finish();
}
});
uae.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent keraButton = new Intent(MainActivity.this, Uae.class);
clickedCard = "Button 3";
keraButton.putExtra("fromMain3", clickedCard);
startActivity(keraButton);
finish();
}
});
south.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ButtonactivityIntent = new Intent(MainActivity.this, South.class);
clickedCard = "Button 4";
ButtonactivityIntent.putExtra("fromMain4", clickedCard);
startActivity(ButtonactivityIntent);
finish();
}
});
}
private void checkPreferences() {
////INDIA Preference
prefs = getSharedPreferences("pref", MODE_PRIVATE);
if (prefs.getString("txt", "").equals("") || prefs.getString("lastActivity", "").equals("")) {
} else {
String txt = prefs.getString("txt", "");
String activity = prefs.getString("lastActivity", "");
Intent CltButton = new Intent(MainActivity.this, India.class);
CltButton.putExtra("fromMain", txt);
startActivity(CltButton);
finish();
}
////PAKISTAN Preference
prefs = getSharedPreferences("pref2", MODE_PRIVATE);
if (prefs.getString("txt2", "").equals("") || prefs.getString("lastActivity2", "").equals("")) {
} else {
String txt2 = prefs.getString("txt2", "");
String activity = prefs.getString("lastActivity", "");
Intent mgButton = new Intent(MainActivity.this, Pak.class);
mgButton.putExtra("fromMain2", txt2);
startActivity(mgButton);
finish();
}
////U A E Preference
prefs = getSharedPreferences("pref3", MODE_PRIVATE);
if (prefs.getString("txt3", "").equals("") || prefs.getString("lastActivity3", "").equals("")) {
} else {
String txt2 = prefs.getString("txt3", "");
String activity = prefs.getString("lastActivity", "");
Intent mgButton = new Intent(MainActivity.this, Uae.class);
mgButton.putExtra("fromMain3", txt2);
startActivity(mgButton);
finish();
}
//// SOUTH AFRICA Preference
prefs = getSharedPreferences("pref4", MODE_PRIVATE);
if (prefs.getString("txt4", "").equals("") || prefs.getString("lastActivity4", "").equals("")) {
} else {
String txt2 = prefs.getString("txt4", "");
String activity = prefs.getString("lastActivity", "");
Intent mgButton = new Intent(MainActivity.this, South.class);
mgButton.putExtra("fromMain4", txt2);
startActivity(mgButton);
finish();
}
}
}
India.java:
public class India extends AppCompatActivity {
String s;
SharedPreferences prefs;
Button buttonind;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_india);
buttonind = (Button) findViewById(R.id.buttonind);
buttonind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String test = "";
Intent mgButton2 = new Intent(India.this, MainActivity.class);
mgButton2.putExtra("test", test);
startActivity(mgButton2);
finish();
}
});
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle == null) {
s = "no data received";
} else {
s = bundle.getString("fromMain");
}
}
#Override
protected void onPause() {
super.onPause();
prefs = getSharedPreferences("pref", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("txt", s);
editor.putString("lastActivity", getClass().getName());
editor.apply();
}
}
Pakistan.java
public class Pak extends AppCompatActivity {
String s;
SharedPreferences prefs;
Button buttonpak;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pak);
buttonpak = (Button) findViewById(R.id.buttonpak);
buttonpak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String test = "";
Intent mgButton2 = new Intent(Pak.this, MainActivity.class);
mgButton2.putExtra("test", test);
startActivity(mgButton2);
finish();
}
});
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle == null) {
s = "no data received";
} else {
s = bundle.getString("fromMain2");
}
}
#Override
protected void onPause() {
super.onPause();
prefs = getSharedPreferences("pref2", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("txt2", s);
editor.putString("lastActivity2", getClass().getName());
editor.apply();
}
}
You can repeat the process for all the other countries. In MainActivity where I check if (bundle!= null) can be simplified, but it is working.
I already ask this question several time in stack overflow, I hope this time can somebody show me the correct code, I modify my coding many time still same output.
coding:
public class MainActivity extends AppCompatActivity {
Toolbar mToolbar;
Button mRedColor;
Button mGreenColor;
Button mYellowColor;
Button[] b=new Button[2];
SharedPreferences mSharedPreferences;
SharedPreferences.Editor edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSharedPreferences = getSharedPreferences("ButtonColor", MODE_PRIVATE);
edit = getSharedPreferences("ButtonColor", MODE_PRIVATE).edit();
mToolbar = (Toolbar) findViewById(R.id.toolbar);
final Button[] b = new Button[]{(Button) findViewById(R.id.btnRed),
(Button) findViewById(R.id.btnGreen),
(Button) findViewById(R.id.btnYellow),};
mToolbar.setTitle(getResources().getString(R.string.app_name));
if (getColor() != getResources().getColor(R.color.colorPrimary)) {
for (int i = 0 ; i<b.length; i++){
if(b[i].equals(b[0]) ){
b[0].setBackgroundColor(getColor());
b[i].setEnabled(false);
}
else if (b[i].equals(b[1])){
b[1].setBackgroundColor(getColor());
b[i].setEnabled(false);
}else if (b[i].equals(b[2])){
b[2].setBackgroundColor(getColor());
b[i].setEnabled(false);
}
}
}
for (int i = 0; i < b.length; i++) {
b[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) //so we get its id here
{
case (R.id.btnRed):
b[0].setBackgroundColor(getResources().getColor(R.color.colorRed));
storeColor(getResources().getColor(R.color.colorRed));
b[0].setEnabled(false);
break;
case (R.id.btnGreen):
b[1].setBackgroundColor(getResources().getColor(R.color.colorGreen));
storeColor(getResources().getColor(R.color.colorGreen));
b[1].setEnabled(false);
break;
case (R.id.btnYellow):
b[2].setBackgroundColor(getResources().getColor(R.color.colorYellow));
storeColor(getResources().getColor(R.color.colorYellow));
b[2].setEnabled(false);
break;
}
}
});
}
}
#Override
protected void onResume() {
super.onResume();
mSharedPreferences = getSharedPreferences("ButtonColor", MODE_PRIVATE);
edit=getSharedPreferences("ButtonColor", MODE_PRIVATE).edit();
}
#Override
public void onStop () {
super.onStop();
}
private void storeColor(int color){
SharedPreferences mSharedPreferences =
getSharedPreferences("ButtonColor", MODE_PRIVATE);
SharedPreferences.Editor mEditor = mSharedPreferences.edit();
mEditor.putInt("color", color);
mEditor.apply();
}
private int getColor(){
SharedPreferences mSharedPreferences =
getSharedPreferences("ButtonColor", MODE_PRIVATE);
int selectedColor = mSharedPreferences.getInt("color",
getResources().getColor(R.color.colorPrimary));
return selectedColor;
}
}
The problem i face is in here: The first Button only will be coloured permanently after reopen application...., thanks
Try below code. you will able to change all buttons color but it will store only last selected button color.
public class MainActivity extends AppCompatActivity {
Toolbar mToolbar;
Button mRedColor;
Button mGreenColor;
Button mYellowColor;
Button[] b = new Button[2];
SharedPreferences mSharedPreferences;
SharedPreferences.Editor edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color);
mSharedPreferences = getSharedPreferences("ButtonColor", MODE_PRIVATE);
edit = getSharedPreferences("ButtonColor", MODE_PRIVATE).edit();
mToolbar = (Toolbar) findViewById(R.id.toolbar);
final Button[] b = new Button[]{(Button) findViewById(R.id.btnRed),
(Button) findViewById(R.id.btnGreen),
(Button) findViewById(R.id.btnYellow),};
mToolbar.setTitle(getResources().getString(R.string.app_name));
int lastPostion = getButtonPosition();
if (getColor() != getResources().getColor(R.color.colorPrimary)) {
for (int i = 0; i < b.length; i++) {
if (b[i].equals(b[0]) && i == lastPostion) {
b[0].setBackgroundColor(getColor());
b[i].setEnabled(false);
} else if (b[i].equals(b[1]) && i == lastPostion) {
b[1].setBackgroundColor(getColor());
b[i].setEnabled(false);
} else if (b[i].equals(b[2]) && i == lastPostion) {
b[2].setBackgroundColor(getColor());
b[i].setEnabled(false);
}
}
}
for (int i = 0; i < b.length; i++) {
b[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) //so we get its id here
{
case (R.id.btnRed):
b[0].setBackgroundColor(getResources().getColor(android.R.color.holo_red_dark));
storeColor(getResources().getColor(android.R.color.holo_red_dark), 0);
b[0].setEnabled(false);
break;
case (R.id.btnGreen):
b[1].setBackgroundColor(getResources().getColor(android.R.color.holo_green_dark));
storeColor(getResources().getColor(android.R.color.holo_green_dark), 1);
b[1].setEnabled(false);
break;
case (R.id.btnYellow):
b[2].setBackgroundColor(getResources().getColor(android.R.color.black));
storeColor(getResources().getColor(android.R.color.black), 2);
b[2].setEnabled(false);
break;
}
}
});
}
}
#Override
protected void onResume() {
super.onResume();
mSharedPreferences = getSharedPreferences("ButtonColor", MODE_PRIVATE);
edit = getSharedPreferences("ButtonColor", MODE_PRIVATE).edit();
}
#Override
public void onStop() {
super.onStop();
}
private void storeColor(int color, int position) {
SharedPreferences mSharedPreferences =
getSharedPreferences("ButtonColor", MODE_PRIVATE);
SharedPreferences.Editor mEditor = mSharedPreferences.edit();
mEditor.putInt("color", color);
mEditor.putInt("position", position);
mEditor.apply();
}
private int getColor() {
SharedPreferences mSharedPreferences =
getSharedPreferences("ButtonColor", MODE_PRIVATE);
int selectedColor = mSharedPreferences.getInt("color",
getResources().getColor(R.color.colorPrimary));
return selectedColor;
}
private int getButtonPosition() {
SharedPreferences mSharedPreferences =
getSharedPreferences("ButtonColor", MODE_PRIVATE);
int selectedColor = mSharedPreferences.getInt("position", 0);
return selectedColor;
}
}
I´m making a simple game where user clicks and score will increase its value. If score is on some point like 200, beast will evolve on different imageView and so on.
Problem is that if I reach point in my if statement it works but when I change activity by clicking upper button and then change it back to the mainActivity Progress bar change its state to different value, than i click and it shows correct filling.
How can it be fixed? I need also progress saves itself and fill the bar after closing and opening the app.... I have Score and Proggress values saved in SharedPreferences so i don´t know where is problem. (sorry for EN). Adding some pictures to make it easier to understand.
My Main Activity's code:
public class MainActivity extends Activity
{
int score;
int progress = score;
ImageButton beast;
SoundPool sp = new SoundPool(15, AudioManager.STREAM_MUSIC, 0);
ProgressBar mProgress;
DecimalFormat df = new DecimalFormat("#,###,###");
private ImageView mScanner;
private Animation mAnimation;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
final int soundDd = sp.load(this, R.raw.menu, 1);
mProgress = (ProgressBar) findViewById(R.id.progressBar);
mProgress.getProgressDrawable().setColorFilter(
Color.rgb(0, 199, 140), android.graphics.PorterDuff.Mode.SRC_IN);
mProgress.setScaleY(5f);
fontChange();
addIntegerValue();
mScanner = (ImageView) findViewById(R.id.imageChanger);
mScanner.setVisibility(View.VISIBLE);
mAnimation = new TranslateAnimation(
TranslateAnimation.ABSOLUTE, 0f,
TranslateAnimation.ABSOLUTE, 0f,
TranslateAnimation.RELATIVE_TO_PARENT, 0f,
TranslateAnimation.RELATIVE_TO_PARENT, 0.05f);
mAnimation.setDuration(2000);
mAnimation.setRepeatCount(- 1);
mAnimation.setRepeatMode(Animation.REVERSE);
mAnimation.setInterpolator(new LinearInterpolator());
mScanner.setAnimation(mAnimation);
score = PreferenceManager.getDefaultSharedPreferences(this).getInt("value", score);
TextView ts = (TextView) findViewById(R.id.textview2);
beast = (ImageButton) findViewById(R.id.beastButton);
beast.setSoundEffectsEnabled(false);
if (progress >= 0 && progress <= 199)
{
mProgress.setMax(200);
mScanner.setBackgroundResource(R.drawable.worm);
}
if (progress >= 200 && progress <= 399)
{
mProgress.setMax(400);
mScanner.setBackgroundResource(R.drawable.worm);
}
if (progress >= 400 && progress <= 599)
{
mProgress.setMax(600);
mScanner.setBackgroundResource(R.drawable.worm);
}
if (progress >= 600 && progress <= 799)
{
mProgress.setMax(800);
mScanner.setBackgroundResource(R.drawable.worm);
}
beast.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
sp.play(soundDd, 1, 1, 0, 0, 1);
Intent i = new Intent(getApplicationContext(), BeastSelect.class);
startActivity(i);
}
});
}
public void fontChange()
{
//font set
TextView ts = (TextView) findViewById(R.id.textview2);
TextView tl = (TextView) findViewById(R.id.textLadder);
TextView tb = (TextView) findViewById(R.id.textBeast);
TextView te = (TextView) findViewById(R.id.textevolve);
int low = PreferenceManager.getDefaultSharedPreferences(this).getInt("value", score);
mProgress.setProgress(low);
ts.setText("SCORE : " + " " + df.format(low));
Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/Phage Regular.otf");
ts.setTypeface(custom_font);
tl.setTypeface(custom_font);
tb.setTypeface(custom_font);
te.setTypeface(custom_font);
//font set over
}
public void addIntegerValue()
{
RelativeLayout rl = (RelativeLayout) findViewById(R.id.activity_main);
rl.setSoundEffectsEnabled(false);
final TextView ts = (TextView) findViewById(R.id.textview2);
final int soundId = sp.load(this, R.raw.coin, 1);
rl.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
score++;
mProgress.setProgress(score);
sp.play(soundId, 1, 1, 0, 0, 1);
ts.setText("SCORE : " + " " + df.format(score));
if (progress >= 0 && progress <= 199)
{
mProgress.setMax(200);
mScanner.setBackgroundResource(R.drawable.worm);
}
if (progress >= 200 && progress <= 399)
{
mProgress.setMax(400);
mScanner.setBackgroundResource(R.drawable.worm);
}
if (progress >= 400 && progress <= 599)
{
mProgress.setMax(600);
mScanner.setBackgroundResource(R.drawable.worm);
}
if (progress >= 600 && progress <= 799)
{
mProgress.setMax(800);
mScanner.setBackgroundResource(R.drawable.worm);
}
}
});
}
protected void onPause()
{
super.onPause();
PreferenceManager.getDefaultSharedPreferences(this).edit().putInt("value", score).apply();
}
protected void onDestroy()
{
super.onDestroy();
sp.release();
sp = null;
}
}
My Second Activity's code:
public class BeastSelect extends Activity
{
ImageButton back;
SoundPool sp = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_beast_select);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
final int soundDd = sp.load(this, R.raw.menu, 1);
back = (ImageButton) findViewById(R.id.imageBack);
back.setSoundEffectsEnabled(false);
fontChange();
back.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
sp.play(soundDd, 1, 1, 0, 0, 1);
Intent b = new Intent(getApplicationContext(), MainActivity.class);
startActivity(b);
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
{
// do something on back.
Intent b = new Intent(getApplicationContext(), MainActivity.class);
startActivity(b);
return true;
}
return super.onKeyDown(keyCode, event);
}
public void fontChange()
{
//font set
TextView hd = (TextView) findViewById(R.id.beasttext);
TextView cm = (TextView) findViewById(R.id.textcommon);
TextView tm = (TextView) findViewById(R.id.textmedium);
TextView pr = (TextView) findViewById(R.id.textpro);
Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/Phage Regular.otf");
hd.setTypeface(custom_font);
cm.setTypeface(custom_font);
tm.setTypeface(custom_font);
pr.setTypeface(custom_font);
//font set over
}
}
in your activity onResume method do this:
mProgress = (ProgressBar) findViewById(R.id.progressBar);
score = PreferenceManager.getDefaultSharedPreferences(this).getInt("value", score);
mProgress.setProgress(score);
So, I've been struggling on this for a while and have searched on here for hours without finding anything that really helped. I have a custom class Streak. When the user creates a new Streak in my Main Activity, I want for that streak to be added to a list of total streaks, which I would then access from an AllStreaks activity. I have tried using Gson, but received errors. What I have below is working for the time being, but since my global variable has to be declared as new. I don't really want to use a MySQL database as this info needs to be quickly editable and I don't want to have to constantly connect to that to potentially change just one detail.
Sorry if my code is a mess or this makes no sense, I'm coming to realize I'm really shitty at programming anyway.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private SharedPreferences prefs;
private SharedPreferences.Editor editor;
private String userID;
private int streakCounter;
private int mainStreakCounter;
private RelativeLayout quickAdd;
private EditText quickSubmitStreak;
private Button quickSubmitButton;
private Button mainStreak1;
private Button mainStreak2;
private Button mainStreak3;
private Button mainStreak4;
private Button allStreaks;
private Button addStreak;
private Dialog pickDialog;
private Button healthButton;
private Button mentalButton;
private Button personalButton;
private Button professionalButton;
private Button socialButton;
private Button submitStreakButton;
private TextView todaysDate;
private EditText chooseDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/*
Creates shared preferences and editor
*/
prefs = getSharedPreferences("carter.streakly", MODE_PRIVATE);
editor = prefs.edit();
// Checks if it's the first time the user opens the app. If so, generates a unique user ID and stores it in shared prefs
if (prefs.getBoolean("firstTime", true)){
userID = UUID.randomUUID().toString();
editor.putString("user", userID);
editor.putBoolean("firstTime", false);
editor.commit();
}
streakCounter = 0; // CHANGE TO streakCounter = prefs.getInt("streakCounter", 0) later
mainStreakCounter = 0; // CHANGE TO mainStreakCount = prefs.getInt("mainStreakCounter", 0) later
quickSubmitStreak = (EditText) findViewById(R.id.enter_goal);
quickSubmitButton = (Button) findViewById(R.id.submit_button);
mainStreak1 = (Button) findViewById(R.id.main_goal_1);
mainStreak2 = (Button) findViewById(R.id.main_goal_2);
mainStreak3 = (Button) findViewById(R.id.main_goal_3);
mainStreak4 = (Button) findViewById(R.id.main_goal_4);
allStreaks = (Button) findViewById(R.id.main_goal_5);
addStreak = (Button) findViewById(R.id.add_streak_button);
/*
if (streakCounter > 4){
quickAdd.setVisibility(View.INVISIBLE);
}
mainStreak1.setText(prefs.getString("mainKeyOne", ""));
mainStreak2.setText(prefs.getString("mainKeyTwo", ""));
mainStreak3.setText(prefs.getString("mainKeyThree", ""));
mainStreak4.setText(prefs.getString("mainKeyFour", ""));
/*
Sets the text to the lowest unused main streak to the inputted streak name
Stores the streak name in shared prefs so it will be there for next time app opens
Increases the total streak count
*/
quickSubmitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mainStreakCounter < 4){
switch(mainStreakCounter){
case 0:
mainStreak1.setText(quickSubmitStreak.getText().toString());
editor.putString("mainKeyOne", quickSubmitStreak.getText().toString()).commit();
break;
case 1:
mainStreak2.setText(quickSubmitStreak.getText().toString());
editor.putString("mainKeyTwo", quickSubmitStreak.getText().toString()).commit();
break;
case 2:
mainStreak3.setText(quickSubmitStreak.getText().toString());
editor.putString("mainKeyThree", quickSubmitStreak.getText().toString()).commit();
break;
case 3:
mainStreak4.setText(quickSubmitStreak.getText().toString());
editor.putString("mainKeyFour", quickSubmitStreak.getText().toString()).commit();
break;
default:break;
}
}
mainStreakCounter++;
AllStreaks.streakList.add(new Streak(quickSubmitStreak.getText().toString()));
// ADD THESE TO SHARED PREFERENCES AT SOME POINT
}
});
/*
Brings user to the All Streaks activity, and passes the LinkedList<Streak> streakList
*/
allStreaks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AllStreaks.class);
startActivity(intent);
}
});
/*
Shows an Alert Dialog that allows users to enter in the type of streak they want
*/
addStreak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
createCustomDialog();
}
});
}
private void createCustomDialog(){
pickDialog = new Dialog(MainActivity.this);
pickDialog.setContentView(R.layout.dialog_add_streak);
final EditText chooseName = (EditText) pickDialog.findViewById(R.id.dialog_acitivty_name);
healthButton = (Button) pickDialog.findViewById(R.id.dialog_health);
mentalButton = (Button) pickDialog.findViewById(R.id.dialog_mental);
personalButton = (Button) pickDialog.findViewById(R.id.dialog_personal);
professionalButton = (Button) pickDialog.findViewById(R.id.dialog_professional);
socialButton = (Button) pickDialog.findViewById(R.id.dialog_social);
submitStreakButton = (Button) pickDialog.findViewById(R.id.dialog_submit_button);
todaysDate = (TextView) pickDialog.findViewById(R.id.dialog_today);
chooseDate = (EditText) pickDialog.findViewById(R.id.dialog_input_date);
pickDialog.show();
healthButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editor.putInt("AddCategory", 0).commit();
editor.putString("Category", "Health");
editor.commit();
recolorCategory();
}
});
mentalButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editor.putInt("AddCategory", 1).commit();
editor.putString("Category", "Mental");
editor.commit();
recolorCategory();
}
});
personalButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editor.putInt("AddCategory", 2).commit();
editor.putString("Category", "Personal");
editor.commit();
recolorCategory();
}
});
professionalButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editor.putInt("AddCategory", 3).commit();
editor.putString("Category", "Professional");
editor.commit();
recolorCategory();
}
});
socialButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editor.putInt("AddCategory", 4).commit();
editor.putString("Category", "Social");
editor.commit();
recolorCategory();
}
});
todaysDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
todaysDate.setTextColor(Color.rgb(51,51,255));
chooseDate.setTextColor(Color.rgb(0,0,0));
editor.putInt("todayOrChosen", 1).commit();
}
});
chooseDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chooseDate.setTextColor(Color.rgb(51,51,255));
todaysDate.setTextColor(Color.rgb(0,0,0));
editor.putInt("todayOrChosen", 2).commit();
}
});
submitStreakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*
If the user selected today's date, enter the days kept as 0. If the user selected how long they've kept the streak for, enter the days kept as chooseDate
*/
if(prefs.getInt("todayOrChosen", 1) == 1){
//streakList.add(new Streak(chooseName.getText().toString(), prefs.getString("Category", ""),
//new SimpleDateFormat("dd-MM-yyyy").format(new Date()), 0));
AllStreaks.streakList.add(new Streak(chooseName.getText().toString(), prefs.getString("Category", ""),
new SimpleDateFormat("dd-MM-yyyy").format(new Date()), 0));
}
else {
//streakList.add(new Streak(chooseName.getText().toString(), prefs.getString("Category", ""),
//new SimpleDateFormat("dd-MM-yyyy").format(new Date()), Integer.parseInt(chooseDate.getText().toString())));
AllStreaks.streakList.add(new Streak(chooseName.getText().toString(), prefs.getString("Category", ""),
new SimpleDateFormat("dd-MM-yyyy").format(new Date()), Integer.parseInt(chooseDate.getText().toString())));
}
/*
Update streakList in Shared Preferences
*/
/*
Display an Alert Dialog indicating that a streak has been added
*/
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Streak Added")
.setPositiveButton("OK", null)
.create()
.show();
pickDialog.dismiss();
}
});
}
/*
Highlights which category is currently chosen
*/
private void recolorCategory(){
Button[] categoryList = {healthButton, mentalButton, personalButton, professionalButton, socialButton};
int recolorIndex = prefs.getInt("AddCategory", 0);
categoryList[recolorIndex].setTextColor(Color.rgb(51,51,255));
for (int i = 0; i < 5; i++){
if (i != recolorIndex) categoryList[i].setTextColor(Color.rgb(153, 255, 102));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
AllStreaks.java:
public class AllStreaks extends AppCompatActivity {
public static ArrayList<Streak> streakList = new ArrayList<>();
private SharedPreferences prefs;
private SharedPreferences.Editor editor;
private ArrayList<Streak> allStreakList;
private TableLayout mTableLayout;
private TableRow mTableRow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_streaks);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/*
if (streakList == null){
Button streakButton = new Button(this);
streakButton.setText("Try again");
}
else{
for (int j = 0; j < streakList.size(); j++){
allStreakList.add(streakList.get(j));
}
}*/
prefs = getSharedPreferences("carter.streakly", MODE_PRIVATE);
editor = prefs.edit();
mTableLayout = (TableLayout) findViewById(R.id.all_streak_table);
int i = 0;
while (i < streakList.size()){
if (i % 2 == 0){
mTableRow = new TableRow(this);
mTableLayout.addView(mTableRow);
}
Button streakButton = new Button(this);
streakButton.setText(String.valueOf(streakList.get(i).getDaysKept()));
streakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(AllStreaks.this, EnlargedActivity.class);
startActivity(intent);
}
});
mTableRow.addView(streakButton);
i++;
}
}
}
you cannot pass object directly.you have to parcelable or serialize it. but in parecelable is part of android where serialzation is part of java so i suggest you to use parcelable.
you can make model class to parcelable from this link if you dont want to code for parcelabel.
parcelable creator
you can achieve like this.
class Car implements Parcelable {
public int regId;
public String brand;
public String color;
public Car(Parcel source) {
regId = source.getInt();
brand = source.getString();
color = source.getString();
}
public Car(int regId, String brand, String color) {
this.regId = regId;
this.brand = brand;
this.color = color;
}
public int describeContents() {
return this.hashCode();
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(regId);
dest.writeString(brand);
dest.writeString(color);
}
public static final Parcelable.Creator CREATOR
= new Parcelable.Creator() {
public Car createFromParcel(Parcel in) {
return new Car(in);
}
public Car[] newArray(int size) {
return new Car[size];
}
};}
And you can pass it like below.
ArrayList carList = new ArrayList();
carList.add(new Car('1','Honda','Black');
carList.add(new Car('2','Toyota','Blue');
carList.add(new Car('3','Suzuki','Green');
Intent i = new Intent(getApplicationContext(), CarDetailActivity.class);
i.putParcelableArrayListExtra("cars", carList);
this.startActivity(i);
you can get it like below:
Intent i = this.getIntent();
ArrayList<Car> carList = (ArrayList<Car>)i.getParcelableArrayListExtra("cars");`
You need to use Parcelable or Serializable interface.
and the pass it with intent
Intent mIntent = new Intent(context, ResultActivity.class);
mIntent.putParcelableArrayListExtra("list", mArraylist);
startActivity(mIntent);
fetch it in ResultActivity
Bundle bundle = getIntent().getExtras();
mArraylist1 = bundle.getParcelableArrayList("list");
Check this thread for reference
Do this on your Streak class and try,
Streak implements Parcelable
Since your modal class has not serialized, it may not able to pass via bundle. You can do that by implementing the Parcelable interface.
Parcelable is an Android specific interface where you implement the
serialization yourself. It was created to be far more efficient that
Serializable, and to get around some problems with the default Java
serialization scheme.
Serializable is a standard Java interface. You simply mark a class
Serializable by implementing the interface, and Java will
automatically serialize it in certain situations.
Courtsy
If I am adding a number in my app let's say upto 15, I want to make sure the next time I open my app no matter if it crashed, phones was restarted, or app was exited; it should continue from number 15 rather than the 0. How can I work on that?
I tried something like this. This is probably wrong not sure how to fix it.
public class MainActivity extends Activity {
private int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.but);
final TextView txt = (TextView) findViewById(R.id.txt);
final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = app_preferences.edit();
i++;
txt.setText(" " + i);
i++;
editor.putInt("Scores: ", i);
editor.commit();
}
});
}
}
public class MainActivity extends Activity {
private int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// let i be previously saved value or default to zero
i = app_preferences.getInt("Scores: ",0);
Button btn = (Button) findViewById(R.id.but);
final TextView txt = (TextView) findViewById(R.id.txt);
final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = app_preferences.edit();
i++;
txt.setText(" " + i);
//i++; maybe DONT really increment twice (unless thats what you intended)
editor.putInt("Scores: ", i);
editor.commit();
}
});
}
}