Multi-dimension String Array for MCQ app - android

I am trying to make an Simple MCQ app with the use of multidimension string array.
here is my code for MainActivity:
My question is how can I define array of answers. I done addition but it won't work.
public class MainActivity extends Activity {
RadioGroup radioGroup;
RadioButton rb1, rb2, rb3, rb4;
TextView tvquestion, tvtotallength_yy, tvpresentindex_xx;
Button previous, answer, next, result;
int q, a, wrong, count;
String[][] array = {{"Question 1", "Question 2", "Question 3", "Question 4", "Question 5", "Question 6", "Question 7", "Question 8", "Question 9", "Question 10"},
{
"1answerA", "1answerB", "1answerC", "1answerD",
"2answerA", "2answerB", "2answerC", "2answerD",
"3answerA", "3answerB", "3answerC", "3answerD",
"4answerA", "4answerB", "4answerC", "4answerD",
"5answerA", "5answerB", "5answerC", "5answerD",
"6answerA", "6answerB", "6answerC", "6answerD",
"7answerA", "7answerB", "7answerC", "7answerD",
"8answerA", "8answerB", "8answerC", "8answerD",
"9answerA", "9answerB", "9answerC", "9answerD",
"10answerA", "10answerB", "10answerC", "10answerD",
}
};
String[] ans = {"1answerA", "2answerD", "3answerC", "4answerA", "5answerB", "6answerB", "7answerA", "8answerC", "9answerD", "10answerD"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initialing text view
tvquestion = (TextView) findViewById(R.id.tvquestion);
tvtotallength_yy = (TextView) findViewById(R.id.tvyy);
tvpresentindex_xx = (TextView) findViewById(R.id.tvxx);
//initializing button
previous = (Button) findViewById(R.id.previous);
answer = (Button) findViewById(R.id.answer);
next = (Button) findViewById(R.id.next);
result = (Button) findViewById(R.id.result);
//initializing radio button
radioGroup = (RadioGroup) findViewById(R.id.radiogrp);
rb1 = (RadioButton) findViewById(R.id.optionA);
rb2 = (RadioButton) findViewById(R.id.optionB);
rb3 = (RadioButton) findViewById(R.id.optionC);
rb4 = (RadioButton) findViewById(R.id.optionD);
count = 0;
wrong = 0;
q = 0;
a = 0;
tvquestion.setText(array[0][q]);
rb1.setText(array[1][q]);
rb2.setText(array[1][q+1]);
rb3.setText(array[1][q+2]);
rb4.setText(array[1][q+3]);
tvpresentindex_xx.setText(String.valueOf(q + 1));
//setting the button to perform specific action
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
q--;
if (q == -1) {
q = array.length - 1;
tvquestion.setText(array[0][q]);
rb1.setText(array[1][q]);
rb2.setText(array[1][q + 4]);
rb3.setText(array[1][q + 8]);
rb4.setText(array[1][q + 12]);
tvpresentindex_xx.setText(String.valueOf(q + 1));
} else {
tvquestion.setText(array[0][q]);
rb1.setText(array[1][a]);
rb2.setText(array[1][q + 4]);
rb3.setText(array[1][q + 8]);
rb4.setText(array[1][q + 12]);
tvpresentindex_xx.setText(String.valueOf(q + 1));
}
}
});
answer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.optionA:
if (ans[q] == array[1][q]) {
count++;
} else {
wrong++;
}
break;
case R.id.optionB:
if (ans[q] == array[1][q + 4]) {
} else {
wrong++;
}
break;
case R.id.optionC:
if (ans[q] == array[1][q + 8]) {
} else {
wrong++;
}
break;
case R.id.optionD:
if (ans[q] == array[1][q + 12]) {
} else {
wrong++;
}
break;
}
}
});
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
radioGroup.clearCheck();
q++;
if (q == array.length) {
q = 0;
tvquestion.setText(array[0][q]);
rb1.setText(array[0][q]);
rb2.setText(array[0][q + 4]);
rb3.setText(array[0][q + 8]);
rb4.setText(array[0][q + 12]);
tvpresentindex_xx.setText(String.valueOf(q + 1));
} else {
tvquestion.setText(array[0][q]);
rb1.setText(array[1][q]);
rb2.setText(array[1][q + 4]);
rb3.setText(array[1][q + 8]);
rb4.setText(array[1][q + 12]);
tvpresentindex_xx.setText(String.valueOf(q + 1));
}
}
});
result.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Correct=" + count + " Incorrect=" + wrong, Toast.LENGTH_LONG).show();
}
});
}
}

