Generate Random integers upon Button Click without refreshing activity - java

Hey everyone :) Ive been scratching my head on this one, and can't seem to find an appropriate answer that works even though I'm sure its a simple issue.
I have a program which generates a random letter text on a group of buttons when another button being pressed.
When I open the application it loads fine and the first time the button is pressed it generates correctly, but after that I can't seem to get it to regenerate random letters.
I can accomplish what I want by adding an Intent, and essentially "refreshing" (not sure of the wording) the main activity but I would like to add a counter for the button clicks, and it resets when the activity does.
{Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
finish();
overridePendingTransition(0, 0);
I just cant seem to wrap my mind around how to do it otherwise. It's seems like I need to rerun the java every time the button is clicked. Any suggestions?
Here is some code, I used buttons rather than textview because I a)wanted to set an easy background b)may make them clickable later. Thanks so much in advance!
public class MainActivity extends Activity
{
Button spin;
Button reel1,reel2,reel3,reel4;
private String rnd,rnd2,rnd3,rnd4;
int count1=50;
#Override
protected void onCreate(Bundle savedInstanceState)
{super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();}
private static String rndm[] = {"A","B","C","D"};
{rnd = rndm[(int) (Math.random() * rndm.length)];}
private static String rndm2[] = {"A","B","C","D"};
{rnd2 = rndm2[(int) (Math.random() * rndm2.length)];}
private static String rndm3[] = {"A","B","C","D"};
{rnd3 = rndm3[(int) (Math.random() * rndm3.length)];}
private static String rndm4[] = {"A","B","C","D"};
{rnd4 = rndm4[(int) (Math.random() * rndm4.length)];}
public void perform_action(View v){}
public void addListenerOnButton() {
spin = (Button) findViewById(R.id.spin);
spin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
{Toast.makeText(getApplicationContext(),"button pressed", Toast.LENGTH_SHORT).show();}
{Button tv = (Button) findViewById(R.id.reel1);
tv.setText(String.valueOf(rnd));
tv.setTextColor(Color.parseColor("#000000"));}
{Button tv = (Button) findViewById(R.id.reel2);
tv.setText(String.valueOf(rnd2));
tv.setTextColor(Color.parseColor("#000000"));}
{Button tv = (Button) findViewById(R.id.reel3);
tv.setText(String.valueOf(rnd3));
tv.setTextColor(Color.parseColor("#000000"));}
{Button tv = (Button) findViewById(R.id.reel4);
tv.setText(String.valueOf(rnd4));
tv.setTextColor(Color.parseColor("#000000"));

I figured it out!!! Whoot. But I can't upvote myself for a correct answer.
public class MainActivity extends Activity
{
Button spin;
Button reel1,reel2,reel3,reel4;
private String rnd,rnd2,rnd3,rnd4;
int count1=50;
#Override
protected void onCreate(Bundle savedInstanceState)
{super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();}
public void perform_action(View v){}
public void addListenerOnButton() {
spin = (Button) findViewById(R.id.spin);
spin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String rndm[] = {"A","B","C","D"};
{rnd = rndm[(int) (Math.random() * rndm.length)];}
String rndm2[] = {"A","B","C","D"};
{rnd2 = rndm2[(int) (Math.random() * rndm2.length)];}
String rndm3[] = {"A","B","C","D"};
{rnd3 = rndm3[(int) (Math.random() * rndm3.length)];}
String rndm4[] = {"A","B","C","D"};
{rnd4 = rndm4[(int) (Math.random() * rndm4.length)];}
{Toast.makeText(getApplicationContext(),"button pressed", Toast.LENGTH_SHORT).show();}
{Button tv = (Button) findViewById(R.id.reel1);
tv.setText(String.valueOf(rnd));
tv.setTextColor(Color.parseColor("#000000"));}
{Button tv = (Button) findViewById(R.id.reel2);
tv.setText(String.valueOf(rnd2));
tv.setTextColor(Color.parseColor("#000000"));}
{Button tv = (Button) findViewById(R.id.reel3);
tv.setText(String.valueOf(rnd3));
tv.setTextColor(Color.parseColor("#000000"));}
{Button tv = (Button) findViewById(R.id.reel4);
tv.setText(String.valueOf(rnd4));
tv.setTextColor(Color.parseColor("#000000"));
I moved my random Strings into my Onclick event and removed the private and static parts. Then whala! Things work like a charm!

Related

How do I take a number input, change it, then out put it, with submit button?

I am completely lost and don't have enough knowledge on coding/android studio.
I have the EditTexts (FoodIncomeCounter, FoodCampX, and FoodUpgradeX) as inputs.
Then the TextView (FoodIncomeResult) as output.
The 1st button (IncomeSubmitButton) Works properly. The 2nd button (FoodCampSubmitButton) does not, I want it to take the input of the FoodCampXs and FoodUpgradeXs then do a calculation and put that into integer TotalFood, then output TotalFood to the FoodIncomeResult TextView.
How the heck do I do this? I feel like I am close but I don't know what is wrong.
Thank you for the help!!!
public class MainActivity extends AppCompatActivity {
// These are the global variables
EditText FoodIncomeCounter;
EditText FoodCamp1Counter, FoodCamp2Counter, FoodCamp3Counter, FoodUpgrade1Counter, FoodUpgrade2Counter, FoodUpgrade3Counter;
TextView FoodIncomeResult;
int FoodIncome;
int FoodCamp1, FoodCamp2, FoodCamp3, FoodUpgrade1, FoodUpgrade2, FoodUpgrade3;
int TotalFood;
Button IncomeSubmitButton, FoodCampSubmitButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//to get from user input and into variable form
FoodIncomeCounter = (EditText) findViewById(R.id.FoodIncomeCounter);
FoodIncomeResult = (TextView) findViewById(R.id.FoodIncomeResult);
IncomeSubmitButton = (Button) findViewById(R.id.IncomeSubmitButton);
FoodCamp1Counter = (EditText) findViewById(R.id.FoodCamp1Counter);
FoodCamp2Counter = (EditText) findViewById(R.id.FoodCamp2Counter);
FoodCamp3Counter = (EditText) findViewById(R.id.FoodCamp3Counter);
FoodUpgrade1Counter = (EditText) findViewById(R.id.FoodUpgrade1Counter);
FoodUpgrade2Counter = (EditText) findViewById(R.id.FoodUpgrade2Counter);
FoodUpgrade3Counter = (EditText) findViewById(R.id.FoodUpgrade3Counter);
FoodCampSubmitButton = (Button) findViewById(R.id.FoodCampSubmitButton);
//Submit button
IncomeSubmitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//to receive the inputted values
Food = Integer.parseInt(FoodIncomeCounter.getText().toString());
//to show the inputted values into the result fields
FoodIncomeResult.setText(FoodIncomeCounter.getText().toString());
}
});
//Submit button
FoodCampSubmitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//receive the inputted values
FoodCamp1 = Integer.parseInt(FoodCamp1Counter.getText().toString());
FoodCamp2 = Integer.parseInt(FoodCamp2Counter.getText().toString());
FoodCamp3 = Integer.parseInt(FoodCamp3Counter.getText().toString());
FoodUpgrade1 = Integer.parseInt(FoodUpgrade1Counter.getText().toString());
FoodUpgrade2 = Integer.parseInt(FoodUpgrade2Counter.getText().toString());
FoodUpgrade3 = Integer.parseInt(FoodUpgrade3Counter.getText().toString());
//get food income and show
TotalFood = FoodCamp1 + (FoodCamp2 * 2) + (FoodCamp3 * 3) + (FoodUpgrade1 * 2) + (FoodUpgrade2 * 4) + (FoodUpgrade3 * 6);
FoodIncomeResult.setText(String.valueOf(TotalFood));
}
});
}
}

