Using textView arrays for questionnaire app - android

I want to build a questionnaire type app with questions that show up individually and when a user submits an answer and clicks the button the data is stored in a textView above and the question goes to the next question where that answer is stored in a new textView. I am having difficulty getting the question to change to the next question.
Below I have attempted using the array method but have gotten errors both here
myTexts[0]=findViewById(R.id.question1);
myTexts[1]=findViewById(R.id.question2);
-- and
myTexts[questionNumber].setText(mEdit.getText().toString());
questionNumber++;
Below is complete source code:
package com.example.greg;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class menu extends Activity {
Button mButton;
EditText mEdit;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button)findViewById(R.id.button);
mEdit = (EditText)findViewById(R.id.userAnswereditText);
TextView [] myTexts = new TextView[2];
myTexts[0]=findViewById(R.id.question1);
myTexts[1]=findViewById(R.id.question2);
int questionNumber = 0;
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
myTexts[questionNumber].setText(mEdit.getText().toString());
questionNumber++;
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}

To change question you should have array of String or List of String that can hold all the question and as soon as button is clicked and the answer is stored in the TextView you will load the next question from that array or List of String that is holding the questions.
String [] questions;
int numberOfQuestions = 2;
and then in onCreate() method
questions=new String[numberOfQuestions];//numberOfQuestion refers to integer that holds total number of questions
questions[0]="This is first question?";
questions[1]="This is second question?";
and now in your view.onClickListener
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
myTexts[questionNumber].setText(mEdit.getText().toString());
questionNumber++;
//here you will have to load the next question
if(questionNumber < numberOfQuestions)
questionTextViewHolder.setText(questions[questionNumber]);
else
Toast.makeText(menu.this,"No more questions!",Toast.LENGTHLONG).show();
//Note one thing that your questionNumber variable should not increase myTexts length or questions length because if it does you will get exception
}
});
questionTextViewHolder is the TextView in which you are displaying the question that is to be answered, you will have to replace "questionTextViewHolder " with your textview in which you are displaying the questions !
Class name menu starting letter should be capital if you follow the coding conventions.

Shouldn't this...
myTexts[0]=findViewById(R.id.question1);
be a cast to TextView instead?...
myTexts[0]=(TextView)findViewById(R.id.question1);
That will definitely eliminate a ClassCastException

Related

Coding a calculator

I'm just a beginner in coding using Android studio and I have a couple of questions in coding a calculator (The calculator is used to only compute carbon emissions so it varies a little bit compared to an actual calculator):
How do I have a clear all button?
How do I add all of the
products that the user has calculated and show its sum? (Kind of like
how those tracking expenses kind of app)
This is my code so far:
package com.carschoolingpromo.scires.carschooling;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Calculator extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
Button caremissionscheck = findViewById(R.id.checkcar);
caremissionscheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent tocarbonemissions = new Intent(Calculator.this, CarbonEmissions.class);
startActivity(tocarbonemissions);
}
});
Button distancecheck = findViewById(R.id.checkdestination);
distancecheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent checkdistance = new Intent(Calculator.this, DistancesList.class);
startActivity(checkdistance);
}
});
final Button multiply =(Button)findViewById(R.id.multiply);
final EditText num1 =(EditText)findViewById(R.id.carboninput);
final EditText num2 =(EditText)findViewById(R.id.distanceinput);
final TextView ans =(TextView)findViewById(R.id.answer);
final TextView carbontotal=(TextView)findViewById(R.id.sumofcarbon);
multiply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
double n1 = Double.parseDouble(num1.getText().toString());
double n2 = Double.parseDouble(num2.getText().toString());
ans.setText(String.valueOf(n1*n2));
}
});
}
}
How do I have a clear all button?
You need to create a new button in the layout file, and get a reference of it in your code, then set a click listener on that reference. Then in the onClick() implementation you will clear your 2 edit texts and 2 text views, something like this:
final Button clearAll =(Button)findViewById(R.id.clear_all);
clearAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
num1.setText("");
num2.setText("");
ans.setText("");
carbontotal.setText("");
}
});
How do I add all of the products that the user has calculated and show its sum? (Kind of like how those tracking expenses kind of app)
For this you need to use some sort of a way to show a list on your UI, I suggest you look into this tutorial by google to creating lists