Instead of storing the actual answer
String[] ans = {"1answerA", "2answerD", "3answerC", "4answerA", "5answerB", "6answerB", "7answerA", "8answerC", "9answerD", "10answerD"};
you can store the index of the answer like this. Suppose you have 10 question and 4 choices which you are storing in an array. So you can define an int array of answers like this
int[] answers_index = new int[]{1,2,2,3,1,1,3,3,1,4,4};

You can try storing the index of the answers as an integer array. For example, if your answers are a,d,c and b respectively for 4 questions, your answer array can be
[0,3,2,1]. Then number the radio buttons so that button 1 has is represented by 0 and so on. Finally, when the user enters an answer, you can compare the number representation of the button to the integer value in your answer array to check for correctness.
Hope this helps!

Related

Simple Math Game?

I am new in Android and I would like to create simple Math quiz. I have a one textview that I display random question with random operator as below code.I would like, user will input their answer to EditText and submit their answer with ImageButton that I called submit answer. My question is, I could not handle to check user answer on Edittext via different method.How can I check user answer that evaluate the answer after submitbutton ?
public class MainActivity extends AppCompatActivity {
int number1, number2, result;
public EditText answer;
char operator;
ImageButton submitAnswer;
Random rand = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random rnd = new Random();
number1 = rnd.nextInt(100) + 1;
number2 = rnd.nextInt(100) + 1;
generateOperator();
TextView question = findViewById(R.id.questionText);
question.setText(number1 + " " + operator + " " + number2 + " " + "=" + " " + "?");
}
public int generateOperator() {
int op = rand.nextInt(3) + 1;
if (op == 1) {
operator = '+';
result = number1+number2;
} else if (op == 2) {
operator = '-';
result= number1-number2;
} else if (op == 3) {
operator = '*';
result = number1+number2;
}
return operator;
}
public void submitAnswer(View view) {
submitAnswer = findViewById(R.id.submitButton);
submitAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if ( result == Integer.valueOf(answer.getText().toString())){
Toast.makeText(view.getContext(), "Correct",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(view.getContext(), "Wrong",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
First of all, edir your generateOperator() method to keep answer.
public int generateOperator() {
int op = rand.nextInt(3) + 1;
if (op == 1) {
operator = '+';
result = number1 + number2;
} else if (op == 2) {
operator = '-';
result = number1 - number2;
} else if (op == 3) {
operator = '*';
result = number1 * number2;
}
return operator;
}
And then you can simply compare your result and the user's answer.
submitAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(result == Integer.valueOf(answer.getText().toString())){
//Answer is ok.
}
else {
//Some code...
}
}
});

how to get which is selected when Checkbox and Radio button added programmatically in android

private void parseProductOptionData(JSONObject response){
try {
boolean success = response.getBoolean("success");
if(success){
rlProductOption.setVisibility(View.GONE);
//Get All the Categories
JSONArray data = response.getJSONArray("data");
if(data.length()!=0){
rlProductOptionQuantityTxt.setVisibility(View.VISIBLE);
for(int i= 0;i<data.length();i++){
//First Get Type
JSONObject optionQuantity = data.getJSONObject(i);
Log.d(TAG, "onResponse: option quantity"+optionQuantity);
//Create a Layout
llMainLayout = new LinearLayout(getActivity());
llMainLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
llMainLayout.setBackgroundResource(R.drawable.border_details);
llMainLayout.setOrientation(LinearLayout.VERTICAL);
llMainLayout.setPadding(10,0,10,5);
llProductOptionsSheet.addView(llMainLayout);
tvOptionTitleText= new TextView(getActivity());
tvOptionTitleText.setId(Integer.valueOf("1"+i));
tvOptionTitleText.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
tvOptionTitleText.setTypeface(Typeface.SERIF);
llMainLayout.addView(tvOptionTitleText);
tvOptionTitleText.setText(optionQuantity.getString("title"));
if(optionQuantity.getString("min_selection").equals("1") && optionQuantity.getString("max_selection").equals("1")){
RadioGroup maxAndMin = new RadioGroup(getActivity());
maxAndMin.setOrientation(LinearLayout.VERTICAL);
maxAndMin.clearCheck();
//maxAndMin.setId(Integer.valueOf("1"));
maxAndMin.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
Log.d(TAG, "Option length1 "+optionQuantity.getJSONArray("options").length());
for (int btnCount =0;btnCount<optionQuantity.getJSONArray("options").length();btnCount++){
RadioButton rdbtn = new RadioButton(getActivity());
//rdbtn.setId(i);
//if (btnCount==0)
rdbtn.setText(optionQuantity.getJSONArray("options").getJSONObject(btnCount).getString("name")+" ("+optionQuantity.getJSONArray("options").getJSONObject(btnCount).getString("price")+")");
maxAndMin.addView(rdbtn);
}
llMainLayout.addView(maxAndMin);
}else if(optionQuantity.getString("min_selection").equals("0") && optionQuantity.getString("max_selection").equals("1")){
RadioGroup maxAndMin = new RadioGroup(getActivity());
maxAndMin.setOrientation(LinearLayout.VERTICAL);
maxAndMin.clearCheck();
//maxAndMin.setId(Integer.valueOf("1"));
maxAndMin.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
Log.d(TAG, "Option length1 "+optionQuantity.getJSONArray("options").length());
for (int btnCount =0;btnCount<optionQuantity.getJSONArray("options").length();btnCount++){
RadioButton rdbtn = new RadioButton(getActivity());
//rdbtn.setId(i);
rdbtn.setText(optionQuantity.getJSONArray("options").getJSONObject(btnCount).getString("name")+" ("+optionQuantity.getJSONArray("options").getJSONObject(btnCount).getString("price")+")");
maxAndMin.addView(rdbtn);
}
llMainLayout.addView(maxAndMin);
}else{
Log.d(TAG, "Option length2 "+optionQuantity.getJSONArray("options").length());
for (int btnCount =0;btnCount<optionQuantity.getJSONArray("options").length();btnCount++){
Log.d(TAG, "Option data fetch "+optionQuantity.getJSONArray("options").getJSONObject(btnCount).getString("name"));
CheckBox cbMaxOption = new CheckBox(getActivity());
cbMaxOption.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
cbMaxOption.setText(optionQuantity.getJSONArray("options").getJSONObject(btnCount).getString("name")+" ("+optionQuantity.getJSONArray("options").getJSONObject(btnCount).getString("price")+")");
llMainLayout.addView(cbMaxOption);
}
}
}
}else{
Log.d(TAG, "No product option ");
rlProductOptionQuantityTxt.setVisibility(View.VISIBLE);
}
btnAddToCart = new Button(getActivity());
btnAddToCart.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
btnAddToCart.setBackgroundColor(getResources().getColor(R.color.color_btn_login));
btnAddToCart.setText(getActivity().getResources().getString(R.string.add_to_cart));
btnAddToCart.setTypeface(Typeface.SERIF);
btnAddToCart.setTextColor(Color.WHITE);
llProductOptionsSheet.addView(btnAddToCart);
btnAddToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvOptionTitleText.setError("please fill all the text");
}
});
}else{
rlProductOption.setVisibility(View.GONE);
Toast.makeText(getActivity(),response.getString("message"),Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(),"Sorry try Later!!!",Toast.LENGTH_SHORT).show();
rlProductOption.setVisibility(View.GONE);
}
}
This is my code in which i have add radio button and checkbox according to json data.So when i click on a button "btnAddToCart" then i want to know all the selected checkbox and radio button.beacuse i have to store all the selected data in my session.
Declare a global variable like:
int rlProductOptionQuantityTxt =0;// for default case
Use Switch case,
#Override
public void onClick(View view)
{
switch (view.getId())
{
case R.id.yourRadioButton:
rlProductOptionQuantityTxt =1;
}
}
and then you can directly use the value of your global variable.
SetGet.setProductOptionQuantityTxt(rlProductOptionQuantityTxt );
int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
View radioButton = radioButtonGroup.findViewById(radioButtonID);
int idx = radioButtonGroup.indexOfChild(radioButton);

