I have seen a decent amount of methods to add a numerical value to an int integer value using intent(). Mine however is not working so well. Does anyone have any advice? I am sending an integer value, via a button, from a separate activity using theintent() method. This value should add 1 to the activity when the button is pressed. Here is what I have so far:
public class GameEmulator extends Activity{
//Creating two static values to pass strings from SelectPlayer classes
public final static String value = "EMPTY_VALUE";
public final static String value2 = "EMPTY_VALUE2";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
//Button created to go back to AddPlayer activity
Button addplayer1 = findViewById(R.id.button9);
addplayer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(GameEmulator.this, AddPlayer.class);
startActivity(i);
}
});
Button viewScores = findViewById(R.id.viewScore);
viewScores.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(GameEmulator.this, MainActivity.class);
startActivity(intent);
}
});
//Button for player one winning
Button winButtonOne = findViewById(R.id.button7);
winButtonOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int scored = 1;
Intent intent = new Intent(GameEmulator.this, Scoreboard.class);
intent.putExtra("MY_KEY", scored);
startActivity(intent);
}
});
TextView textView = findViewById(R.id.name1);
TextView textview2 = findViewById(R.id.name2);
//setting value retrieved from SleectPlayer and Displaying it in textView
Intent intent = getIntent();
String extra = intent.getStringExtra(value);
textView.setText(extra);
//setting value retrieved from SleectPlayer2 and Displaying it in textView2
Intent in = getIntent();
String extra1 = in.getStringExtra(value2);
textview2.setText(extra1);
}
}
public class Scoreboard extends Activity{
public static ArrayAdapter<String> adapter2;
public static ArrayAdapter<String> adapter3;
public static ArrayList<String> list2 = new ArrayList<>();
public static ArrayList<String> list3 = new ArrayList<>();
ListView selectView3;
ListView selectView4;
public static int losses1 = 0;
public static int ties1 = 0;
public static int losses2 = 0;
public static int ties2 = 0;
public final static String value2 = "EMPTY_VALUE2";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scoreboard);
selectView3 = findViewById(R.id.selectview3);
selectView3.setVisibility(View.VISIBLE);
selectView4 = findViewById(R.id.selectview4);
selectView4.setVisibility(View.VISIBLE);
//Using adapter for ListView menu
adapter2 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list2);
selectView3.setAdapter(adapter2);
//Using intent to retrieve string from AddPlayer Activity
Intent i = getIntent();
int score = getIntent().getIntExtra("MY_KEY", 1);
String data = i.getStringExtra("text_key");
if(data != null){
list2.add("Player 1"+"\n"+"Name: "+data+"\n"+"Wins: "+ score +"\n"+"Losses: "+ losses1+"\n"+"Ties: "+ ties1);
}
if(data != ""){
changeList();
}
adapter3 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list3);
selectView4.setAdapter(adapter3);
Intent intent = getIntent();
String extra= intent.getStringExtra(value2);
if(extra != null) {
list3.add("Player 2" + "\n" + "Name: " + extra + "\n" + "Wins: " + score + "\n" + "Losses: " + losses2 + "\n" + "Ties: " + ties2);
}
if(data != ""){
changeList();
}
}
public void changeList()
{
adapter2.notifyDataSetChanged();
}
}
This line:
String data = i.getStringExtra("text_key");
makes data = null because you did not put in the original intent an extra value with key "text_key"
So this code:
list2.add("Player 1"+"\n"+"Name: "+data+"\n"+"Wins: "+ score +"\n"+"Losses: "+ losses1+"\n"+"Ties: "+ ties1);
is never executed
This is my Code. When the user enters their answer and press the Submit Button which is the AnswerCheck Method, i would like the score to be shown in a TextView for example - if they input the right answer, the TextView would state 1 correct out of 1. I would like some help, Thanks
public class Perimeter extends AppCompatActivity {
private int number;
private int number2;
private String myString;
private String myString2;
private int perimeter;
private Random rand;
private Random rand2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_perimeter);
rand = new Random();
rand2 = new Random();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public void PerimeterGame(View view) {
number = rand.nextInt(12) + 1;
TextView myText = (TextView) findViewById(R.id.rand1);
myString = String.valueOf(number);
myText.setText(myString);
number2 = rand2.nextInt(12) + 1;
TextView myText2 = (TextView) findViewById(R.id.rand2);
myString2 = String.valueOf(number2);
myText2.setText(myString2);
((TextView) findViewById(R.id.question)).setText
("Find the perimeter of a rectange with a width of " + myString + "cm" + " and " + "length of " + myString2 + "cm" + ".");
}
public void AnswerCheck(View view) {
EditText num = (EditText) findViewById(R.id.answertext);
int val = Integer.parseInt(num.getText().toString());
perimeter = (number + number2 + number + number2);
if (val == perimeter) {
Toast.makeText(this, "The answer is correct", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "The answer is incorrect ", Toast.LENGTH_SHORT).show();
}
findViewById(R.id.showsolbutton).setEnabled(true);
}
}
Set two global int variables
private int totalQuestion = 0;
and private int correctQuestions = 0;
Inside public void PerimeterGame(View view) increment totalQuestion by one.
When the answer is correct, inside public void AnswerCheck(View view) increment correctQuestion by one.
Finally, display the text
youTextView.setText(String.valueOf(correctQuestions) + " correct out of " + String.valueOf(totalQuestion));
Hope it helps.
public class Perimeter extends AppCompatActivity {
// Code ommitted
private int totalQuestion = 0 ;
private int correctQuestions = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// Code ommitted
}
public void PerimeterGame(View view) {
// Increment totalQuestion
totalQuestion++;
number = rand.nextInt(12) + 1;
TextView myText = (TextView) findViewById(R.id.rand1);
myString = String.valueOf(number);
myText.setText(myString);
number2 = rand2.nextInt(12) + 1;
TextView myText2 = (TextView) findViewById(R.id.rand2);
myString2 = String.valueOf(number2);
myText2.setText(myString2);
((TextView) findViewById(R.id.question)).setText
("Find the perimeter of a rectange with a width of " + myString + "cm" + " and " + "length of " + myString2 + "cm" + ".");
}
public void AnswerCheck(View view) {
EditText num = (EditText) findViewById(R.id.answertext);
int val = Integer.parseInt(num.getText().toString());
perimeter = (number + number2 + number + number2);
if (val == perimeter) {
correctQuestions++;
Toast.makeText(this, "The answer is correct", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "The answer is incorrect ", Toast.LENGTH_SHORT).show();
}
findViewById(R.id.showsolbutton).setEnabled(true);
// Display text
youTextView.setText(String.valueOf(correctQuestions) + " correct out of " + String.valueOf(totalQuestion));
}
}
I have created a Fragment that uses a Receiver to take in data and present it dynamically (#runtime) on the View. However, everytime the receiver gets new data, the buttons get created and the view is not overriden, but added on with the previous button. The main problem lies within the Fragment class, as I have tested TextViews. Help me find the problem with this Fragment:
public class OneFragment extends Fragment{
SDReceiver sdr;
View v;
TextView tx;
LinearLayout main_layer;
public OneFragment() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_one, container, false);
tx = (TextView) v.findViewById(R.id.result);
main_layer = (LinearLayout) v.findViewById(R.id.dynamic_layout);
setupServiceReceiver();
onStartService();
return v;
}
public void onStartService(){
Intent intent = new Intent(getActivity(),ServiceHandler.class);
intent.putExtra("receiver",sdr);
getActivity().startService(intent);
}
public void setupServiceReceiver() {
// Setup GUI by accessing objects from ArrayList
sdr = new SDReceiver(new Handler());
sdr.setReceiver(new SDReceiver.Receiver() {
#Override
public void onReceiveResult(int resultCode, Bundle resultData) {
if (resultCode == Activity.RESULT_OK) {
try{
HashMap<Integer,String[]> resultValue = (HashMap<Integer,String[]>) resultData.getSerializable("itemList");
for(int i=0;i<resultValue.size();i++){
String data[] = resultValue.get(i);
String resultString = data[1] + ", " + data[2] + ", " + data[3] + ", " + data[4] + "\n";
Button button1 = new Button(v.getContext());
button1.setId(i);
button1.setText(resultString);
//button1.setOnClickListener(getOnClickDoSomething(button1));
main_layer.addView(button1);
//tx.setText(bee);
}
}catch(NullPointerException e){
e.printStackTrace();
}
//tx.setText(values);
}
}
});
}
}
Remove the old Buttons from your LinearLayout before adding the new ones. You can use removeAllViews() method:
main_layer.removeAllViews(); // to remove the old Buttons
for(int i=0;i<resultValue.size();i++){// then you can loop to add the new ones
String data[] = resultValue.get(i);
String resultString = data[1] + ", " + data[2] + ", " + data[3] + ", " + data[4] + "\n";
Button button1 = new Button(v.getContext());
button1.setId(i);
button1.setText(resultString);
main_layer.addView(button1);
}
The answer is, assign a value to a variable does not mean your recreated a view, already drawn on a screen.
First, try to remove already added button by main_layer.removeView(button1) and then create and add a new one
I'm trying to randomly pick a string from an array and spit it out to the user, but whenever I try to run it via AVD the app crashes. I'm very much a novice at this, and can't figure out what to do.
Here is my code:
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final LinearLayout rr = new LinearLayout (this);
// setting up the LinearLayout. I'll get to proper formatting one I get the code running.
Button b1 = new Button (this);
b1.setId(R.id.Button01);
b1.setText("Generate");
rr.addView(b1);
final TextView tv;
tv = new TextView(this);
tv.setId(R.id.Text1);
rr.addView(tv);
setContentView(rr);
final String [] columnA = { "artless", "bawdy", "beslubbering", "bootless", "churlish", "cockered", "clouted", "craven", "currish", "dankish", "dissembling", "droning", "errant", "fawning", "fobbing", "froward", "frothy", "gleeking", "goatish", "gorbellied", "impertinent", "infectious", "jarring", "loggerheaded", "lumpish", "mammering", "mangled", "mewling", "paunchy", "pribbling", "puking", "puny", "qualling", "rank", "reeky", "roguish", "ruttish", "saucy", "spleeny", "spongy", "surly", "tottering", "unmuzzled", "vain", "venomed", "villainous", "warped", "wayward", "weedy", "yeasty" };
final String [] columnB = { "base-court", "bat-fowling", "beef-witted", "beetle-headed", "boil-brained", "clapper-clawed", "clay-brained", "common-kissing", "crook-patted", "dismal-dreaming", "dizzy-eyed", "doghearted", "dread-boiled", "earth-vexing", "elf-skinned", "fat-kidneyed", "fen-sucked", "flap-mouthed", "fly-bitten", "folly-fallen", "fool-born", "full-gorged", "guts-gripping", "hasty-witted", "half-faced", "hell-hated", "idle-headed", "ill-breeding", "ill-nurtured", "knotty-pated", "milk-livered", "motley-minded", "onion-eyed", "plume-plucked", "pottle-deep", "pox-marked", "reeling-riped", "rough-hewn", "rude-growing", "rump-fed", "shard-borne", "sheep-biting", "spur-galled", "swag-bellied", "tardy-gaited", "tickle-brained", "toad-spotted", "unchin-snouted", "weather-bitten"};
final String [] columnC = { "apple-john", "baggage", "barnacle", "bladder", "boar-pig", "bugbear", "bum-bailey", "canker-blossom", "clack-dish", "clotpole", "coxcomb", "codpiece", "death-token", "dewberry", "flap-dragon", "flax-wench", "flirt-gill", "foot-licker", "fustilarian", "giglet", "gudgeon", "haggard", "harpy", "hedge-pig", "horn-beast", "hugger-mugger", "joithead", "lewdster", "lout", "maggot-pie", "malt-worm", "mammet", "measle", "minnow", "miscreant", "moldwarp", "mumble-news", "nut-hook", "pigeon-egg", "pignut", "puttock", "pumpion", "ratsbane", "scut", "skainsmate", "strumpet", "varlot", "vassal", "whey-face", "wagtail"};
//Attempts to pick one string from each array, add "thou art a" and spaces, and display it to the device.
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String outputA;
Random r;
r = new Random(columnA.length);
Random s;
s = new Random(columnB.length);
Random t;
t = new Random(columnC.length);
outputA = "Thou art a" + " " + columnA[r.nextInt() % columnA.length] + " " + columnB[s.nextInt() % columnB.length] + " " + columnC[t.nextInt() % columnC.length];
tv.setText(outputA);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
I imagine you were getting an ArrayIndexOutOfBoundsException
To solve, remove all the Randoms and change your onClickListener to:
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String outputA = "Thou art a" + " " + columnA[(int) (Math.random() * columnA.length)] + " " + columnB[(int) (Math.random() * columnB.length)] + " " + columnC[(int) (Math.random() * columnC.length)];
tv.setText(outputA);
}
});
I'm trying to get an Image and want to put it into HashMap using `Button.onClickListener()
I am sure i am doing mistake here:
String s_image = imgv.toString();
I guess here i should use ImageView in place of String, but having doubt how and what code need to write
Logcat Says:
05-11 10:56:51.760: D/dalvikvm(299): GC_EXTERNAL_ALLOC freed 2253 objects / 144464 bytes in 48ms
05-11 10:57:16.500: D/Single(299): ImageURL :: http://2.imimg.com/data2/EE/RJ/MY-932393/children-suits-250x250.jpg
05-11 10:57:17.920: D/Single(299): Title :: Kids
05-11 10:57:17.920: D/Single(299): Image :: android.widget.ImageView#46092008
Single.java Code:
public class Single extends Activity {
public static final String LOG_TAG = "Single";
public static final String TAG_TITLE = "title";
public static final String TAG_IMAGE = "image";
String s_title, s_image;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.information_product);
Intent in = getIntent();
String title = in.getStringExtra(TAG_TITLE);
String image = in.getStringExtra(TAG_IMAGE);
Log.d(Single.LOG_TAG, "ImageURL :: " + image);
final ImageLoader imageLoader = new ImageLoader(getApplicationContext());
final ImageView imgv = (ImageView) findViewById(R.id.single_thumb);
final TextView txttitle = (TextView) findViewById(R.id.single_title);
txttitle.setText(title);
imageLoader.DisplayImage(image, imgv);
Button mImgAddCart = (Button) findViewById(R.id.button_add);
mImgAddCart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
s_title = txttitle.getText().toString();
Log.d(Single.LOG_TAG, "Title :: " + s_title);
s_image = imgv.toString();
Log.d(Single.LOG_TAG, "Image :: " + s_image);
if (Session.item_data.size() <= 0) {
HashMap<String, String> h_obj = new HashMap<String, String>();
h_obj.put(TAG_TITLE, s_title);
h_obj.put(TAG_IMAGE, s_image);
Session.item_data.add(h_obj);
}
}
});
Button mImgAddCart = (Button) findViewById(R.id.button_add);
mImgAddCart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
s_title = txttitle.getText().toString();
Log.d(Single.LOG_TAG, "Title :: " + s_title);
image = in.getStringExtra(TAG_IMAGE);
if (Session.item_data.size() <= 0) {
HashMap<String, String> h_obj = new HashMap<String, String>();
h_obj.put(TAG_TITLE, s_title);
h_obj.put(TAG_IMAGE, image);
Session.item_data.add(h_obj);
}
}
});