Replace string text?

I'm trying to develop an app that consists of multiple arrays and textviews and I've run into a problem.
I have 3 textviews and 2 arrays.
One of my arrays contains sentences.
My first question is how can I highlight specific words in each sentence?
Ex: "This is my first array item"
I need to highlight a word in the string so that when it is displayed in textview1, it will appear like this...
"This is my first array item"
My other array contains words. They are displayed in textview2 and should also be highlighted.
My next question is how can I replace the current highlighted word in textview1 with the new highlighted word from textview2, and also have a 3rd textview displaying the new sentence?
Ex: If the chosen item from my sentence array is "This is a test" (displayed in textview1) And the item from my word array is "website" (displayed in textview2) the result would be "This is a website" (displayed in textview3)
Here is my code so far
import java.util.Random;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Button;
public class Class1 extends Activity implements OnClickListener
{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_class1);
Button btn_sentence = (Button) findViewById(R.id.btn_sentence );
Button btn_word = (Button) findViewById(R.id.btn_word );
Button btn_newsentence = (Button) findViewById(R.id.btn_newsentence );
final Random ran = new Random();
final Resources res = getResources();
final TextView text1 = (TextView) findViewById(R.id.sentencetext);
final TextView text2 = (TextView) findViewById(R.id.wordtext);
final TextView text3 = (TextView) findViewById(R.id.newsentencetext);
btn_sentence.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String[] NewText = null;
NewText = res.getStringArray(R.array.sentences);
String strRandom = NewText[ran.nextInt(NewText.length)];
text1.setText(strRandom);
}
});
btn_word.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String[] NewText2 = null;
NewText2 = res.getStringArray(R.array.words);
String strRandom2 = NewText2[ran.nextInt(NewText2.length)];
text2.setText(strRandom2);
}
});
btn_newsentence.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
**text3.setText(" " + (text1.getText()) + " " + (text2.getText()) + " ");**
}
});
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}}
The bold text is as close as I've gotten, but all that really does is combine both TexttView1 and textview2, and display it in textview3... which isn't exactly what I want.
Help would be much appreciated
~TylerNormal
You can use simple HTML-tags, wrap your words you want to highlight into those using this:
TextView text = findViewByID(R.id.myTextView);
String test = "This is my first array item";
// example - the word in brackets is to be replaced and captured
// it is just an example to show how you can use it later with more
// complex cases
test = test.replaceAll("(first)", "<b>$1</b>");
text.setText(Html.fromHtml(test));

display answer in an maths game in Android

