I have two identical views with a number of editTexts. In one, pre-defined answers are populated in the editTexts (but not shown to the user). In the second, the user starts with all blank editTexts, and then fills them out in an attempt to make them the same as the pre-defined answers.
So I want to loop through the user's view, checking it against the pre-defined one, until an inequality is found, in which case the method will return false.
My code is below. Inside the onCreate I have a buttonListener (when the user is ready to check answers)
btnSolution.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(checkAnswer() == true){
Toast.makeText(getBaseContext(), "all good!", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getBaseContext(), "no good", Toast.LENGTH_LONG).show();
}
}
});
the checkAnswer() method is then defined as follows
public boolean checkAnswer() {
final int ROW_COUNT = 15;
final int COL_COUNT = 10;
final String ROWS[] = {"R1","R2","R3","R4","R5","R6","R7","R8","R9","R10","R11","R12","R13","R14","R15"};
final String COLS[] = {"C1","C2","C3","C4","C5","C6","C7","C8","C9","C10"};
for(int i=0; i<ROW_COUNT; i++) {
for(int j=0; j<COL_COUNT; j++) {
String a = ROWS[i];
String b = COLS[j];
int editTextBaseId = getResources().getIdentifier("box" + a + b, "id", getPackageName());
int editTextAnswerId = getResources().getIdentifier("boxA" + a + b, "id", getPackageName());
EditText editTextBase = (EditText)findViewById(editTextBaseId);
EditText editTextAnswer = (EditText)findViewById(editTextAnswerId);
String textBase = editTextBase.getText().toString();
String textAnswer = editTextAnswer.getText().toString();
if(textBase.equals(textAnswer)) {
}
else {
return false;
}
}
}
return true;
}
Unfortunately when I try and run this I am getting a crash and the following error in my LogCat
12-17 00:05:02.075: E/SKIA(16370): FimgApiStretch:stretch failed
Any obvious errors?
That's not an error itself. I guess you're using a Samsung as your target device, if so, don't worry about it.
In the other hand, maybe it's better to compare only the strings. All those findViewById are inneficient.
Looking at your code:
EditText editTextAnswer = (EditText)findViewById(editTextAnswerId);
Do you have both views in the same layout, and the one with the answers is hidden? I mean, if you have the view with blank editTexts as the content of your activity, you can't find the editText with the answer as it's in other xml (assuming you did it as a different xml).
Related
I'd like to show a series of 10 questions and have the user answer, and have the app show whether the answer is correct, and then show the next question.
Right now I can show the first question, check whether it's correct, and then display the second question. I don't know how to get this looping, however, to show all questions. Here is the relevant code:
public class MathTestActivity extends AppCompatActivity {
int i = 0;
int n = 20; /*How many rows this test*/
String[] mathTest = new String[40];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mathtest);
final TextView mathProblem = (TextView) findViewById(R.id.mathProblem);
final EditText mathAnswer = (EditText) findViewById(R.id.mathAnswer);
//Styling for the question text
mathProblem.setTextSize(40);
mathProblem.setTextColor(Color.rgb(0, 0, 0));
//Try to read the problem and answers text file
try {
InputStream is = this.getResources().openRawResource(R.raw.mediummath);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
int n = 20; /*How many rows this test has*/
/*read in file to array*/
for (i = 0; i < n; i=i+2) {
if ((line = reader.readLine()) != null)
mathTest[i] = line;
if ((line = reader.readLine()) != null)
mathTest[i+1] = line;
}
} catch (IOException e) {
e.printStackTrace();
}
mathProblem.setText(mathTest[0]);
Button enterButton = (Button) findViewById(R.id.enterButton);
enterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int correctcount = 0;
i = 0;
String answer = mathAnswer.toString() ;
String correctAnswer = mathTest[i+1];
if (answer.equals(correctAnswer)){
Toast.makeText(MathTestActivity.this,
R.string.correct_toast,
Toast.LENGTH_SHORT).show();
correctcount++;
i = i + 2;
mathProblem.setText(mathTest[i]);
correctAnswer = mathTest[i+1];
}
else{
Toast.makeText(MathTestActivity.this,
correctAnswer,
Toast.LENGTH_SHORT).show();
i = i + 2;
mathProblem.setText(mathTest[i]);
correctAnswer = mathTest[i+1];
}
}
});
}
}
You can't count the correct answers with a local variable that gets set to 0 each time you click the button. :)
You should move int correctcount = 0; outside of the listener and next to your i and n variables.
You will also want to remove the i = 0; line from inside the button click because that will reset you back to the first question every time you click the button.
Also, since these three lines are duplicated between the if and the else, you can just place them directly after the else.
i = i + 2;
mathProblem.setText(mathTest[i]);
correctAnswer = mathTest[i+1]; // this isn't needed, though
You can try putting your questions in ViewPager if you want to make the questions shown in sliding presentation (http://developer.android.com/training/animation/screen-slide.html).
Or you can put your question inside a ListView if you want to view the question from top to bottom. (http://developer.android.com/guide/topics/ui/layout/listview.html)
EDIT:
Actually you are close to achieve what you want to do.
You should delete i = 0; inside your button onClick() function as it prevents you from going to next questions (3rd, 4th, etc). You might want to consider clearing the mathAnswer EditText when the user submits a question.
Also, it is not necessary to set correctAnswer = mathTest[i+1]; inside your if-else function.
Use arraylist for questions array and answer array.use view pager with two layouts questions and answer layout.if the answer array of position equal to the user answer its correct answer like u can dynamically
I am developing a card game. I divide 13 cards to each client using Server,
when I divide 13 cards to 1st player, 9 cards are invisible and remaining 4 are visible.
Now I want when I click this one Image, the remaining 9 cards gets visible?
How to do this?
- the code is this:
String str=" "c,a", "c,k", "c,q", "c,j", "c,10", "c,9", "c,8", "c,7", "c,6", "c,5", "c,4", "c,3", "c,2"";
drawCards(str);
private void drawCards(String drawString) {
String[] separated = msgLog.split("\\,");
for (int i = 2; i < separated.length - 1; i += 2) {
String symbol = separated[i];
String num = separated[i + 1];
String resourceName = symbol + num;
//symbol and number is used for get image from xml file
int resID = getResources().getIdentifier(resourceName, "id", getPackageName());
im = (ImageView) findViewById(resID);
Context context = im.getContext();
cardID = context.getResources().getIdentifier(resourceName, "drawable", context.getPackageName());
//9 card invisible
if ( i > 10) {
im.setVisibility(View.GONE);
}
/* elseif(x.getVisibility() == VISIBLE)
{
x.setVisibility(INVISIBLE);
}*/
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(im.getLayoutParams());
lp.setMargins(counter * 5, 0, 0, 0);//left,right,top,bottom
im.setLayoutParams(lp);
im.setImageResource(cardID);
im.setOnClickListener(this);
counter = counter + 8;
}
}
public void onClick(View v) {
final String IdAsString = v.getResources().getResourceName(v.getId());
pieceToast = Toast.makeText(getApplicationContext(), idServer, Toast.LENGTH_SHORT);
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
pieceToast.show();
}
});
}
When I click this card how to hide card make visible
You can take the help from below given link:
https://stackoverflow.com/questions/41285814/how-to-make-visible-and-invisible-an-image-by-clicking-a-button-in-android-studi
If you still have question, let me know
You could play around with the visibility and use the methode setVisibility(View.VISIBLE) and setVisibility(View.GONE)
I am developing a simple questionnaire-like app which includes lots of radio buttons joined into groups and spinners. I have multiple activities (6); some of them having RBs and some Spinners to let the user answer the questions.
The following step, which I have trouble with, is how to fetch lots of selections (of all the radio buttons/choices) and possibly do that in a for loop (so I don't have to initialize each new variable 30+ times in a row for just one activity). I've already assigned IDs to all of the views, but am having a hard time how to actually fetch the selection, initialize a new var corresponding to the selection (let's say radio button 1 in radio group 1 gives me a new variable with a value of 1) and then make the variables available to all of the activities (should I use global when initializing?).
My failed attempt on generating 10 variables for the first "page"
public void goTo2(View v) {
checkRB();
Intent intent1 = new Intent(Vprasalnik1.this, Vprasalnik2.class);
startActivity(intent1);
finish();
}
public void checkRB()
{
for (int i=0;i<9;i++)
{
RadioButton "vRB" + i; //I'd like to loop and initialize vars by adding a number to them (vRB1, vRB2, ...)
}
}
Put variables into array like a
int size = 9;
RadioButton[] views = new RadioButton[size];
public static checkRB()
{
for(int i=0;i<size;i++)
{
views[i] = (RadioButton)findViewByID(...);//For example
}
}
Or make a structure :
public class Choise
{
int mRadioButtonChoise;
int mSpinnerChoise;
}
And use something like this:
...
Choise c = new Choise();
c.mRadioButtonChoise = yourRadioButtonID;
c.mSpinnerChoise = youtSpinnerChoiseID;
...
Using a variable to identify a resource:
RadioButton[] rb = new RadioButton[size];
public static checkRB()
{
for(int i=0;i<size;i++)
{
int id = context.getResources().getIdentifier("vRB" + i, "id", context.getPackageName())
rb[i] = (RadioButton)findViewByID(id);
}
}
If you have an array of RadioButtons then you can get all the values at the same time, however initializing them will have to be manual.
RadioButton rb[];
boolean rbc[];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rbc=new boolean[200];
rb=new RadioButton[200]();
rb[0]=(RadioButton)findViewById(R.id.rb1);
rb[1]=(RadioButton)findViewById(R.id.rb2);
rb[2]=(RadioButton)findViewById(R.id.rb3);
rb[3]=(RadioButton)findViewById(R.id.rb4);
// many more.
}
public void checkRB()
{
for (int i=0;i<9;i++)
{
rbc[i]=rb.isChecked(); //I'd like to loop and initialize vars by adding a number to them (vRB1, vRB2, ...)
}
}
Then before starting your intent add all relevant data to it.
So I've managed to cramp up the radio buttons activity, so that it finally works. If anyone is interested - I've used tags in xml code to properly assign values (1, 2 and 3 for each group of buttons) and managed to get an output in my testToast. At least I didn't have to initialize all of the variables manually - I've been saving the values into an ArrayList and then appended to them via StringBuilder.
Thanks to everyone who tried to help - it turned out I've needed a bit more research, testing and teasing my half-awake brain.
btn = (Button) findViewById(R.id.v3_btn1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for(int i = 1; i <= 36; i++)
{
tmpRGid = "radioGroup_v3q" + i;
tmp2RGid = getResources().getIdentifier(tmpRGid, "id", getPackageName());
RGid = (RadioGroup) findViewById(tmp2RGid);
selectedOption = RGid.getCheckedRadioButtonId();
RBid = (RadioButton) findViewById(selectedOption);
addToIDList.add((String)RBid.getTag());
}
String testToast = "";
StringBuilder builder = new StringBuilder();
builder.append("Vaša izbira (");
for (int z=0; z < addToIDList.size(); z++) {
testToast = addToIDList.get(z);
builder.append(testToast + ", ");
}
builder.setLength(builder.length() - 2);
builder.append(") je bila shranjena.");
Toast.makeText(Vprasalnik3.this, builder, Toast.LENGTH_LONG).show();
I have a list view, in that list view, I have 30 items with edit text in which I manually put the value and after that I calculate the total of value set on edit text for 30 items. But problems is it calculate the total of only visible list items which are almost 10 and I need all 30 values of edit text.after 10 items view become null.
How to resolve this problem.
totalpoints.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*for (int i = 0; i < summaryList.size(); i++)
{
summaryList.get();
}*/
for (int i = 0; i < listView_subCategory.getCount(); i++) {
view = listView_subCategory.getChildAt(i);
if (view == null) {
} else {
try {
EditText text = (EditText) view
.findViewById(R.id.et_date);
TextView tv_productname=(TextView) view.findViewById(R.id.textView_userName);
String points = text.getText().toString().trim();
String productname=tv_productname.getText().toString().trim();
int point = Integer.valueOf(points);
count_summary = count_summary + point;
String truetotal = Integer.toString(count_summary);
et_total.setText(truetotal);
} catch (Exception e) {
Toast toast1 = Toast.makeText(getActivity(),
"Fill Value First", Toast.LENGTH_SHORT);
toast1.setGravity(Gravity.CENTER, 0, 0);
toast1.show();
}
}
}
count = 0;
}
});
I guess you should think fo a better approach than iterating over the EditTexts with getChildAt() to collect all the value.
I take it that the user can change the values in the EditTexts, you can have an Array of size 30 of Values and everytime the user enters / changes a value you change the according value in the Array. Use a listener that changes the values in your Array like this.
I am trying to create dynamic buttons. When clicking a button it should go to the specified url assigned to the text of the button.
For testing, first I tried to get that ID, if it is equal it prints the value of i. But whenever I clicked any one button, instead of telling that particular i value, it enters into whole loop, and prints all the values of i starting from 1 to 19 (the number of buttons that are dynamically created)
And after printing all values from 1 to 19, the program is getting force closed saying Null pointer exception.
I even tried by placing the handler code outside onCreate(), but I'm still getting the same error.
for ( i = 0; i <itemList.getTitle().size()-1; i++) {
title[i] = new TextView(this);
title[i].setTextColor( -16711936 );
title[i].setTextSize(18);
title[i].setText("Title = "+itemList.getTitle().get(i));
description[i] = new TextView(this);
description[i].setTextColor(-16776961);
description[i].setText("Description = "+itemList.getDescription().get(i)+"......");
more[i]=new Button(this);
more[i].setText(itemList.getLink().get(i));
layout.addView(title[i]);
System.out.println("Title view is set");
layout.addView(description[i]);
//System.out.println("Description view is set");
layout.addView(more[i]);
more[i].setOnClickListener(listener);
}
private OnClickListener listener=new OnClickListener(){
public void onClick(View arg) {
int index = 0;
for (i = 0; i < more.length; i++)
{
if (more[i].getId() == arg.getId())
{
index = i;
System.out.println("Value of i onclick is"+i);
}
}
//System.out.println("Vlaue of I in onclick"+i);
//Uri uri=Uri.parse(itemList.getLink().get(i));
//startActivity(new Intent(Intent.ACTION_VIEW,uri));
//Toast.makeText(getApplicationContext(), "This button is clicked"+i+more[i].getText()+itemList.getLink().get(i),Toast.LENGTH_LONG).show();
}
}
You can use setTag() and getTag() method of View to identify different button.
for (i = 0; i < itemList.getTitle().size()-1; i++) {
...
more[i].setTag(i); // Use index of itemList as the tag
}
In onClick:
int index = (Integer)arg.getTag();
you can also set the id of button
more[i].setid(i);
int index = 0;
for (i = 0; i < more.length; i++)
{
if (more[i].getId() == arg.getId())
{
index = i;
System.out.println("Value of i onclick is"+i);
}
}
As you can see here, i is still in your for loop.
Put the System.out.println("Value of i onclick is"+i); outside of your for loop and it should work
PS: format your code, it's easier to read that way and you'll notice small mistakes like these more easily
I think this will help you..
set button tag also dynamic like
more[i].setId(i);
and also changed condition like
if (more[i].getId() == i) {
index = i;
}
hope this will help you...