Android passing value from checkbox to toast view - android

I managed to do the passing value from radio button and now I want when the user clicks on several checkboxes to display the checked values in a toast view +Toppings: HERE
package com.example.pizzaorderding;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText name=(EditText)findViewById(R.id.name);
final EditText phone=(EditText)findViewById(R.id.phone_number);
final EditText address=(EditText)findViewById(R.id.address);
final RadioGroup shapes = (RadioGroup) findViewById(R.id.rBtnshapes);
final RadioGroup types = (RadioGroup) findViewById(R.id.rBtntypes);
final CheckBox pep = (CheckBox)findViewById(R.id.pepperoni);
final CheckBox mshr = (CheckBox)findViewById(R.id.mushrooms);
Button orderBtn = (Button)findViewById(R.id.orderBtn);
orderBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
StringBuffer result = new StringBuffer();
result.append("Pepperoni").append(pep.isChecked());
result.append("Mushrooms").append(mshr.isChecked());
int selectedShape = shapes.getCheckedRadioButtonId();
int selectedCheese = types.getCheckedRadioButtonId();
RadioButton sh = (RadioButton)findViewById(selectedShape);
RadioButton ty=(RadioButton)findViewById(selectedCheese);
Toast.makeText(MainActivity.this, "Name: "+name.getText()+"\n"+"Phone: "+phone.getText()+"\n"+"Address: " +address.getText()+"\n"+"Shape: "+sh.getText()+"\n"+"Cheese: "+ty.getText()+"\n"+"Toppings: "+result.toString(), Toast.LENGTH_SHORT).show();
}
});
}
}

Maybe this will work?
result.append("Pepperoni").append(pep.isChecked().toString());
result.append("Mushrooms").append(mshr.isChecked().toString());

Do you mean something like:
if (pep.isChecked())
result.append("Pepperoni, ");
if (mshr.isChecked())
result.append("Mushrooms, ");
if (result.length() > 2)
result.delete(result.length() - 2, result.length()); // to remove last ", "