Android add EditText dynamically

at the click of the button, I want to create EDITTEXT dynamically and display them vertically. I have this code but it just creates one EditText. Where am I wrong? Thanks for your help.
private LinearLayout containerLayout;
static int totalEditTexts = 0;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_category);
containerLayout = (LinearLayout)findViewById(R.id.relative1);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
totalEditTexts++;
EditText editText = new EditText(getBaseContext());
containerLayout.addView(editText);
editText.setGravity(Gravity.LEFT);
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) editText.getLayoutParams();
layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT;
layoutParams.setMargins(23, 34, 0, 0);
editText.setLayoutParams(layoutParams);
editText.setTag("EditText" + totalEditTexts);
}
});
}
Your example works perfectly if your add_category.xml were to look like this:
https://gist.github.com/akodiakson/9d37e3e48d0798d106c3
So I'm guessing your Activity layout might be a little bit off.

I want to make a president review app in Android Studio that has pictures of every president, but I keep getting OutOfMemoryError

I have just started Android Studio and am also a little new to java, so please excuse the inefficient code.
Anyway, when I click on the button on the main activity on my app to take the user to the activity that I want to display the images, my app stops working and it throws an OutOfMemoryError.
Here is MainActivty.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button presidentQuizButton = (Button) findViewById(R.id.presidentQuizButton);
Button reviewPresidentsButton = (Button) findViewById(R.id.reviewPresidentsButton);
presidentQuizButton.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
//when button is clicked, do something
}
});
reviewPresidentsButton.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
//when button is clicked, do something
startActivity(new Intent(MainActivity.this, presidentReviewActivity.class));
}
});
}
Here is presidentReviewActivity.java:
ImageView imageView;
public int presidentNumber = 0;
private Drawable drawable;
private Drawable [] drawables = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_president_review);
Button menuButton = (Button) findViewById(R.id.menuButton);
Button nextButton = (Button) findViewById(R.id.nextButton);
Button backButton = (Button) findViewById(R.id.backButton);
drawables = new Drawable[]{
getResources().getDrawable(R.drawable.president1),
getResources().getDrawable(R.drawable.president2),
getResources().getDrawable(R.drawable.president3),
getResources().getDrawable(R.drawable.president4),
getResources().getDrawable(R.drawable.president5),
getResources().getDrawable(R.drawable.president6),
getResources().getDrawable(R.drawable.president7),
getResources().getDrawable(R.drawable.president8),
getResources().getDrawable(R.drawable.president9),
getResources().getDrawable(R.drawable.president10),
getResources().getDrawable(R.drawable.president11),
getResources().getDrawable(R.drawable.president12),
getResources().getDrawable(R.drawable.president13),
getResources().getDrawable(R.drawable.president14),
getResources().getDrawable(R.drawable.president15),
getResources().getDrawable(R.drawable.president16),
getResources().getDrawable(R.drawable.president17),
getResources().getDrawable(R.drawable.president18),
getResources().getDrawable(R.drawable.president19),
getResources().getDrawable(R.drawable.president20),
getResources().getDrawable(R.drawable.president21),
getResources().getDrawable(R.drawable.president22),
getResources().getDrawable(R.drawable.president23),
getResources().getDrawable(R.drawable.president24),
getResources().getDrawable(R.drawable.president25),
getResources().getDrawable(R.drawable.president26),
getResources().getDrawable(R.drawable.president27),
getResources().getDrawable(R.drawable.president28),
getResources().getDrawable(R.drawable.president29),
getResources().getDrawable(R.drawable.president30),
getResources().getDrawable(R.drawable.president31),
getResources().getDrawable(R.drawable.president32),
getResources().getDrawable(R.drawable.president33),
getResources().getDrawable(R.drawable.president34),
getResources().getDrawable(R.drawable.president35),
getResources().getDrawable(R.drawable.president36),
getResources().getDrawable(R.drawable.president37),
getResources().getDrawable(R.drawable.president38),
getResources().getDrawable(R.drawable.president39),
getResources().getDrawable(R.drawable.president40),
getResources().getDrawable(R.drawable.president41),
getResources().getDrawable(R.drawable.president42),
getResources().getDrawable(R.drawable.president43),
getResources().getDrawable(R.drawable.president44),
};
menuButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
finish();
}
});
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
presidentNumber++;
drawable = drawables[presidentNumber];
imageView.setImageDrawable(drawable);
}
});
And here is most of the error log:
http://imgur.com/xzFfPrq
Instead of store all the drawable content in an array. You can actually just store the resource id in a array.
replace private Drawable [] drawables = null; with private int[] drawableids
replace drawables = new Drawable[]{...} to drawableids = new int[]{...}
replace
drawable = drawables[presidentNumber];
imageView.setImageDrawable(drawable);
to
drawable = getResource().getDrawable(drawableids[presidentNumber]);
imageView.setImageDrawable(drawable);
Try to change as above steps and try again.
The nullpointerexception may be caused by you did not init the drawableids array or you are still using the drawables array instead of drawableids.
you are trying to load large size images directly into memory which causes out of memory exceptions,this issue is discussed in details and a nice solution is given in developers site