In my game i have a hash button which acts like a submit button. when i press the hash button it displays INCORRECT even if the answer is correct, Do i have to add a different if statement for each position in the array? It displays INCORRECT each expression.
(Sorry i'm a new in this)
package com.gamesup.braingame;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Easy extends Activity implements OnClickListener{
EditText display;
// This Array says , I am an array that holds arrays
String [][] multiArray = {{"4 + 5", "9"},
{"20 * 3","60"},
{"99 - 9","90"}};
TextView displayExpression;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.easy);
display = (EditText)findViewById(R.id.displayText);
display.setText("?");
displayExpression = (TextView) findViewById(R.id.expression);
Button generate = (Button) findViewById(R.id.random_gen);
generate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Random ranGenerate = new Random ();
int random = ranGenerate.nextInt(multiArray.length) ;
// Fetch your random question
String Rquestion = multiArray[random][0];
displayExpression.setText(Rquestion);
}
});
}
static boolean isEmpty = true;
public void num_Clicked(View v){
Button btn = (Button) findViewById(v.getId());
//getting the button object and using a view to get the id of the buttons
if (v.getId()== R.id.del_button){
String s = display.getText().toString();
s = s.substring(0, s.length() - 1);
display.setText(s);
return;
}
if(isEmpty){
display.setText(btn.getText());
isEmpty = false;
}
else{
display.append(btn.getText().toString());
}
public void hash_Clicked(View v){
if (v.getId()== R.id.hash_button){
// Get the Answer from your EditText
String answer = display.getText().toString();
// Using a for loop iterate on the base index
for(int i = 0; i < multiArray.length ; i++)
{
// if the answer is in position 1 of Array [i]
if(answer.equals(multiArray[i][1]))
{
// We have found the answer, Congratulate the User
displayExpression.setText("CORRECT");
}else{
// Tell them how bad they are since they can't solve simple equations!
displayExpression.setText("INCORRECT");
}
}
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Put break statement after you show that the answer is correct, so that you don't iterate through the remaining answers in your array and compare with current, because if you have a correct answer at say index 0, you are still going through the remaining answers in an array, so your "CORRECT" gets replaced by "INCORRECT".
// if the answer is in position 1 of Array [i]
if(answer.equals(multiArray[i][1]))
{
// We have found the answer, Congratulate the User
displayExpression.setText("CORRECT");
break; //<---add this to exit the loop, because correct answer has been found
}

Android Apptitude practice app

I want to develop an aptitude app..
for that in my text view i have to display first question .. On clicking next button i have to display second question.. on again clicking same next button third question have to be displayed.. liked that i want to display some 30 questions ..all questions should be displayed in single java file.I Tried to display two questions . but for multiple questions i could not find the code..
package com.example.asl;
import java.util.Arrays;
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Aptitude extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aptitude);
Button b=(Button) findViewById(R.id.button1);
final TextView tv=(TextView) findViewById(R.id.textView1);
final String Question[]={"what is UR Name","What is ur Age","Whats ur Qualification"};
Button btnNext = (Button) findViewById(R.id.button1);
final TextView cumulos = (TextView) findViewById(R.id.textView1);
//TextView respostas = (TextView)findViewById(R.id.respostas);
Random randPhrase = new Random();
final String[] cum = {"what is UR Name","What is ur Age","Whats ur Qualification"};
//String[] resp = getResources().getStringArray(R.array.resp_cumulos);
String textout = "";
String textresp = "";
//Button btnPrevious = (Button) findViewById(R.id.yourPreviousbutton);
btnNext.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
int i = 0;
if(i<cum.length-1){
i+=1;
cumulos.setText(cum[i]);
// respostas.setText(resp[i]);
}
}
});
//btnPrevious.setOnClickListener(new OnClickListener(){
//public void onClick(View arg0) {
//if(i>0){
// i-=1;
// cumulos.setText(cum[i]);
// respostas.setText(resp[i]);
// }
// }
//});
}
}
enter code here
Initializing your counter in your onClick() is always going to reset it
Initialize it outside of onClick() and increment it in onClick() as you are.
public class Aptitude extends Activity {
int i = 0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aptitude);
Button b=(Button) findViewById(R.id.button1);
...
}
public void onClick(View arg0) { // rename arg0 to something meaningful
// like v or view for readibility
// int i = 0; remove this guy
if(i<cum.length-1){
i+=1;
cumulos.setText(cum[i]);
If this doesn't fix your problem then please explain what the problem is but I'm sure this part was causing you trouble.

How to set numeric value in EditText?

I want to make a simple calculator My code is below:
package som.dev.android.calc;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class CalcApp extends Activity {
/** Called when the activity is first created. */
Button addValues, subValues, equalsValue;
EditText inputValue;
int inputNum = 0;
public int value1;
public int value2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// initializing Views
inputValue = (EditText) findViewById(R.id.editText1);
addValues = (Button) findViewById(R.id.addBtn);
subValues = (Button) findViewById(R.id.subBtn);
equalsValue = (Button) findViewById(R.id.equalsBtn);
// adding onClick Listeners
addValues.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
pressed = true;
value1 = Integer.parseInt(inputValue.getText().toString());
inputValue.setText("");
}
});
equalsValue.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
value2 = Integer.parseInt(inputValue.getText().toString());
int result = value1+value2;
inputValue.setText(result);// There an exception occurs....
}
});
}
}
But it does not sets result to Edittext in my app and an exception occurs and message comes Unfortunately app is colsed some thing like that so please any one tell me the solution of this problem
use this inputValue.setText(""+result);instead of inputValue.setText(result);// There an exception occurs....
just conversion integer into string
The reason you get an exception is that the EditText thinks you are setting a resource id. You need to convert the integer to a string yourself Integer.toString(result) before using it in the EditText Object. http://developer.android.com/reference/android/widget/TextView.html
change Following Line:-
inputValue.setText(result);
to
inputValue.setText(String.Valueof(result));
then your error is solved.

Categories

Resources