well i'm just testing the idea of shared preferences to save the user progress, but this simple code is not working, when i pass lev1 it should update preffile so that at next app start it should opens directly to lev2Activity, everything is ok even log cat is clean but nothing happens, i don't know whats wrong with my code, any help will be appreciated.
MainActivity.java
private Button b1;
public static final String levstate= "levstate";
private Context mycontext;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mycontext= this;
b1= (Button) findViewById(R.id.b1);
b1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
MainActivity.savelevstate(1, mycontext);
Intent i= new Intent(MainActivity.this, Lev1Activity.class);
startActivity(i);
}
});
}
public static void savelevstate(int state, Context mycontext)
{
SharedPreferences pref= mycontext.getSharedPreferences("preffile", MODE_APPEND);
Editor editor= pref.edit();
editor.putInt("levstate", state);
editor.commit();
}
public static int getlevstate(Context mycontext)
{
SharedPreferences pref= mycontext.getSharedPreferences("preffile", MODE_APPEND);
int state= pref.getInt("levstate", 1);
return state;
}
Lev1Activity.java
private EditText et1;
private Button b1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lev1);
et1= (EditText) findViewById(R.id.et1);
b1= (Button) findViewById(R.id.b1);
}
public void Next (View v)
{
String value= et1.getText().toString();
int finalvalue= Integer.parseInt(value);
if(finalvalue==22)
{
Intent i = new Intent (this, Lev2Activity.class);
startActivity(i);
MainActivity.savelevstate(2, this);
this.finish();
}
}
Your idea of using sharedPreferences is excellent. However, if you look at your MainActivity's onCreate(), you can see that you never check the last level state before starting the intent. The app runs, the user clicks on button "b1" and it immediately starts Lev1Activity. Assuming you want the correct level to start when the user presses that same button, you'd have to check for the current level state and then link that state to its appropriate level Activity.
For example (MainActivity.java):
b1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
Intent i;
switch(getlevstate(myContext)) {
case 1:
i = new Intent(myContext, Lev1Activity.class);
break;
case 2:
i = new Intent(myContext, Lev2Activity.class);
break;
case 3:
i = new Intent(myContext, Lev3Activity.class);
break;
case 4
i = new Intent(myContext, Lev4Activity.class);
break;
...
}
startActivity(i);
}
});
Using MODE_APPEND should work as well as using MODE_PRIVATE, however it is recommended to use the latter.
I would recommend to you to create a new class for working with SharedPreferences.
Here is a example for saving and retrieving data from shared preferences:
public class SharedPreferenceSettings {
private static final String PREFS_NAME = "MY_APP_SETTINGS";
private static final String PREFS_LANGUAGE = "LANGUAGE";
private static final String PREFS_CITY = "CITY";
private final SharedPreferences settings;
public SharedPreferenceSettings(Context context) {
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
}
public void setLanguage(String language) {
settings.edit().putString(PREFS_LANGUAGE, language).apply();
}
public String getlanguage() {
return settings.getString(PREFS_LANGUAGE, "english");
}
public void setCity(String city) {
settings.edit().putString(PREFS_CITY, city).apply();
}
public String getCity() {
return settings.getString(PREFS_CITY, "london");
}
}
For more info, check official Android documentation - link
You are only saving the states, but you aren't checking it anywhere in the code.
In MainActivity try this :
b1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
if(getlevstate(MainActivity.this)==2) {
Intent i= new Intent(MainActivity.this, Lev2Activity.class);
startActivity(i);
} else {
MainActivity.savelevstate(1, mycontext);
Intent i= new Intent(MainActivity.this, Lev1Activity.class);
startActivity(i);
}
}
});
Not sure this is the problem, but when I use Preferences I use Context.MODE_PRIVATE this is the only difference between my code and yours, maybe it will help!
Edit : I might be wrong, but I don't see anywhere the call to getlevstate. After setting this
et1= (EditText) findViewById(R.id.et1);
You shoud do somehing like this :
et1.setText(""+getlevstate(this))
Related
I am a beginner programmer and I create a game for android and I came across a problem that I want after finishing the game to show me the best score that I managed to achieve in playing this game I made a condition
if(DOD> sharedPreferences.getInt("DOD_SHA",0));
of course I use sharedPreferences to save the best score here but this condition doesn't work at all and my sharedPreference takes any value even less than the last score
public class EndScreen extends AppCompatActivity {
TextView Levelwys,war;
Button GotoMenu;
int DOD,ODE,MNO,PIE,DZI,POT,SIL,LOG;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_end_screen);
Levelwys = findViewById(R.id.textView15);
war = findViewById(R.id.textView19);
GotoMenu = findViewById(R.id.button);
sharedPreferences = getSharedPreferences("com.example.goodmath", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
Intent intent = getIntent();
int number = intent.getIntExtra(GameSingleActivity.LEVEL, 0);
DOD = intent.getIntExtra("DOD", 0);
ODE = intent.getIntExtra("ODE", 0);
MNO = intent.getIntExtra("MNO", 0);
PIE = intent.getIntExtra("PIE", 0);
DZI = intent.getIntExtra("DZI", 0);
POT = intent.getIntExtra("POT", 0);
SIL = intent.getIntExtra("SIL", 0);
LOG = intent.getIntExtra("LOG", 0);
Levelwys.setText(String.valueOf(number));
String test = String.valueOf(DOD);
Toast.makeText(getApplicationContext(), test, Toast.LENGTH_LONG).show();
Save();
GotoMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GotoMenu();
}
});
}
#Override
public void onBackPressed() {
}
void GotoMenu()
{
Intent intent1 = new Intent(this, MenuActivity.class);
startActivity(intent1);
}
void Save()
{
if(DOD> sharedPreferences.getInt("DOD_SHA",0));
{
editor.putInt("DOD_SHA",DOD);
editor.apply ();
editor.commit();
Toast.makeText(getApplicationContext(), "cos", Toast.LENGTH_LONG).show();
war.setText(String.valueOf(sharedPreferences.getInt("DOD_SHA",DOD)));
}
}
}
You have typo in your if condition:
if(DOD> sharedPreferences.getInt("DOD_SHA",0));
You have added extra semicolon at the end of this line. Because of this, the code below this condition was always called.
Delete this semicolon and everything should works fine:
if(DOD> sharedPreferences.getInt("DOD_SHA",0))
{
editor.putInt("DOD_SHA",DOD);
editor.apply ();
editor.commit();
Toast.makeText(getApplicationContext(), "cos", Toast.LENGTH_LONG).show();
war.setText(String.valueOf(sharedPreferences.getInt("DOD_SHA",DOD)));
}
I am trying to make promo code for my app when the user gives correct value in the EditText I will set a boolean value false and a number will be stored in shared preferences. But don't know why the value is not getting decremented and even if it decreases and even if I do it multiple times then only it moves from 30 to 29.
So I created a test app where I am setting the value in onClick what happens when the promo code is equal. So the decrement thing is when the user open the app the number will get decreased and stored back when the boolean value is false
public class MainActivity extends AppCompatActivity {
TextView textView;
Button button, button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
button1 = (Button) findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences prefs = getSharedPreferences("Admob", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("ShowAd", false);
editor.putLong("daycounter", 30);
editor.commit();
}
});
caller();
}
#Override
protected void onResume() {
super.onResume();
caller();
}
#Override
protected void onPause() {
super.onPause();
caller();
}
public void caller() {
SharedPreferences settings = getSharedPreferences("Admob", 0);
boolean ad_start = settings.getBoolean("ShowAd", true);
long ad = settings.getLong("daycounter", 0);
SharedPreferences prefs = getSharedPreferences("apprater", 0);
SharedPreferences.Editor editor = prefs.edit();
Log.e("toaster", "" + ad_start);
if (!ad_start) {
long ads = ad -1 ;
if (ad > 0) {
editor.putLong("daycounter", ads);
editor.putBoolean("ShowAd", true);
editor.commit();
Toast.makeText(MainActivity.this, "" + ads, Toast.LENGTH_SHORT).show();
textView.setText(ad + "R" + ad_start);
}
}
}
}
In the dummy app I am showing the data in TextView so I am calling onResume and onPause method otherwise I know onCreate is enough. I don't understand whats wrong in the algorithm. I am not getting any error at all and in the toast I am only able to decrease the value till 29 . I have tried all types of decrement operation. Any advice will be helpful.**I am able to save the data onle problem is with the lonng value is not getting saved and not getting decremented **
Put these methods in your utils class and use
public static void cacheBoolean(Context ctx, String k, Boolean v) {
SharedPreferences prefs = getSharedPreferences(ctx);
prefs.edit().putBoolean(k, v).apply();
}
public static Boolean getCachedBoolean(Context ctx, String k, Boolean defaultValue) {
SharedPreferences prefs = getSharedPreferences(ctx);
return prefs.getBoolean(k, defaultValue);
}
public static void cacheString(Context ctx, String k, String v) {
SharedPreferences prefs = getSharedPreferences(ctx);
prefs.edit().putString(k, v).apply();
}
public static String getCachedString(Context ctx, String k, String defaultValue) {
SharedPreferences prefs = getSharedPreferences(ctx);
return prefs.getString(k, defaultValue);
}
public static void cacheInt(Context ctx, String k, int v) {
SharedPreferences prefs = getSharedPreferences(ctx);
prefs.edit().putInt(k, v).apply();
}
public static int getCachedInt(Context ctx, String k, int defaultValue) {
SharedPreferences prefs = getSharedPreferences(ctx);
return prefs.getInt(k, defaultValue);
}
public static void clearCachedKey(Context context, String key) {
getSharedPreferences(context).edit().remove(key).apply();
}
You don't need to put shared preferences everywhere, just initialize it inside onCreate method and access from constant String, so will easy to access it.
public class MainActivity extends AppCompatActivity {
TextView textView;
Button button, button1;
SharedPreferences prefs;
SharedPreferences.Editor editor;
final String pref_name = "Admob";
final String ad_name = "ShowAd";
final String day_count = "daycounter";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
button1 = (Button) findViewById(R.id.button2);
prefs = getSharedPreferences(pref_name, 0);
editor = prefs.edit();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor.putBoolean(ad_name, false);
editor.putLong(day_count, 30);
editor.commit();
}
});
caller();
}
#Override
protected void onResume() {
super.onResume();
caller();
}
#Override
protected void onPause() {
super.onPause();
caller();
}
public void caller() {
boolean ad_start = prefs.getBoolean(ad_name, true);
long ad = prefs.getLong(day_count, 0);
Log.e("toaster", "" + ad_start);
if (!ad_start) {
long ads = ad -1 ;
if (ad < 0) {
editor.putBoolean(ad_name, true);
}
editor.putLong(day_count, ads);
editor.commit();
Toast.makeText(MainActivity.this, "" + ads, Toast.LENGTH_SHORT).show();
textView.setText(ad + "R" + ad_start);
}
}
}
I was making mistake in this method part thx to Ahmed sir My mistake was setting the value equal to
if (ad > 0) so when the value is more than zero the boolean was st as true and the data never get a chance to get decremented more
public void caller() {
SharedPreferences settings = getSharedPreferences("Admob", 0);
boolean ad_start = settings.getBoolean("ShowAd", true);
long ad = settings.getLong("daycounter", 0);
Log.e("toaster", "" + ad_start);
if (!ad_start) {
SharedPreferences prefs = getSharedPreferences("Admob", 0);
SharedPreferences.Editor editor = prefs.edit();
long ads = ad - 1;
if (ad < 0) {
editor.putBoolean("ShowAd", true);
}
editor.putLong("daycounter", ads);
editor.commit();
Toast.makeText(MainActivity.this, "" + ads, Toast.LENGTH_SHORT).show();
textView.setText(ad + "R" + ad_start);
}
}
This is my code to display two values: Recommended insulin dose and administered insulin dose. The two value is passed to another activity.
I have used two intent to pass two values to another activity(NewActivity).
The problem is as two intents are used only one value is displayed. The output is displayed as:
Recommended insulin dosage:null, Administered insulin dosage:10 (correct value of the calculation).
If the startActivity(intent) is removed from the button.setOnClickListener the output is displayed as:
Recommended insulin dosage:23 (correct value), Administered insulin dosage:null.
One of the value is becoming null. How to get two values displayed?
I tried declaring the string as public also
MainActivity.java
public class MainActivity extends Activity implements View.OnClickListener {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
private Button button;
private Button button2;
private EditText editText;
private EditText editText2;
private EditText editText4;
public static String myid;
public static String insulin;
private Spinner dynamicSpinner;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent=getIntent();
String carbval=intent.getStringExtra("carbval");
final EditText editText2 = (EditText) findViewById(R.id.editText2);
editText2.setText(carbval);
dynamicSpinner = (Spinner) findViewById(R.id.dynamic_spinner);
editText = (EditText) findViewById(R.id.editText);
button2 = (Button) findViewById(R.id.button2);
button = (Button) findViewById(R.id.button);
editText4=(EditText) findViewById(R.id.editText4);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String carbohydrate = editText2.getText().toString().trim();
String dailydose = editText4.getText().toString().trim();
int cc = Integer.parseInt(carbohydrate);
int dd = Integer.parseInt(dailydose);
int goc = 450 / dd;
int ab = cc / goc;
myid = Integer.toString(ab);
Intent intent1=new Intent(MainActivity.this,NewActivity.class);
intent1.putExtra("ids",myid);
startActivity(intent1);
}
});
Spinner staticSpinner = (Spinner) findViewById(R.id.static_spinner);
// Create an ArrayAdapter using the string array and a default spinner
ArrayAdapter<CharSequence> staticAdapter = ArrayAdapter
.createFromResource(this, R.array.brew_array,
android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
staticAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
staticSpinner.setAdapter(staticAdapter);
Spinner dynamicSpinner = (Spinner) findViewById(R.id.dynamic_spinner);
String[] items = new String[] { "---SELECT---", "LOW", "MODERATE", "HIGH" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items);
dynamicSpinner.setAdapter(adapter);
dynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Log.v("item", (String) parent.getItemAtPosition(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
private void getData() {
String bloodglucose = editText.getText().toString().trim();
if (bloodglucose.equals("")) {
Toast.makeText(this, "Please enter bloodglucose", Toast.LENGTH_LONG).show();
return;
}
String dosage =dynamicSpinner.getSelectedItem().toString().trim();
if (dosage.equals("")) {
Toast.makeText(this, "Please enter dosage", Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,"Please wait...","Calculating insulin dosage...",false,false);
String url1 = "http://10.1.6.21/getData1.php?bloodglucose="+editText.getText().toString().trim()+"&dosage="+dynamicSpinner.getSelectedItem().toString().trim();
StringRequest stringRequest = new StringRequest(url1, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String insulin="";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Confignew.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
insulin = collegeData.getString(Confignew.KEY_INSULIN);
Intent intent1=new Intent(MainActivity.this,NewActivity.class);
intent1.putExtra("value",insulin);
startActivity(intent1);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
getData();
}
}
NewActivity.java
public class NewActivity extends AppCompatActivity {
private Button mBtGoBack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
TextView tvmessage=(TextView) findViewById(R.id.tv_message);
tvmessage.setText("Recommended Insulin Dosage: "+getIntent().getExtras().getString("value"));
TextView tvmessage1=(TextView) findViewById(R.id.tv_message1);
tvmessage1.setText("Administered Insulin Dosage: "+getIntent().getExtras().getString("ids"));
mBtGoBack = (Button) findViewById(R.id.bt_go_back);
mBtGoBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
}
Looking at your code, it looks like you are re-creating the intent before starting an activity. Each of the intents you are creating only has one value passed through to NewActivity.java. You need to add both values to the same intent rather than re-creating it.
Here is your issue:
Intent intent1=new Intent(MainActivity.this,NewActivity.class);
intent1.putExtra("ids",myid);
Intent intent1=new Intent(MainActivity.this,NewActivity.class);
intent1.putExtra("value",insulin);
Rather than instantiating it twice, you should be creating the Intent only once and then adding extras to it as needed.
The two value is passed to another activity
You're only passing one value to the intent in every startActivity call, not two. That's why one is null and the other is not.
Here
Intent intent1=new Intent(MainActivity.this,NewActivity.class);
intent1.putExtra("value",insulin);
startActivity(intent1);
And here
Intent intent1=new Intent(MainActivity.this,NewActivity.class);
intent1.putExtra("ids",myid);
startActivity(intent1);
Just because you name it intent1 doesn't mean the data is shared.
You need to place both extras in the intent.
How about making a helper method, so you don't forget?
private void startNewActivity(String recommended, String administered) {
Intent i = new Intent(MainActivity.this,NewActivity.class);
i.putExtra("value",recommended);
i.putExtra("ids", administered);
startActivity(i);
}
Then use this to get both correct values.
startNewActivity("23", "10");
And by the way, this button event is never actually ran.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String carbohydrate = editText2.getText().toString().trim();
String dailydose = editText4.getText().toString().trim();
int cc = Integer.parseInt(carbohydrate);
int dd = Integer.parseInt(dailydose);
int goc = 450 / dd;
int ab = cc / goc;
myid = Integer.toString(ab);
// Replace this code with the method
/*
Intent intent1=new Intent(MainActivity.this,NewActivity.class);
intent1.putExtra("ids",myid);
startActivity(intent1);
*/
}
});
This one is... It overwrites the previous one.
button.setOnClickListener(this);
And does this
#Override
public void onClick(View v) {
getData();
}
One Intent can open a single Activity. What you are trying to do is sending value from two different Intents which you are re-creating inside onClicks.
You have to provide onClick using any one method. You have first set clickListener on Button using Anonymous Class and implemented the OnClickListener at the same time.
Remove onClickListener from the button, the part below
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String carbohydrate = editText2.getText().toString().trim();
String dailydose = editText4.getText().toString().trim();
int cc = Integer.parseInt(carbohydrate);
int dd = Integer.parseInt(dailydose);
int goc = 450 / dd;
int ab = cc / goc;
myid = Integer.toString(ab);
Intent intent1=new Intent(MainActivity.this,NewActivity.class);
intent1.putExtra("ids",myid);
startActivity(intent1);
}
});
Keep your overrdien onClick as it is.
#Override
public void onClick(View v) {
getData();
}
And now edit your getData() method to add the removed code
private void getData() {
String bloodglucose = editText.getText().toString().trim();
if (bloodglucose.equals("")) {
Toast.makeText(this, "Please enter bloodglucose", Toast.LENGTH_LONG).show();
return;
}
String dosage =dynamicSpinner.getSelectedItem().toString().trim();
if (dosage.equals("")) {
Toast.makeText(this, "Please enter dosage", Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,"Please wait...","Calculating insulin dosage...",false,false);
String url1 = "http://10.1.6.21/getData1.php?bloodglucose="+editText.getText().toString().trim()+"&dosage="+dynamicSpinner.getSelectedItem().toString().trim();
StringRequest stringRequest = new StringRequest(url1, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
And finally showJSON
private void showJSON(String response){
String insulin="";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Confignew.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
//The code from button's onClickListener
String carbohydrate = editText2.getText().toString().trim();
String dailydose = editText4.getText().toString().trim();
int cc = Integer.parseInt(carbohydrate);
int dd = Integer.parseInt(dailydose);
int goc = 450 / dd;
int ab = cc / goc;
myid = Integer.toString(ab);
Intent intent1 = new Intent(MainActivity.this,NewActivity.class);
intent1.putExtra("ids",myid);
//startActivity(intent1); Put second value too before starting activity
insulin = collegeData.getString(Confignew.KEY_INSULIN);
intent1.putExtra("value",insulin);
startActivity(intent1);
} catch (JSONException e) {
e.printStackTrace();
`enter code here`}
}
#Rasiga could you please let me know why 2 OnCickListener is set like
`button.setOnClickListener(this)`
and
button.setOnClickListener(new OnCLickListner){.....}
You are setting 2 onCLickListener for same View
I'm making a simple application and want to open a new Activity when I click a button. I have looked at a few tutorials online to do so, but I keep getting errors in my code that I dont quite know how to get rid of.
My code:
public class MainActivity extends AppCompatActivity {
private static Button button_convert;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onClick_Convert();
public void onClick_Convert() {
onClick_Convert = (button_convert) findViewById(R.id.button_convert);
onClick_Convert.setOnClickListener (
new View.onClickListener() {
public void onClick (View v) {
Intent intent = new Intent("com.example.jamesk93.bmi_app.SecondActivity");
startActivity(intent);
}
}
);
}
final Button button_calc = (Button) findViewById(R.id.button_calc);
final EditText field_weight = (EditText) findViewById(R.id.field_height);
final EditText field_height = (EditText) findViewById(R.id.field_height);
final TextView view_result = (TextView) findViewById(R.id.view_result);
final TextView view_msg = (TextView) findViewById(R.id.view_msg);
button_calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View V) {
double weight;
double height;
double bmi;
String msg = "";
weight = Double.parseDouble(field_weight.getText().toString());
height = Double.parseDouble(field_height.getText().toString());
if (field_height.getText().toString().equals("") || field_weight.getText().toString().equals("")) {
Toast.makeText(getApplicationContext(), "No Valid Values", Toast.LENGTH_LONG);
} else {
bmi = height * height;
bmi = weight / bmi;
view_result.setText(String.valueOf(bmi));
if (bmi < 18.5) {
msg = "Underweight";
} else if (bmi > 18.5 && bmi < 25) {
msg = "Normal";
} else if (bmi > 25) {
msg = "Overweight";
}
view_msg.setText(msg);
}
}
});
}
}
Im pretty sure it is my use of brackets and indenting that is generating the errors. Ive tried to reposition them but it doesnt seem to be solving anything.
If I comment lines 21-33 out which is the code for the onclick intent, it runs fine. If you need to see any of my other files, just comment which ones and I'll upload them for you.
Your code should be like this:
private Button button_convert;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_convert= (Button) findViewById(R.id.button_convert);
onClick_Convert();
}
public void onClick_Convert() {
button_convert.setOnClickListener (
new View.OnClickListener() {
#Override
public void onClick (View v) {
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
startActivity(intent);
}
}
);
}
EDIT:
There are a few mistakes:
First:
You are trying to initialize "onClick Convert" but it was not declared, actually the name of your button is "button convert". And then you try to cast it with "button convert". You should cast your button with "(Button)"
Second:
You are trying to initialize your button inside the click event, you should initialized it before the event, because then your button will be null.
Third:
The correct syntax to start an activity is:
Intent intent = new Intent(YourActivity.class, NewActivity.class);
startActivity(intent);
Hope this help you, I recommend you to take a look to this link: http://developer.android.com/intl/es/training/basics/firstapp/starting-activity.html
I have an android application similar to wheel of fortune where users have the option to purchase one consumable, $1000, and two entitlements, where they unlock two images as wheel styles. I am using the Amazon In-App Purchasing API. The user should be able to purchase as many consumables as they want but once they purchase the entitlements the unlocked image should be the only image that they see and they should no longer see the locked image. These in-app purchases work fine the first instance I initiate these purchases.
However, the consumable field will only update once and even though I can still go through the process of completing purchases for the consumable, the text view containing the score, or money, does not update other then that first initial purchase. Also the wheels return to the locked image rather then remaining as the unlocked image despite the fact that when I initiate the purchase for these entitlements I am told that I already own these items. Therefore I believe it may be something to do with my SharedPreferences. In short my purchases update my views once and then never again, however the backend code i.e the responses I receive from the Amazon client when completing purchases are correct. Can anyone see where I have made a mistake? Why does the textView containing the score update on the 1st purchase and never again from then on? Also how do I save the changes toe the wheel style so that when it reopens they no longer have the option to purchase the wheel? I have three classes and have included the code below. All and any help is greatly appreciated.
Game Class
public class Game extends Activity {
private ImageView wheel;
private int rand;
private int[] amounts = {100,650,-1,650,300,-1,800,250,-1,500};
private int score = 0;
private TextView scoreText;
private AnimatorSet set;
protected boolean animationDone = true;
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
prefs.registerOnSharedPreferenceChangeListener(prefsChanged);
wheel = (ImageView) findViewById(R.id.imageView1);
scoreText = (TextView) findViewById(R.id.score);
score = prefs.getInt("score", 0);
scoreText.setText("$" + String.valueOf(score));
}
private OnSharedPreferenceChangeListener prefsChanged = new OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences prefs,
String key) {
if(key.equals("money") && prefs.getBoolean(key, false)) {
score += 1000;
scoreText.setText("$" + String.valueOf(score));
prefs.edit().putBoolean("money", false);
}
}
};
#Override
protected void onStart() {
super.onStart();
InAppObserver obs = new InAppObserver(this);
PurchasingManager.registerObserver(obs);
}
#Override
protected void onPause() {
if(this.isFinishing())
{
prefs.edit().putInt("score", score).commit();
}
super.onPause();
}
#Override
protected void onStop() {
prefs.edit().putInt("score", score).commit();
super.onStop();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode != RESULT_CANCELED) {
String style = data.getStringExtra("wheel");
if(style.equals("camo"))
wheel.setImageResource(R.drawable.camowheel);
if(style.equals("gold"))
wheel.setImageResource(R.drawable.goldwheel);
if(style.equals("normal"))
wheel.setImageResource(R.drawable.wheel);
}
}
public void spinTheWheel(View v) {
if(animationDone) {
wheel.setRotation(0);
rand = (int) Math.round(2000 + Math.random()*360);
set = new AnimatorSet();
set.play(ObjectAnimator.ofFloat(wheel, View.ROTATION, rand));
set.setDuration(2000);
set.setInterpolator(new DecelerateInterpolator());
set.start();
animationDone = false;
set.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
calculateResult();
animationDone = true;
}
});
}
}
private void calculateResult() {
int angle = (int) wheel.getRotation();
angle %= 360;
angle = (int) Math.floor(angle/36);
if(amounts[angle] == -1) {
Intent intent = new Intent(this, GameOver.class);
intent.putExtra("score", score);
prefs.edit().putInt("score", 0).commit();
score = 0;
startActivity(intent);
}
else {
score += amounts[angle];
scoreText.setText("$"+String.valueOf(score));
prefs.edit().putInt("score", 0).commit();
}
}
public void upgradeWheel(View v) {
Intent intent = new Intent(getApplicationContext(), ChangeWheel.class);
startActivityForResult(intent, 1);
}
public void endGame(View v) {
Intent intent = new Intent(getApplicationContext(), GameOver.class);
intent.putExtra("score", score);
prefs.edit().putInt("score", 0).commit();
score = 0;
startActivity(intent);
}
public void addMoney(View v) {
PurchasingManager.initiatePurchaseRequest("money");
}
}
ChangeWheel Class
public class ChangeWheel extends Activity {
private Button buyCamoButton;
private Button buyGoldButton;
private ImageButton goldButton;
private ImageButton camoButton;
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change_wheel);
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
prefs.registerOnSharedPreferenceChangeListener(prefsChanged);
buyCamoButton = (Button) findViewById(R.id.buyCamo);
buyGoldButton = (Button) findViewById(R.id.buyGold);
goldButton = (ImageButton) findViewById(R.id.goldButton);
camoButton = (ImageButton) findViewById(R.id.camoButton);
goldButton.setEnabled(false);
camoButton.setEnabled(false);
}
private OnSharedPreferenceChangeListener prefsChanged = new OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences prefs,
String key) {
if(key.equals("camo") && prefs.getBoolean(key, false)) {
camoButton.setImageResource(R.drawable.camowheel);
camoButton.setEnabled(true);
buyCamoButton.setVisibility(View.INVISIBLE);
}
else if(key.equals("gold") && prefs.getBoolean(key, false)) {
goldButton.setImageResource(R.drawable.goldwheel);
goldButton.setEnabled(true);
buyGoldButton.setVisibility(View.INVISIBLE);
}
}
};
#Override
protected void onStart() {
super.onStart();
InAppObserver obs = new InAppObserver(this);
PurchasingManager.registerObserver(obs);
}
public void camoClick(View v) {
Intent intent = new Intent(getApplicationContext(), Game.class);
intent.putExtra("wheel", "camo");
setResult(RESULT_OK, intent);
finish();
}
public void goldClick(View v) {
Intent intent = new Intent(getApplicationContext(), Game.class);
intent.putExtra("wheel", "gold");
setResult(RESULT_OK, intent);
finish();
}
public void normalClick(View v) {
Intent intent = new Intent(getApplicationContext(), Game.class);
intent.putExtra("wheel", "normal");
setResult(RESULT_OK, intent);
finish();
}
public void buyCamo(View v) {
String req = PurchasingManager.initiatePurchaseRequest("camo");
prefs.edit().putString(req, "camo").commit();
}
public void buyGold(View v) {
String req = PurchasingManager.initiatePurchaseRequest("gold");
prefs.edit().putString(req, "gold").commit();
}
}
InAppObserver Class
public class InAppObserver extends BasePurchasingObserver {
private SharedPreferences prefs;
public InAppObserver(Activity caller) {
super(caller);
prefs = PreferenceManager.getDefaultSharedPreferences(caller.getApplicationContext());
}
#Override
public void onSdkAvailable(boolean isSandboxMode) {
PurchasingManager.initiatePurchaseUpdatesRequest(Offset.BEGINNING);
}
#Override
public void onPurchaseUpdatesResponse(PurchaseUpdatesResponse res) {
for(String sku : res.getRevokedSkus()) {
prefs.edit().putBoolean(sku, false).commit();
}
switch (res.getPurchaseUpdatesRequestStatus()) {
case SUCCESSFUL:
for(Receipt rec : res.getReceipts()) {
prefs.edit().putBoolean(rec.getSku(), true).commit();
}
break;
case FAILED:
// do something
break;
}
}
#Override
public void onPurchaseResponse(PurchaseResponse res) {
switch(res.getPurchaseRequestStatus()) {
case SUCCESSFUL:
String sku = res.getReceipt().getSku();
prefs.edit().putBoolean(sku, true).commit();
break;
case ALREADY_ENTITLED:
String req = res.getRequestId();
prefs.edit().putBoolean(prefs.getString(req, null), true).commit();
break;
case FAILED:
// do something
break;
case INVALID_SKU:
// do something
break;
}
}
}
It could be that you are not using the same editor.
preferences.edit().putString(PreferenceKey.DISTANCE, distance);
preferences.edit().commit();
two different SharedPreferences.Editors are being returned. Hence the
value is not being committed. Instead, you have to use:
SharedPreferences.Editor spe = preferences.edit();
spe.putString(PreferenceKey.DISTANCE, distance);
spe.commit();
From... SharedPreferences not working across Activities