Displaying list values with each button click

How can i display list items on each button click. Lets say there are 4 names in the list. When I press next it displays the first name. Then when you press next it displays the second name and so on.
The only way I think is using the list.get() method. however I dont know how to use the method so that it knows how many values there are in the list and displaying then on each button hit. I think i need to use for method however I hadnt had any luck with it.
public class ZaidimasActivity extends ZaidejaiActivity {
public TextView mPlayer;
public TextView mKlausimas;
public Button mNext;
public Button mBack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zaidimas);
/** //get the player list from ZaidejaiActivity
Bundle recdData = getIntent().getExtras();
String myVal = recdData.getString("playerList"); */
Intent zaidejuInfo = getIntent();
Bundle extrasBundle = zaidejuInfo.getExtras();
final ArrayList<String> players = extrasBundle.getStringArrayList("playerList");
//show the first players name
mPlayer = (TextView)findViewById(R.id.ZaidejoVardas);
players.size();
mPlayer.setText(players.get(0));
mNext = (Button)findViewById(R.id.KitasBtn);
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPlayer.setText(players.get(1));
}
});
mBack = (Button)findViewById(R.id.GryztiMeniuBtn);
mBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent gryztiMeniu = new Intent(ZaidimasActivity.this, ZaidejaiActivity.class);
startActivity(gryztiMeniu);
}
});
}
Here you go, maintain a variable for storing the global array index and increment it every time the button is clicked.
private int count = 0; // Global array index. Make it as class field
final ArrayList<String> players = extrasBundle.getStringArrayList("playerList");
mPlayer = (TextView)findViewById(R.id.ZaidejoVardas);
players.size();
mPlayer.setText(players.get(0));
mNext = (Button)findViewById(R.id.KitasBtn);
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count++;
mPlayer.setText(players.get((count)%players.size())); //Incrementing global count and making sure it never exceeds the players list size
}
});