public void onClick(View v) {
// TODO Auto-generated method stub
StringBuffer result = new StringBuffer();
result.append("Pepperoni"+"\n").append(pep.isChecked()).toString();
result.append("Mushrooms"+"\n").append(mshr.isChecked()).toString();
int selectedShape = shapes.getCheckedRadioButtonId();
int selectedCheese = types.getCheckedRadioButtonId();
RadioButton sh = (RadioButton)findViewById(selectedShape);
RadioButton ty=(RadioButton)findViewById(selectedCheese);
Toast.makeText(MainActivity.this, "Name: "+name.getText()+"\n"+"Phone: "+phone.getText()+"\n"+"Address: " +address.getText()+"\n"+"Shape: "+sh.getText()+"\n"+"Cheese: "+ty.getText()+"\n"+"Toppings: "+result.toString(), Toast.LENGTH_SHORT).show();
`
And that is how it displays http://postimg.org/image/zc1dobpuf/ .. I dont want to display true or false, just if it's checked to display the topping

Related

create unique IDs for multiple views and use it Onclick

i want to create ids for three buttons so that i can use them in a switch case i want the ids to be unique in each loop like btna[1].setid("btna"+1),btnb[1].setid("btnb"+1),btnc[3].setid("btnc"+3) somethimg like that and i want to repet this for n number of times
here is my code:
package com.astro.famouspandit.Activities.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.astro.famouspandit.Database.DatabaseHelper;
import com.astro.famouspandit.R;
import com.astro.famouspandit.datasets.ItemProfile;
import java.util.ArrayList;
import mehdi.sakout.fancybuttons.FancyButton;
public class ProfleList extends AppCompatActivity implements View.OnClickListener{
private TextView txtProfileName,txtProfileDate,txtProfileTime,txtProfileLocation;
private FancyButton btnEdit[],btnDelete[],btnView[];
LinearLayout linearlist ;
DatabaseHelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profle_list);
mydb = new DatabaseHelper(this);
long count = mydb.getCount();
Log.d("count", "onCreate: "+count);
if (count == 0){
}else{
ArrayList<ItemProfile> listprofile = mydb.profilelist();
for (int i = 1; i < count+1; i++ ) {
ItemProfile itemProfile = listprofile.get(i-1);
linearlist = (LinearLayout)findViewById(R.id.layoutlist);
View[] myView = new View[i];
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
myView[i-1] = inflater.inflate(R.layout.profile_list, null);
txtProfileName = (TextView)myView[i-1].findViewById(R.id.txtName);
txtProfileDate = (TextView)myView[i-1].findViewById(R.id.txtDate);
txtProfileTime = (TextView)myView[i-1].findViewById(R.id.txtTime);
txtProfileLocation = (TextView)myView[i-1].findViewById(R.id.txtLocation);
btnEdit[i] = (FancyButton)myView[i-1].findViewById(R.id.btn_edtProfile);
btnDelete[i] = (FancyButton)myView[i-1].findViewById(R.id.btn_deleteProfile);
btnView[i] = (FancyButton)myView[i-1].findViewById(R.id.btn_viewProfile);
btnEdit[i].setOnClickListener(this);
btnDelete[i].setOnClickListener(this);
btnDelete[i].setOnClickListener(this);
String profileName = itemProfile.getProfileName();
txtProfileName.setText(profileName);
Log.d("ProfileName", "onCreate: "+itemProfile.getProfileName());
int dd = itemProfile.getDay();
int mm = itemProfile.getMonth();
int yy = itemProfile.getYear();
txtProfileDate.setText(dd+"/"+mm+"/"+yy);
Log.d("Profiledate", "onCreate: "+itemProfile.getDay()+itemProfile.getMonth()+itemProfile.getYear());
int hour = itemProfile.getHour();
int min = itemProfile.getMinute();
txtProfileTime.setText(hour+":"+min);
Log.d("ProfileTime", "onCreate: "+itemProfile.getHour()+itemProfile.getHour());
String city = itemProfile.getCity();
txtProfileLocation.setText(itemProfile.getCity());
Log.d("citylocation,city", "onCreate: "+itemProfile.getCity()+","+city);
linearlist.addView(myView[i-1]);
}
}
}
#Override
public void onClick(View v) {
}
}
I recommend using View.setTag(), where you can set an object to a View.
View also has a method called findViewWithTag(Object tag) where it searches between the child views for the given tag (using Object.equals()).
So to adapt it to your case:
btna[1].setTag("btna" + 1);
btnb[1].setTag("btnb" + 1);
btnc[3].setTag("btnc" + 3);
You can easily make a for loop from this.
And then later:
Button btnc = (Button)container.findViewWithTag("btnc3");
Just make sure that the buttons are direct children of the ViewGroup named container.
To handle click events, modify your onClick() this way:
#Override
public void onClick(View v) {
String tag = v.getTag();
if (tag.equals("btna1")) {
Log.i("Test", "Clicked on button A 1");
} else if (tag.equals("btnb1")) {
Log.i("Test", "Clicked on button B 1");
}
}
And so on...
You can use switch-case with Strings only in Java 7, which is available from ADT 22.6.

In android, How can i display selected data from databse in list view??? i am using sqlite database

I am developing one android application.i want to display a data which is selected from database and display it in listview.first of all i had used static data for display Trainee(user) data. which is static. then after For same functionality i have use sqlite Database and register the Trainee(user) and now i want to display registered trainne's name in listview. i have just done below code. can anyone help me how to display trainee names in listview.
AddTraineeActivity.java
This file works basic function of create trainee database and insert values of trainee:
package com.example.gymapp;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AddTraineeActivity extends Activity implements OnClickListener
{
EditText fn;
EditText ln;
EditText un;
EditText pwd;
EditText pno;
EditText age;
Button btnAdd;
SQLiteDatabase db = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_managetrainee);
fn = (EditText) findViewById(R.id.etfirstname);
ln = (EditText) findViewById(R.id.etlastname);
age = (EditText) findViewById(R.id.edage);
pno = (EditText) findViewById(R.id.etphoneno);
un = (EditText) findViewById(R.id.ettraineeun);
pwd = (EditText) findViewById(R.id.etpwdtrainee);
btnAdd = (Button) findViewById(R.id.btnsavedata);
db=openOrCreateDatabase("mydb", MODE_PRIVATE, null);
db.execSQL("create table if not exists trainee(firstname text, lastname text,age varchar,phoneNumber varchar,userTrainee varchar,passwordTrainee varchar)");
btnAdd.setOnClickListener(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
public void show(String str)
{
Toast.makeText(this, str, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v== btnAdd)
{
String firstname = fn.getText().toString();
String lastname = ln.getText().toString();
String Age = age.getText().toString();
String phoneNumber = pno.getText().toString();
String usernameTrainee = un.getText().toString();
String passwordTrainee = pwd.getText().toString();
if(firstname==null||firstname==""||firstname.length()<3)
{
show("Please Enter Correct Name.");
}
else if(lastname==null||lastname==""||lastname.length()<2)
{
show("Please Enter Correct Name.");
}
else if(Age==null||Age==""||Age.length()>3)
{
show("Please Enter Correct Age.");
}
else if(phoneNumber==null||phoneNumber==""||phoneNumber.length()<10)
{
show("Please Enter Correct mobile number.");
}
else if(usernameTrainee==null||usernameTrainee==""||usernameTrainee.length()<4)
{
show("Please Enter valid User name.");
}
else if(passwordTrainee==null||passwordTrainee==""||passwordTrainee.length()<6)
{
show("Please Enter Strong Password.");
}
else
{
db.execSQL("insert into trainee values('"+firstname+"','"+lastname+"','"+Age+"','"+phoneNumber+"','"+usernameTrainee+"','"+passwordTrainee+"')");
//i=new Intent(this,Welcome.class);
//startActivityForResult(i, 500);
//overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
db.close();
finish();
}
}
}
}`
UserListActivity.java
This file contain the code which display the trainee names in listview. but this file display static users for example,trainee1,trainee2,trainee3....trainee13.
package com.example.gymapp;
import com.tss.constant.Constant;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.content.Context;
import android.database.sqlite.*;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import com.example.gymapp.AddTraineeActivity;
import com.example.gymapp.dao.DBfitguidehelper;
public class UserListActivity extends Activity {
private ListView listViewUser;
private String loggedInType ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_list);
//SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
//queryBuilder.setTables(DBfitguidehelper.)
listViewUser = (ListView)findViewById(R.id.listViewUser);
String[] values = new String[]{"trainee", "trainee1", "trainee2", "trainee3", "trainee4", "trainee5", "trainee6", "trainee7", "trainee8", "trainee9", "trainee10", "trainee11", "trainee12", "trainee13"};
ArrayAdapter<String> userAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, values);
listViewUser.setAdapter(userAdapter);
listViewUser.setOnItemClickListener(new ListViewListner());
if(savedInstanceState!=null){
Bundle extras = getIntent().getExtras();
loggedInType = extras.getString("loggedInType");
System.out.println("loggedInType - " + loggedInType);
}
}
private class ListViewListner implements OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "selected user is " + listViewUser.getItemAtPosition(position), Toast.LENGTH_SHORT).show();
Constant.Selected_Trainee = ""+listViewUser.getItemAtPosition(position);
Intent intent = new Intent(getApplicationContext(),TrainerActivity.class);
intent.putExtra("loggedInType", loggedInType);
Toast.makeText(getApplicationContext(), "loggedInType"+loggedInType, Toast.LENGTH_SHORT).show();
startActivity(intent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.user_list, menu);
return true;
}
}
now i want to display name of trainees which is stored in database. can anyone help me??
If you want to see how a Cursor loader can work for you, you can review the following project that I have uploaded to github: GPS Distance Tracking