Cart Count increment & decrement while clicking button

I populates cart items into the list using cursor adapter. My ListView item has
Price TextView
Product Name TextView
Count TextView
Increment Button
Decrement Buttton
When I click the increment / decrement button the value is incremented/ decremented in a certain condition of AFTER TOUCHING THE LISTVIEW ROW,otherwise the count is not changed.
In some case, if I click the 1st row increment button ,item count is incremented in 2nd row.
NOTE:
1. I am populating List using Cursor Adapter.
2. Using Increment & Decrement clicklistener in activity class.
Here is my code:
cartList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> parent, View itemView, final int position, final long rowId) {
txt_cartProduct = (TextView) itemView.findViewById(R.id.cartProduct);
txt_cartQuantity = (TextView) itemView.findViewById(R.id.cartQuantity);
txt_cartPrice = (TextView) itemView.findViewById(R.id.cartPrice);
txt_cartPriceDum = (TextView) itemView.findViewById(R.id.cartPriceDum);
txt_cartCount = (TextView) itemView.findViewById(R.id.cartCount);
img_ivDecrease = (ImageView) itemView.findViewById(R.id.ivDecrease);
img_ivIncrease = (ImageView) itemView.findViewById(R.id.ivIncrease);
but_addTowish = (Button) itemView.findViewById(R.id.addTowish);
but_remove = (Button) itemView.findViewById(R.id.remove);
img_ivIncrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strPrice = txt_cartPrice.getText().toString();
price = Integer.parseInt(strPrice);
int counter = 0;
try {
counter = Integer.parseInt(txt_cartCount.getText().toString());
} catch (NumberFormatException e) {
e.printStackTrace();
}
counter++;
if (counter > 0) {
txt_cartCount.setText(Integer.toString(counter));
txt_cartPrice.setVisibility(View.GONE);
txt_cartPriceDum.setVisibility(View.VISIBLE);
quantity = txt_cartCount.getText().toString();
total = (Integer.parseInt(quantity)) * (price);
netA = String.valueOf(total);
sum += price;
if (sum == 0) {
netAmount = Integer.parseInt(txt_cartPriceDum.getText().toString());
}
netAmount = sum;
Log.e("Sum is", String.valueOf(sum));
txt_cartPriceDum.setText(String.valueOf(total));
cartCount = Integer.parseInt(quantity);
Toast.makeText(context, "netAmount" + netAmount + "\n" + "Total" + total, Toast.LENGTH_SHORT).show();
if (counter == 1) {
cartPrice = price;
cartSum = sum;
}
if (counter == 0) {
cartPrice = 0;
cartSum = 0;
cartCount = 0;
Toast.makeText(context, "Minimum Item is 1", Toast.LENGTH_SHORT).show();
}
int count_check = 1;
if (count_check >= position) {
count_check++;
} else if (count_check == 0) {
Toast.makeText(context, "Minimum Item is 1", Toast.LENGTH_SHORT).show();
}
}
}
});
img_ivDecrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strPrice = txt_cartPrice.getText().toString();
price = Integer.parseInt(strPrice);
int counter = 0;
try {
counter = Integer.parseInt(txt_cartCount.getText().toString());
} catch (NumberFormatException e) {
e.printStackTrace();
}
counter--;
if (counter > 0) {
txt_cartCount.setText(Integer.toString(counter));
txt_cartPrice.setVisibility(View.GONE);
txt_cartPriceDum.setVisibility(View.VISIBLE);
quantity = txt_cartCount.getText().toString();
total = (Integer.parseInt(quantity)) * (price);
netA = String.valueOf(total);
sum -= price;
if (sum == 0) {
netAmount = Integer.parseInt(txt_cartPriceDum.getText().toString());
}
Log.e("Sum - is", String.valueOf(sum));
txt_cartPriceDum.setText(String.valueOf(total));
cartCount = Integer.parseInt(quantity);
Toast.makeText(context, "netAmount" + netAmount + "\n" + "Total" + total, Toast.LENGTH_SHORT).show();
if (counter == 1) {
cartPrice = price;
cartSum = sum;
}
if (counter == 0) {
cartPrice = 0;
cartSum = 0;
cartCount = 0;
}
}
}
});
}
});
You can use setTag() and getTag() methods for saving the counter value in each list item.
Refer this answer for more details.

