Android: Randomly picking strings from an array - android
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);
}
});
Related
Perimeter in Android Studio
I'm supposed to generate two random numbers, then find the perimeter of a rectangle with them. Then it allows the User to input their answer in a EditText, when the User inputs their answer in the EditText, There is a submit button so that when the user clicks it, it lets the person know if their answer is correct or incorrect. This is displayed as a toast message. The problem i have, is when i click the submit button, it always show says "The answer is incorrect even if i put in the right value in the EditText. Would appreciate some help. Thank You public class Perimeter extends AppCompatActivity { #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_perimeter); 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) { Random rand = new Random(); int number = rand.nextInt(12) + 1; TextView myText = (TextView) findViewById(R.id.rand1); String myString = String.valueOf(number); myText.setText(myString); Random rand2 = new Random(); int number2 = rand2.nextInt(12) + 1; TextView myText2 = (TextView) findViewById(R.id.rand2); String 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){ int perimeter; Random randOne = new Random(); int number = randOne.nextInt(12) + 1; TextView myText = (TextView) findViewById(R.id.rand1); String myString = String.valueOf(number); myText.setText(myString); Random randTwo = new Random(); int number2 = randTwo.nextInt(12) + 1; TextView myText2 = (TextView) findViewById(R.id.rand2); String myString2 = String.valueOf(number2); myText2.setText(myString2); 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(); } } }
Your problem is that you are generating completely different random numbers when you go to check the answer. You need to save the numbers in instance variables like so. public class Perimeter extends AppCompatActivity { private int number1, number2; private Random rand; onCreate() { rand = new Random(); } PerimeterGame(View view) { number1 = rand.nextInt(12) + 1; number2 = rand.nextInt(12) + 1; } AnswerCheck(View view) { // Don't make new random variables here, just check your inputs. EditText num = (EditText)findViewById(R.id.answertext); int val = Integer.parseInt(num.getText().toString() ); int perimeter= 2*(number + number2); if (val == perimeter) { } } }
In AnswerCheck you dont need to generate new numbers again.. you need to get old generated numbers in first method PerimeterGame() and do your formula with them.
ANDROID - Save multiple images in database
I have an app in which I have to combine parts of clothes. To understand me better I have given a screenshot below. The thing is, that i am having problems on how to get these images and save them in my database. Of course i faced errors. public class ViewOutfit extends Activity { private DatabaseHandler handler; #Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.view_outfit); Intent i = getIntent(); final ImageView im1 = (ImageView) findViewById(R.id.im1); im1.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image1"))); im1.toString(); final ImageView im2 = (ImageView) findViewById(R.id.im2); im2.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image2"))); im2.toString(); final ImageView im3 = (ImageView)findViewById(R.id.im3); im3.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image3"))); im3.toString(); final ImageView im4 = (ImageView)findViewById(R.id.im4); im4.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image4"))); im4.toString(); final ImageView im5 = (ImageView)findViewById(R.id.im5); im5.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image5"))); im5.toString(); final ImageView im6 = (ImageView)findViewById(R.id.im6); im6.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image6"))); im6.toString(); ImageButton btn_save_outfit = (ImageButton)findViewById(R.id.btn_combine); btn_save_outfit.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) { im1.getDrawable().toString(); im2.getDrawable().toString(); im3.getDrawable().toString(); im4.getDrawable().toString(); im5.getDrawable().toString(); im6.getDrawable().toString(); Outfits outfits = new Outfits(); outfits.setImage1(String.valueOf(im1)); outfits.setImage2(String.valueOf(im2)); outfits.setImage3(String.valueOf(im3)); outfits.setImage4(String.valueOf(im4)); outfits.setImage5(String.valueOf(im5)); outfits.setImage6(String.valueOf(im6)); Boolean added = handler.addOutfit(outfits); if(added){ Toast.makeText(getApplicationContext() , "Outfit added." , Toast.LENGTH_LONG).show(); String log = "Id: "+ outfits.getID()+" ,Image1: " + outfits.getImage1() + " ,Image2: " + outfits.getImage2() + ",Image3:" + outfits.getImage3() + ",Image4:" + outfits.getImage5() + ",Image6:" +outfits.getImage6(); Log.d("Image1: ", log); }else{ Toast.makeText(getApplicationContext(), "Outfit not added. Please try again", Toast.LENGTH_LONG).show(); } }}); }
Duplicate Button in LinearLayout via Fragment
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
How to fetch edittext and text values created dynamically?
Am trying to create edittext and textview widgets dynamically into program. it works fine. now i want to access the textvalue with its corresponding edittext value. how to do it? Here is what i have tried. protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_callreport); dcname = ProductdetailsEnd.doctor; resultArr1 = ProductdetailsEnd.resultArr; callreportbtn = (Button) findViewById(R.id.callreportbtn); arraysize = resultArr1.length; TableLayout tb = (TableLayout) findViewById(R.id.tablelayout); for (int i = 0; i < arraysize; i++) { res = resultArr1[i]; TableRow tr = new TableRow(this); TableRow.LayoutParams pl = new TableRow.LayoutParams( TableRow.LayoutParams.MATCH_PARENT); tr.setLayoutParams(pl); tr.setWeightSum(1.0f); product = new TextView(this); product.setLayoutParams(new TableRow.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 0.7f)); product.setId(i); qty = new EditText(this); qty.setLayoutParams(new TableRow.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 0.3f)); qty.setId(i); qty.setWidth(50); product.setText(res); tr.addView(product); tr.addView(qty); tb.addView(tr, i); Log.d("Call Report name : ", "" + dcname); Log.d("Call Report prod :", "" + res); } Log.d("res length : ", "" + arraysize); for (int i = 0; i < arraysize; i++) { String product1 = resultArr1[i]; String qty1 = qty.getText().toString(); Log.d("products &&: ", "" + product1 + ":" + qty1); } callreportbtn.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) { // TODO Auto-generated method stub Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_LONG).show(); for (int i = 0; i < arraysize; i++) { String product1 = resultArr1[i]; String qty1 = qty.getText().toString(); Log.d("products &&: ", "" + product1 + ":" + qty1); } } }); } after entering the value, when i say submit it should display the textview value along with edittext value. For more convenience i have added a snap of my output. first image to enter the value second image is output in logcat.
There are many ways to do what you want. Place your views inside a List object, and read the list when you submit. Implement TextWatcher interface and record your String values as they change. Assign an Id to your views, and later retrieve your views by Id. Third option required you to carefully assign id's, because I think they must be unique. Second option, I think, is best one in many cases, since you may also want to provide some feedback to user. EDIT: TextWatcher is interface that receives callbacks from TextView. Simply call addTextChangedListener method and provide a TextWatcher implementation. aTextView.addTextChangedListener(new TextWatcher() { #Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } #Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } #Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } });
Finally i got the answer. referred this post - Creation of EditText Dynamically and get their text from each of EditText Created an array of the EditText and accessed it in the button onclick method. this is my code and its working. #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_callreport); dcname = ProductdetailsEnd.doctor; resultArr1 = ProductdetailsEnd.resultArr; callreportbtn = (Button) findViewById(R.id.callreportbtn); quantity = new ArrayList<EditText>(); arraysize = resultArr1.length; TableLayout tb = (TableLayout) findViewById(R.id.tablelayout); for (int i = 0; i < arraysize; i++) { res = resultArr1[i]; TableRow tr = new TableRow(this); TableRow.LayoutParams pl = new TableRow.LayoutParams( TableRow.LayoutParams.MATCH_PARENT); tr.setLayoutParams(pl); tr.setWeightSum(1.0f); product = new TextView(this); product.setLayoutParams(new TableRow.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 0.7f)); product.setId(i); qty = new EditText(this); qty.setLayoutParams(new TableRow.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 0.3f)); //qty.setId(i); qty.setWidth(50); product.setText(res); tr.addView(product); tr.addView(qty); tb.addView(tr, i); quantity.add(qty); Log.d("Call Report name : ", "" + dcname); Log.d("Call Report prod :", "" + res); } Log.d("res length : ", "" + arraysize); Log.d("qty length : ", "" + qty.length()); String[] items1 = new String[quantity.size()]; for (int i = 0; i < arraysize; i++) { String product1 = resultArr1[i]; items1[i] = quantity.get(i).getText().toString(); Log.d("qty id ", "" +qty.toString()); Log.d("products &&: ", "" + product1 + ":" + items1); } callreportbtn.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) { // TODO Auto-generated method stub Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_LONG).show(); String[] items = new String[quantity.size()]; for (int i = 0; i < arraysize; i++) { String product1 = resultArr1[i]; items[i] = quantity.get(i).getText().toString(); Log.d("products &&: ", "" + product1 + ":" + items[i]); } } }); }
TextViews become uneditable after reactivating activity?
So currently I am making an educational application where users can view how to solve a given problem by pressing a button. While my code works fine initially, when I hit the back button and click my View Solution button, my default layout pops up and I cannot edit the last four TextViews. Here is my code: public class AdditionTensSolutionActivity extends Activity { public static ArrayList<TextView> explain = new ArrayList<TextView>(3); public static Button nextstep; public static int onesnum1 = TensAdditionExerciseActivity.n1display % 10; public static int onesnum2 = TensAdditionExerciseActivity.n2display % 10; public static int onesanswer = onesnum1 + onesnum2; public static int onesanswermod = onesanswer % 10; public static int tensnum1 = TensAdditionExerciseActivity.n1display / 10; public static int tensnum2 = TensAdditionExerciseActivity.n2display / 10; public static int tensanswer = tensnum1 + tensnum2; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.showsolutionlayout); TextView numrow1 = (TextView) findViewById(R.id.solproblemrow1); TextView numrow2 = (TextView) findViewById(R.id.solproblemrow2); TextView solution = (TextView) findViewById(R.id.solutiontextview); TextView carryover = (TextView) findViewById(R.id.carryovernumbers); TextView exp1 = (TextView) findViewById(R.id.explain1); TextView exp2 = (TextView) findViewById(R.id.explain2); TextView exp3 = (TextView) findViewById(R.id.explain3); TextView exp4 = (TextView) findViewById(R.id.explain4); numrow1.setText(TensAdditionExerciseActivity.n1display + ""); numrow2.setText(" " + TensAdditionExerciseActivity.n2display + " +"); explain.add(exp1); explain.add(exp2); explain.add(exp3); explain.add(exp4); nextstep = (Button) findViewById(R.id.nextstep); for (int i = 0; i < 4; i++) { explain.get(i).setVisibility(View.GONE); } solution.setVisibility(View.GONE); carryover.setVisibility(View.GONE); explain.get(0).setText("test"); setTextViews(); nextButtonsetOnClickListener(); } protected void nextButtonsetOnClickListener() { nextstep.setOnClickListener(new View.OnClickListener() { int i = 0; public void onClick(View v) { explain.get(i).setVisibility(View.VISIBLE); i++; if (i > 2 && onesanswer < 10) { nextstep.setClickable(false); } if (i > 3 && onesanswer >= 10) { nextstep.setClickable(false); } } }); } protected void setTextViews() { explain.get(0).setText( "Add " + (onesnum1) + " and " + (onesnum2) + " which equals " + (onesanswer) + "."); if (onesanswer >= 10) { explain.get(1).setText( "Since the answer is 10 or greater, 1 must carry over to the tens place and " + onesanswermod + " is left in the ones place."); explain.get(2).setText( "Add the tens place digits, " + tensnum1 + " and " + tensnum2 + ". Don't forget to add the carried over 1!"); explain.get(3).setText( "1 + " + tensnum1 + " + " + tensnum2 + " = " + (tensanswer + 1)); } else { explain.get(1).setText( "Add the tens place digits: " + tensnum1 + " and " + tensnum2 + "."); explain.get(2).setText( tensnum1 + " + " + tensnum2 + " = " + tensanswer); } Ah, I figured it out. I had my ArrayList set to static rather than final, but I still do not completely the entirety of my error. Would someone be willing to tell me why it made such a big difference?
A static variable / method has only one instance for the entire class. That means, that in the case of your listview, only one exists for all instances of your activity in the entire app, which is why your getting your error. Final means that it can't be initialized anywhere other than the constructor or when the variable is defined. (Difference between Static and final?).