Closing Android Game After 5 Seconds

I'm tring to build an simple android game.
Users answer the questions, when the answer is correct, it is continue..
I want to add time control for each answer.
I tried to add handler function, but I didn't.
My Code;
import java.util.Collections;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class EasyGameActivity extends Activity {
public int score = 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_easygame);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
finishScreen();
}
}, 5000);
startGame();
}
private void startGame() {
// TODO Auto-generated method stub
Button b1 = (Button)findViewById(R.id.answer_one);
Button b2 = (Button)findViewById(R.id.answer_two);
Button b3 = (Button)findViewById(R.id.answer_three);
Button b4 = (Button)findViewById(R.id.answer_four);
Random number = new Random();
int first = number.nextInt(100)+1;
int second = number.nextInt(100)+1;
int answer = first + second;
int rnd1 = answer + 1;
int rnd2 = answer + 2;
int rnd3 = answer - 1;
final String a = Integer.toString(answer);
String b = Integer.toString(rnd1);
String c = Integer.toString(rnd2);
String d = Integer.toString(rnd3);
((TextView) findViewById(R.id.display)).setText(Integer.toString(first) + '+' + Integer.toString(second));
List<Button> buttons = Arrays.asList(b1, b2, b3, b4);
List<String> texts = Arrays.asList(a, b, c, d);
Collections.shuffle(texts);
int i = 0;
OnClickListener onClick = new OnClickListener() {
public void onClick(View view) {
Button button = (Button) view;
String value = (String) button.getText();
if(value == a) {
checkTrue();
} else {
finishScreen();
}
}
};
for(Button button : buttons) {
button.setText(texts.get(i++));
button.setOnClickListener(onClick);
}
}
private void checkTrue() {
score++;
((TextView) findViewById(R.id.score)).setText(Integer.toString(score));
startGame();
}
private void finishScreen() {
score = 0;
startActivity (new Intent("com.bsinternet.mathfast.RESTARTGAMESCREEN"));
finish();
}
}
How can I add time control. Thanks.
This bit of code doesn't look right
if(value == a) {
checkTrue();
} else {
finishScreen();
}
You should be using equals() to check for String equality. At the moment you are checking only object equality, which will evaluate to False, and the code will never call checkTrue().
Do this instead:
if(value.equals(a) {
checkTrue();
} else {
finishScreen();
}

How to multiply two editText's value and accoringly get value in a textView when user enters value in android

I have two EditText and one TextView in my activity,I want to multiple both edittext value thing is that when user entering values to any of edittext ,Accordingly the textView value should be change..My code is as below:
EDITTEXTS:qty,price
TextView:tv_subtotal
main.java
package com.epe.yehki.ui;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Pref;
import com.epe.yehki.util.Utils;
import com.example.yehki.R;
public class PlaceOrderActivity extends ListActivity {
Button confirm, shipping;
RelativeLayout rl_adress;
TextView product_name;
TextView tv_adress;
TextView tv_select_adres;
EditText qty;
EditText price;
TextView tv_subtotal;
TextView tv_total;
ArrayAdapter<String> adapter;
String method;
ImageView back;
Double total, subtotal, min_qty, min_agree_prc, max_agree_prc, min_agree_qty, Max_agree_qty, min_qty_unit_name, max_price, min_price;
Intent i = null;
#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_place_order);
final ListView lv = getListView();
System.out.println("::::::::::::my custome Id inside ::::::::::place order" + Pref.getValue(PlaceOrderActivity.this, Const.PREF_CUSTOMER_ID, ""));
// FINDINLG IDS...!!
qty = (EditText) findViewById(R.id.et_qty);
price = (EditText) findViewById(R.id.et_price);
rl_adress = (RelativeLayout) findViewById(R.id.btn_adress);
product_name = (TextView) findViewById(R.id.tv_product_name);
tv_adress = (TextView) findViewById(R.id.tv_adress);
tv_select_adres = (TextView) findViewById(R.id.tv_select_adress);
tv_total = (TextView) findViewById(R.id.tv_total);
tv_subtotal = (TextView) findViewById(R.id.tv_subtotal);
back = (ImageView) findViewById(R.id.iv_back);
qty.setCursorVisible(false);
price.setCursorVisible(false);
lv.setVisibility(View.GONE);
String[] shipMethods = new String[] { "Sea Freight", "Air Cargo", "Express" };
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, shipMethods);
shipping = (Button) findViewById(R.id.btn_shiping_method);
shipping.setText("Select shipping Method");
if (Pref.getValue(PlaceOrderActivity.this, Const.FLAG_ADDRESS, "").equals("")) {
max_agree_prc = Double.parseDouble(i.getStringExtra(Const.TAG_PRODUCT_AGREE_MAX_PRICE));
min_agree_prc = Double.parseDouble(i.getStringExtra(Const.TAG_PRODUCT_AGREE_MIN_PRICE));
Max_agree_qty = Double.parseDouble(i.getStringExtra(Const.TAG_PRODUCT_AGREE_MAX_QTY));
min_agree_qty = Double.parseDouble(i.getStringExtra(Const.TAG_PRODUCT_AGREE_MIN_QTY));
min_qty = Double.parseDouble(i.getStringExtra(Const.TAG_PRODUCT_MIN_ORDER_QTY));
min_qty_unit_name = Double.parseDouble(i.getStringExtra(Const.TAG_PRODUCT_MIN_ORDER_QTY_UNIT_NAME));
max_price = Double.parseDouble(i.getStringExtra(Const.TAG_PRODUCT_MAX_PRICE));
min_price = Double.parseDouble(i.getStringExtra(Const.TAG_PRODUCT_MIN_PRICE));
product_name.setText(getIntent().getStringExtra(Const.TAG_PRODUCT_NAME));
}
qty.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
qty.setCursorVisible(true);
}
});
price.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
price.setCursorVisible(true);
}
});
// SELECT ADDRESS CLICK EVENT..!
rl_adress.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
i = new Intent(PlaceOrderActivity.this, AddressListActivity.class);
startActivity(i);
}
});
shipping.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
setListAdapter(adapter);
lv.setVisibility(View.VISIBLE);
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
method = (String) getListAdapter().getItem(position);
shipping.setText(method);
i.putExtra("shipping", method);
lv.setVisibility(View.GONE);
}
});
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
confirm.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Checking for quantity and price...!!!
if (Integer.parseInt(qty.getText().toString()) >= min_qty) {
// check for quantity range
if (Integer.parseInt(price.getText().toString()) >= min_price && Integer.parseInt(price.getText().toString()) <= max_price) {
// check for price range
} else {
Utils.showCustomeAlertValidation(PlaceOrderActivity.this, "Enter Price in Range", "ALERT", "OK");
}
} else {
Utils.showCustomeAlertValidation(PlaceOrderActivity.this, "Enter Quantity in Range", "ALERT", "OK");
}
}
});
}
private void calculate() {
// TODO Auto-generated method stub
double QuantyInt = 1;
double PriceInt = 0;
if (qty != null)
QuantyInt = Double.parseDouble(qty.getText().toString());
if (price != null)
PriceInt = Double.parseDouble(price.getText().toString());
subtotal = (QuantyInt * PriceInt);
String textResult = "Your BMI is " + subtotal;
tv_subtotal.setText(textResult);
tv_total.setText(textResult);
}
}