Text view if statement not working

Can anyone help me work out where I'm going wrong here. On the button click the media player plays one of the mfiles at random and I'm trying to set a textview depending on which file was played. Currently the setText if statements only match the audio playing half the time. Really not sure where I'm going wrong here.
private final int SOUND_CLIPS = 3;
private int mfile[] = new int[SOUND_CLIPS];
private Random rnd = new Random();
MediaPlayer mpButtonOne;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mfile[0] = R.raw.one;
mfile[1] = R.raw.two;
mfile[2] = R.raw.three;
//Button setup
Button bOne = (Button) findViewById(R.id.button1);
bOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final TextView textOne = (TextView)findViewById(R.id.textView1);
mpButtonOne = MediaPlayer.create(MainActivity.this, mfile[rnd.nextInt(SOUND_CLIPS)]);
if (mpButtonOne==null){
//display a Toast message here
return;
}
mpButtonOne.start();
if (mfile[rnd.nextInt(SOUND_CLIPS)] == mfile[0]){
textOne.setText("one");
}
if (mfile[rnd.nextInt(SOUND_CLIPS)] == mfile[1]){
textOne.setText("two");
}
if (mfile[rnd.nextInt(SOUND_CLIPS)] == mfile[2]){
textOne.setText("three");
}
mpButtonOne.setOnCompletionListener(new soundListener1());
{
}
So just to clarify the problem I am having is that the setText only matches the audio occasionally, not on every click. The rest of the time it displays the wrong text for the wrong audio.
You are choosing another random file
mfile[rnd.nextInt(SOUND_CLIPS)]
set that to a variable in onClick() then check against that variable in your if statement
public void onClick(View v) {
int song = mfile[rnd.nextInt(SOUND_CLIPS)];
final TextView textOne = (TextView)findViewById(R.id.textView1);
mpButtonOne = MediaPlayer.create(MainActivity.this, song);
if (song == mfile[0]){
textOne.setText("one");
}
Edit
To make it a member variable so you can use it anywhere in the class, just declare it outside of a method. Usually do this before onCreate() just so all member variables are in the same place and it makes your code more readable/manageable.
public class SomeClass extends Activity
{
int song;
public void onCreate()
{
// your code
}
then you can just initialize it in your onClick()
public void onClick(View v) {
song = mfile[rnd.nextInt(SOUND_CLIPS)];
final TextView textOne = (TextView)findViewById(R.id.textView1);
mpButtonOne = MediaPlayer.create(MainActivity.this, song);

Categories

Resources