Check if EditText is empty

I am making a math app. I have two arrays with two sets of numbers. I make the app choose a random number from each array. The app displays that two numbers in a TextView. It asks the user to type in a EditText what the addition of the numbers is. Then when the user presses "Submit", the app will then tell the user if they are right or wrong.
The app works, but I have one main problem. If the user does not type anything in the EditText and presses "Submit", the app force closes. I have looked at other questions asking how to check if a EditText is empty. I tried different methods but it still does not work.
public class MainActivity extends Activity {
Button submitb, startb, idkb;
EditText et;
TextView tv, rig, wron;
int arrone[] = { 24, 54, 78, 96, 48, 65, 32, 45, 95, 13, 41, 55, 33, 22,
71, 5, 22, 17, 13, 29, 63, 72, 14, 81, 7 }; // One Set of Numbers//
int arrtwo[] = { 121, 132, 147, 79, 82, 723, 324, 751, 423, 454, 448,
524, 512, 852, 845, 485, 775, 186, 99 }; // Another set of Numbers//
int random1, random2, add;
int wrong = 0;
int right = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list();
startb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int num = (int) (Math.random() * 25);
int mun = (int) (Math.random() * 19);
random1 = arrone[num];
random2 = arrtwo[mun];
String yu = (random1 + " + " + random2 + " =");
tv.setText(yu);
et.setHint("");
idkb.setVisibility(0);
startb.setText("Next Question");
}
});
startb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int bread2 = 0;
if (bread2 == 0) {
Toast.makeText(getApplicationContext(),
"You didn't answer the question!",
Toast.LENGTH_LONG).show();
}
int swag = random1 + random2;
String bread = et.getText().toString();
bread2 = Integer.parseInt(bread);
if (bread2 == swag) {
startb.setText("Next Question");
tv.setText("Correct");
et.setText("");
et.setHint("Click Next Question");
right++;
rig.setText("Right:" + right);
rig.setTextColor(Color.parseColor("#14df11"));
bread2 = 0;
}
else if (bread2 == 0) {
tv.setText("Wrong, the correct answer is " + swag + ".");
startb.setText("Next Question");
et.setText("");
tv.setHint("Click Next Question");
wrong++;
wron.setText("Wrong:" + wrong);
wron.setTextColor(Color.parseColor("#ff0000"));
bread2 = 0;
}
else {
tv.setText("Wrong, the correct answer is " + swag + ".");
startb.setText("Next Question");
et.setText("");
et.setHint("Click Next Question");
wrong++;
wron.setText("Wrong:" + wrong);
wron.setTextColor(Color.parseColor("#ff0000"));
bread2 = 0;
}
}
});
idkb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int swag = random1 + random2;
tv.setText("The Correct Answer is " + swag + ".");
et.setText("");
tv.setHint("Click Next Question");
wrong++;
wron.setText("Wrong:" + wrong);
wron.setTextColor(Color.parseColor("#ff0000"));
}
});
}
private void list() {
submitb = (Button) findViewById(R.id.b1);
startb = (Button) findViewById(R.id.b2);
et = (EditText) findViewById(R.id.et1);
tv = (TextView) findViewById(R.id.tv1);
rig = (TextView) findViewById(R.id.rtv);
wron = (TextView) findViewById(R.id.wtv);
idkb = (Button) findViewById(R.id.idk);
}
Few points to consider:
you are setting OnClickListener on startb twice, is it just a typo?
in the second onClick(), you have a condition:
int bread2 = 0;
if (bread2 == 0) {
//rest of code
}
This condition will ALWAYS be satisfied, is that what you want?
you can check if there's nothing entered by use with the following:
String bread = et.getText().toString();
// check if there is any text entered by user
if (bread.length() > 0) {
bread2 = Integer.parseInt(bread);
if (bread2 == swag) {
startb.setText("Next Question");
//the rest of the code
}
Not sure I'm understanding you correctly, but it should be easy as:
et = (EditText) findViewById(R.id.et1);
String bread = et.getText().toString();
if (bread.length() == 0){
// raise error dialogue
} else {
// continue to check the parsed integer
}
This should all be done within your click listener.
You need to use findViewById on the et before gets its value.
By the way, you are setting bread2 value to 0, and on the next line verifying if it's 0, i suppose it's just a test, isn't it?
#Override
public void onClick(View v) {
int bread2 = 0;
if (bread2 == 0) {
Toast.makeText(getApplicationContext(),
"You didn't answer the question!",
Toast.LENGTH_LONG).show();
}
int swag = random1 + random2;
et = findViewById(R.id.yourEditText);
String bread = et.getText().toString();
bread2 = Integer.parseInt(bread);
//...
Hope it helps!
I think it good practice to check text length, for example this function can help you..
public boolean isEditTextEmpty(EditText input){
if(input.getText().length() == 0)
return true;
else
return false;
}
if (et.getText().length == 0 || et.gettext == null ){
// do nothing
} else {
// do whatever here
}
this should works fine

Displaying an array of values to buttons

I have an array of 12 values and I want to display it one after the other. Initially on application run I am displaying 6 values. On the button click I want to display the other 6 values one by one.
prevbutton-> value1 value2 value3 value4 value5 value6 -> nextbutton
So on next button click it should be like this.
prevbutton-> value2 value3 value4 value5 value6 value7 -> nextbutton
This should be continued up to the 12 values, and the reverse should happen in case of prevbutton.
I have used this code but it's not working:
public void onClick(View v) {
switch (v.getId()) {
case R.id.radionextstn:
forwardtune();
break;
}
}
public void forwardtune(){
Button[] buttons = new Button[5];
buttons[0] = (Button)findViewById(R.id.radiostation1);
buttons[1] = (Button)findViewById(R.id.radiostation2);
buttons[2] = (Button)findViewById(R.id.radiostation3);
buttons[3] = (Button)findViewById(R.id.radiostation4);
buttons[4] = (Button)findViewById(R.id.radiostation5);
buttons[5] = (Button)findViewById(R.id.radiostation6);
if(currentlyDisplayingFromPosition + 6 >= arraySize)
return;
for(int i=0; i<arraySize; i++) {
buttons[i].setText("");
}
for(int i=currentlyDisplayingFromPosition; i<=currentlyDisplayingFromPosition+6; i++){
if (frequency[i] == 0.0)
buttons[i].setText("");
else
buttons[i].setText("" + frequency[0]);
}
}
I am displaying the first 6 values like this:
public void autoTune() {
Log.i("autotune", " called");
if (frequency[0] == 0.0)
station1.setText(""); // station1 is a button
else
station1.setText("" + frequency[0]); // station1 is a button
if (frequency[1] == 0.0)
station2.setText(""); // station2 is a button
else
station2.setText("" + frequency[1]); // station2 is a button
if (frequency[2] == 0.0)
station3.setText(""); // station3 is a button
else
station3.setText("" + frequency[2]); // station3 is a button
if (frequency[3] == 0.0)
station4.setText(""); // station4 is a button
else
station4.setText("" + frequency[3]); // station4 is a button
if (frequency[4] == 0.0)
station5.setText(""); // station5 is a button
else
station5.setText("" + frequency[4]); // station5 is a button
if (frequency[5] == 0.0)
station6.setText(""); // station6 is a button
else
station6.setText("" + frequency[5]); // station6 is a button
}
#Override
protected Boolean doInBackground(Context... params) {
// TODO Auto-generated method stub
Log.i("in autotune", " before freq length");
int[] freq = { 911, 943, 947, 932, 901, 964, 843, 835, 946,904,908,873 };
freqCounter = 0;
Log.i("in autotune", "after freq length : " + freq.length);
frequency = new double[freq.length];
Log.i("in autotune", "after frequency length : " + frequency.length);
for (int k = 0; k < freq.length; k++) {
Log.i("In Radio.java", "Freq : " + freq[k]);
frequency[k] = freq[k];
frequency[k] = frequency[k] / 10;
if (frequency[k] == 0.0)
break;
freqCounter++;
Log.i("In Radio.java", "Frequency : " + frequency[k]);
}
}
first error I see, you declare an array of 5 button and try to put 6 buttons :
Button[] buttons = new Button[5];
you should do:
Button[] buttons = new Button[6];
solution :
if(currentlyDisplayingFromPosition + 6 >= arraySize)
return;
for(int i=0; i<6; i++){
buttons[i].setText("" + frequency[currentlyDisplayingFromPosition+i]);
}
Modify it as per your need.
Button[] btns = new Button[8];
List<String> pages = new ArrayList<String>();
int mStart = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog_activiy);
btns[0] = (Button) findViewById(R.id.pr);
btns[1] = (Button) findViewById(R.id.b1);
btns[2] = (Button) findViewById(R.id.b2);
btns[3] = (Button) findViewById(R.id.b3);
btns[4] = (Button) findViewById(R.id.b4);
btns[5] = (Button) findViewById(R.id.b5);
btns[6] = (Button) findViewById(R.id.b6);
btns[7] = (Button) findViewById(R.id.nt);
btns[0].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
rearrangeBy(-1);
}
});
btns[btns.length - 1].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
rearrangeBy(1);
}
});
// setup listeners
for (int i = 1; i < btns.length - 1; i++) {
btns[i].setOnClickListener(mClickListener);
}
for (int i = 0; i < 12; i++) {
pages.add((i + 1) + "");
}
setUpButtons();
}
final View.OnClickListener mClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(DialogActiviy.this, v.getTag() + "",
Toast.LENGTH_SHORT).show();
}
};
private void rearrangeBy(int by) {
mStart += by;
setUpButtons();
}
private void setUpButtons() {
// setup previous button
btns[0].setEnabled(!(mStart == 1));
// setup next button
int end = pages.size() - btns.length + 2 + 1;
btns[btns.length - 1].setEnabled(!(mStart == end));
// setup intermediate buttons
for (int i = 1; i < btns.length - 1; i++) {
String text = (mStart + i - 1) + "";
btns[i].setText(text);
btns[i].setTag(text);
}
}

Categories

Resources