Error: Final local variable score cannot be assigned, since it is defined in an enclosing type?

I am trying to use the getIntent value(score) which is retrieve from the previous activity but it seems like it is impossible. It seems that addition and subtraction under if else cannot detect score. Is there any other way?
package com.mkyong.android;
import com.mkyong.android.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;
public class App2Activity extends Activity {
private RadioGroup radioAnswerGroup2;
private RadioButton radioAnswerButton2;
private Button btnSubmit2;
Button button2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
addListenerOnButton();
}
public void addListenerOnButton() {
final Context context = this;
radioAnswerGroup2 = (RadioGroup) findViewById(R.id.radioAnswer2);
button2 = (Button) findViewById(R.id.button2);
Button button2pre = (Button) findViewById(R.id.button2pre);
Intent intent = getIntent();
final int score = intent.getIntExtra("int", -1);
final TextView result2 = (TextView) findViewById(R.id.txtResult2);
result2.setText("Result counting: " + String.valueOf(score));
button2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int correctId2 = (R.id.answer2b);
// get selected radio button from radioGroup
int selectedId2 = radioAnswerGroup2.getCheckedRadioButtonId();
// find the radio button by returned id
radioAnswerButton2 = (RadioButton) findViewById(selectedId2);
if (selectedId2==correctId2){
score = score + 1;
//show toast saying it is correct
//Context context = getApplicationContext();
//CharSequence text = ("You are correct!");
//int duration = Toast.LENGTH_SHORT;
//Toast toast = Toast.makeText(context, text, duration);
//toast.show();
}
else{
score = score - 1;
//toast incorrect
//Context context = getApplicationContext();
//CharSequence text = ("You are wrong but it's ok and the answer is Data Link");
//int duration = Toast.LENGTH_LONG;
//Toast toast = Toast.makeText(context, text, duration);
//toast.show();
}
Intent intent2 = new Intent(App2Activity.this, App3Activity.class);
intent2.putExtra("int", score);
startActivity(intent2);
}
});
button2pre.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, AppActivity.class);
startActivity(intent);
}
});
}
}
Move int score to be a global variable to access it in onClick. You'll also need to remove the final keyword so the value can be changed after you initialize it.
public class YourActivity extends Activity{
int score;
public onCreate( /*...etc.*/
Simply remove final keyword from :
final int score = intent.getIntExtra("int", -1);
Because a final variable can only be initialized once, either via an initializer or an assignment statement.
Read more here.

Categories

Resources