How to pass information from one java class to another - java

I need to pass one parameter from one Java class(A) to another Java class(B).
I use many solutions from the Internet but it couldn't solve my problem. The user will choose their answer from a list of radio button. The score will be added and I need to pass the score to B class.
In B class, the user continues to answer the question and I need to add the score from both A and B class to get the final score and display it at the bottom of B class. The application keep stopped when I click on the button in A class. But I think the problem is in B class. Does anyone know how to solve this? Thank you so much.
A class
private int score;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.a);
Button btn = findViewById(R.id.anxnext);
final RadioGroup rg1 = findViewById(R.id.anxq1g);
final RadioGroup rg2 = findViewById(R.id.anxq2g);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Get the checked Radio Button ID from Radio Group
int g1 = rg1.getCheckedRadioButtonId();
int g2 = rg2.getCheckedRadioButtonId();
if (g1 != -1) {
View radioButton = rg1.findViewById(g1);
idx1 = rg1.indexOfChild(radioButton);
}
if (g2 != -1) {
View radioButton = rg2.findViewById(g2);
idx2 = rg2.indexOfChild(radioButton);
}
score=idx1+idx2;
Intent intent = new Intent(A.this, B.class);
intent.putExtra("message", score);
startActivity(intent);
}
});
}
B class
private int score1,totalscore;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.b);
Bundle extras = getIntent().getExtras();
if(extras!=null) {
String m= extras.getString("message");
totalscore=Integer.parseInt(m);
}
Button btn = findViewById(R.id.anxresult);
final TextView tv_result = findViewById(R.id.tv_result);
final RadioGroup rg10 = findViewById(R.id.anxq10g);
final RadioGroup rg11 = findViewById(R.id.anxq11g);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Get the checked Radio Button ID from Radio Grou[
int g1 = rg10.getCheckedRadioButtonId();
int g2 = rg11.getCheckedRadioButtonId();
if (g1 != -1) {
View radioButton = rg10.findViewById(g1);
idx10 = rg10.indexOfChild(radioButton);
}
if (g2 != -1) {
View radioButton = rg11.findViewById(g2);
idx11 = rg11.indexOfChild(radioButton);
}
score1 = idx10 + idx11;
totalscore = score1 + totalscore;
tv_result.setText(totalscore + " selected.");
}
});
}
Below showed in the logcat

Take care of the data type:
In A class, you have:
score=idx1+idx2;
Intent intent = new Intent(A.this, B.class);
intent.putExtra("message", score);
startActivity(intent);
which score is int, however in B class:
Bundle extras = getIntent().getExtras();
if(extras!=null) {
String m= extras.getString("message");
totalscore=Integer.parseInt(m);
}
You are trying to get it as a String, and it is null so the app crashes.
So please change it to:
Bundle extras = getIntent().getExtras();
if(extras!=null) {
totalscore = extras.getInt("message");
}
And try again

try like this example
<RadioGroup
android:id="#+id/radioSex"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/radio_male"
android:checked="true" />
<RadioButton
android:id="#+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/radio_female" />
</RadioGroup>
In your class A
radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
btnDisplay = (Button) findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// get selected radio button from radioGroup
int selectedId = radioSexGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioSexButton = (RadioButton) findViewById(selectedId);
Toast.makeText(MyAndroidAppActivity.this,
radioSexButton.getText(), Toast.LENGTH_SHORT).show();
}
});
post the crash report to know more about your issue

Related

Get the checked radio button

I want to create dynamic RadioGroup (with dynamic radio options). I'm doing with the following code.
My question is that, how can I get the option that is selected by clicking the button "Check Answer". If the radio group is added through the XML layout then I can get by its ID, but in this case I'm unable to do so.
Here's the code:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/linear_layout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="vertical"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="#+id/button">
</LinearLayout>
<TextView
android:id="#+id/answer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toTopOf="#+id/button"
android:textColor="#008b00"
/>
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Check Answer"
app:layout_constraintBottom_toBottomOf="parent"
android:onClick="checkAnswer"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity:
package com.example.quiz8;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private LinearLayout linearLayout = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
RadioGroup radioGroup = new RadioGroup(this);
RadioButton radioButton;
final String[] title = {"Male", "Female", "Other", "Secret"};
for (int i = 0; i < title.length; i++) {
radioButton = new RadioButton(this);
radioButton.setId(i);
radioButton.setText(title[i]);
radioGroup.addView(radioButton);
}
linearLayout.addView(radioGroup);
}
public void checkAnswer(View view) {
//get the answer here
TextView answerText = (TextView) findViewById(R.id.answer);
answerText.setText("You selected the option...");
}
}
You can set a tag to the RadioGroup in order to be able to find it easily. A tag can be any Object. We'll use a String here, which has to be unique in the ViewGroup on which you call findViewWithTag(). Then in checkAnswer() you retrieve the RadioGroup by its tag and so get the text of the checked RadioButton.
private static final String RADIOGROUP_TAG = "radiogroup";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
RadioGroup radioGroup = new RadioGroup(this);
radioGroup.setTag(RADIOGROUP_TAG);
RadioButton radioButton;
final String[] title = {"Male", "Female", "Other", "Secret"};
for (int i = 0; i < title.length; i++) {
radioButton = new RadioButton(this);
radioButton.setId(i);
radioButton.setText(title[i]);
radioGroup.addView(radioButton);
}
linearLayout.addView(radioGroup);
}
public void checkAnswer(View view) {
//get the answer here
RadioGroup radioGroup = linearLayout.findViewWithTag(RADIOGROUP_TAG);
int checkedId = radioGroup.getCheckedRadioButtonId();
RadioButton radioButton = radioGroup.findViewById(checkedId);
String text = radioButton.getText().toString();
TextView answerText = (TextView) findViewById(R.id.answer);
answerText.setText("You selected the option..." + text);
}
Another option: you can have String[] title and the RadioGroup as fields in your Activity. This makes sense since you need them in more than one place.
private final String[] title = {"Male", "Female", "Other", "Secret"};
private RadioGroup radioGroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
radioGroup = new RadioGroup(this);
RadioButton radioButton;
for (int i = 0; i < title.length; i++) {
radioButton = new RadioButton(this);
radioButton.setId(i);
radioButton.setText(title[i]);
radioGroup.addView(radioButton);
}
linearLayout.addView(radioGroup);
}
public void checkAnswer(View view) {
//get the answer here
int checkedId = radioGroup.getCheckedRadioButtonId();
TextView answerText = (TextView) findViewById(R.id.answer);
// Note: make sure there is a checked RadioButton!
answerText.setText("You selected the option..." + title[checkedId]);
}
You can simply check for the selected one.
public class MainActivity extends AppCompatActivity {
private LinearLayout linearLayout = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
RadioGroup radioGroup = new RadioGroup(this);
RadioButton radioButton;
final String[] title = {"Male", "Female", "Other", "Secret"};
for (int i = 0; i < title.length; i++) {
radioButton = new RadioButton(this);
radioButton.setId(i);
radioButton.setText(title[i]);
radioGroup.addView(radioButton);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
//checkedId is the RadioButton selected
}
}
linearLayout.addView(radioGroup);
}
public void checkAnswer(View view) {
//get the answer here
TextView answerText = (TextView) findViewById(R.id.answer);
answerText.setText("You selected the option...");
}
}
1) You can add following code in OnClickListner() to check if desired check boxed is clicked.
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_pirates:
if (checked)
// Pirates are the best
break;
case R.id.radio_ninjas:
if (checked)
// Ninjas rule
break;
}
Further help can be found in Radio button documentation : Radio Button Documentation
2) Another method: A better way is to use RadioGroup and set the listener on this to change and update the View accordingly (saves you having 2 or 3 or 4 etc listeners).
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.yourRadioGroup);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
}
});

Display next database entry

I am programming my first android app.
I am trying to create a quiz app. I have questions stored in a SQLite Database, which are displayed one after the other.
The user selects one of the answers (a radio button) and the clicks the 'next button' and the next question is displayed and so on.
Following code shows my Activity file displaying each question one after the other, which was working perfectly.
ACEActivity (old, working version)
public class ACEActivity extends Activity {
List<Question> quesList;
int score = 0;
int qid = 0;
Question currentQ;
TextView txtQuestion;
RadioButton rda, rdb, rdc, rdd;
Button butNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
DatabaseHelper db = new DatabaseHelper(this);
quesList = db.getAllACEQuestions();
currentQ = quesList.get(qid);
txtQuestion = (TextView)findViewById(R.id.textView);
rda = (RadioButton)findViewById(R.id.radio0);
rdb = (RadioButton)findViewById(R.id.radio1);
rdc = (RadioButton)findViewById(R.id.radio2);
rdd = (RadioButton)findViewById(R.id.radio3);
butNext = (Button)findViewById(R.id.nextButton);
setQuestionView();
butNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup grp = (RadioGroup)findViewById(R.id.radioGroup);
RadioButton answer = (RadioButton)findViewById(grp.getCheckedRadioButtonId());
Log.d("yourans", currentQ.getANSWER() + " " + answer.getText());
// If the correct answer was clicked display the next question
if(currentQ.getANSWER().equals(answer.getText())) {
currentQ = quesList.get(qid);
setQuestionView();
}
}
});
}
// Load the next question
private void setQuestionView() {
txtQuestion.setText(currentQ.getQUESTION());
rda.setText(currentQ.getOPTA());
rdb.setText(currentQ.getOPTB());
rdc.setText(currentQ.getOPTC());
rdd.setText(currentQ.getOPTD());
qid++;
}
}
In my newer version of this activity I load another activity to give the user immediate feedback, if the correct or wrong answer was clicked.
After displaying the feedback activity I would like to return to this activity and display the next question.
I am trying to do this by passing the question id from the feedback activity (ACECorrectActivity) to this activity (ACEActivity) without any success.
How I tried to solve this problem:
ACEActivity (new version, just working for the first question)
public class ACEActivity extends Activity {
List<Question> quesList;
int score = 0;
int qid = 0;
Question currentQ;
TextView txtQuestion;
RadioButton rda, rdb, rdc, rdd;
Button checkBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
// THIS PART IS NEW ================================
// Get the intent
Intent intent = getIntent();
// Get the question id (if there are any extras)
Bundle extras = intent.getExtras();
if (extras != null) {
int qid = extras.getInt("nextQuestionID");
} else {
int qid = 0;
}
// ==================================================
DatabaseHelper db = new DatabaseHelper(this);
quesList = db.getAllACEQuestions();
currentQ = quesList.get(qid);
txtQuestion = (TextView)findViewById(R.id.textView);
rda = (RadioButton)findViewById(R.id.radio0);
rdb = (RadioButton)findViewById(R.id.radio1);
rdc = (RadioButton)findViewById(R.id.radio2);
rdd = (RadioButton)findViewById(R.id.radio3);
checkBtn = (Button) findViewById(R.id.checkButton);
setQuestionView(qid);
checkBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup grp = (RadioGroup) findViewById(R.id.radioGroup);
RadioButton answer = (RadioButton) findViewById(grp.getCheckedRadioButtonId());
Log.d("yourans", currentQ.getANSWER() + " " + answer.getText());
// THIS PART IS NEW AND WORKING FINE ================================
// If the correct answer was clicked
if (currentQ.getANSWER().equals(answer.getText())) {
Intent intent = new Intent(ACEActivity.this, CorrectACEActivity.class);
startActivity(intent);
// If the wrong answer was clicked
} else {
Intent intent = new Intent(ACEActivity.this, FalseACEActivity.class);
startActivity(intent);
}
}
});
}
private void setQuestionView() {
txtQuestion.setText(currentQ.getQUESTION());
rda.setText(currentQ.getOPTA());
rdb.setText(currentQ.getOPTB());
rdc.setText(currentQ.getOPTC());
rdd.setText(currentQ.getOPTD());
qid++;
}
}
ACECorrectActivity (feedback activity loaded, when the correct answer is chosen and the next button is clicked in the ACEActivity)
public class CorrectACEActivity extends Activity {
List<Question> quesList;
int score = 0;
int qid = 0;
Question currentQ;
TextView txtQuestion;
RadioButton rda, rdb, rdc, rdd;
Button nextBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_correct);
DatabaseHelper db = new DatabaseHelper(this);
quesList = db.getAllACEQuestions();
currentQ = quesList.get(qid);
txtQuestion = (TextView) findViewById(R.id.textView);
rda = (RadioButton) findViewById(R.id.radio0);
rdb = (RadioButton) findViewById(R.id.radio1);
rdc = (RadioButton) findViewById(R.id.radio2);
rdd = (RadioButton) findViewById(R.id.radio3);
nextBtn = (Button) findViewById(R.id.nextButton);
// Set colors according to correct answer
rda.setBackgroundColor(Color.RED);
rdb.setBackgroundColor(Color.RED);
rdc.setBackgroundColor(Color.RED);
rdd.setBackgroundColor(Color.RED);
if(currentQ.getANSWER().equals(currentQ.getOPTA())) {
rda.setBackgroundColor(Color.GREEN);
} else if(currentQ.getANSWER().equals(currentQ.getOPTB())) {
rdb.setBackgroundColor(Color.GREEN);
} else if(currentQ.getANSWER().equals(currentQ.getOPTC())) {
rdc.setBackgroundColor(Color.GREEN);
} else if(currentQ.getANSWER().equals(currentQ.getOPTD())) {
rdd.setBackgroundColor(Color.GREEN);
}
setQuestionView();
// WHEN NEXT BUTTON IS CLICKED RETURN TO ACEActivity AND LOAD NEXT QUESTION
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(CorrectACEActivity.this, ACEActivity.class);
intent.putExtra("nextQuestionID", currentQ + 1);
startActivity(intent);
}
});
}
private void setQuestionView() {
txtQuestion.setText(currentQ.getQUESTION());
rda.setText(currentQ.getOPTA());
rdb.setText(currentQ.getOPTB());
rdc.setText(currentQ.getOPTC());
rdd.setText(currentQ.getOPTD());
qid++;
}
}
The first question works perfectly. However, as soon as I return to the ACEActivity after answering the first question, I am presented with the first question once again.
As you can see, I am really new to this and would be tremendously happy for any kind of help! Thank you!!
intent.putExtra("nextQuestionID", currentQ + 1);
you are setting the extra wrong in CorrectACEActivity , shouldn't it be like this?
intent.putExtra("nextQuestionID", qid+ 1);

Preference settings in Android studio how to connect the value in EditTextPreference to a TextView

I don't know how to find the value from the EditTextPreference. Like when i write a number in Edittextpreference I want the number shows up in my Textview "numTxt" in my fragment firstlayout xml :(.
Blockquote
The base for the settings menu is the "Settings Activity" where you get in Android studio, new>Activity>Settings Activity.so in the xml pref_general.xml is where the EditTextPreference is.
Please look at the imgur photos where the textfield is going to be edited.
Image-imgur
This is the preference xml file.
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<SwitchPreference
android:defaultValue="true"
android:key="example_switch"
android:summary="#string/pref_description_social_recommendations"
android:title="#string/pref_title_social_recommendations" />
<!-- NOTE: EditTextPreference accepts EditText attributes. -->
<!-- NOTE: EditTextPreference's summary should be set to its value by the activity code. -->
<EditTextPreference
android:capitalize="words"
android:defaultValue="#string/pref_default_display_name"
android:inputType="textCapWords"
android:key="example_text"
android:id="#+id/textnrisettings"
android:maxLines="1"
android:selectAllOnFocus="true"
android:singleLine="true"
android:title="#string/pref_title_display_name" />
<!-- NOTE: Hide buttons to simplify the UI. Users can touch outside the dialog to
dismiss it. -->
<!-- NOTE: ListPreference's summary should be set to its value by the activity code. -->
<ListPreference
android:defaultValue="-1"
android:entries="#array/pref_example_list_titles"
android:entryValues="#array/pref_example_list_values"
android:key="example_list"
android:negativeButtonText="#null"
android:positiveButtonText="#null"
android:title="#string/pref_title_add_friends_to_messages" />
</PreferenceScreen>
And here is the java file of the first layout xml
public class FirstFragment extends Fragment {
private View view;
public FirstFragment(){
}
Button sendSMS;
Button sendSMSaon;
Button sendSMSaoff;
Button sendSMSrela1;
Button sendSMSrela2;
EditText msgTxt;
EditText aonTxt;
EditText aoffTxt;
EditText rela1txt;
EditText rela2txt;
Button taframnummer;
//Down below in Textview numTxt is where the value from the Edittextpreference will be shown
TextView numTxt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.first_layout, container, false);
sendSMS = (Button)view.findViewById(R.id.skicka);
sendSMSaon = (Button)view.findViewById(R.id.skickaaon);
sendSMSaoff = (Button)view.findViewById(R.id.skickaaoff);
sendSMSrela1 = (Button)view.findViewById(R.id.skickarela1);
sendSMSrela2 = (Button)view.findViewById(R.id.skickarela2);
msgTxt = (EditText)view.findViewById(R.id.Textmeddelande);
numTxt = (TextView)view.findViewById(R.id.nummer);
aonTxt = (EditText)view.findViewById(R.id.aon);
aoffTxt = (EditText)view.findViewById(R.id.aoff);
rela1txt = (EditText)view.findViewById(R.id.rela1txt);
rela2txt = (EditText)view.findViewById(R.id.relä2txt);
taframnummer = (Button) view.findViewById(R.id.taframnummer);
msgTxt.setVisibility(View.INVISIBLE);
aonTxt.setVisibility(View.INVISIBLE);
aoffTxt.setVisibility(View.INVISIBLE);
rela1txt.setVisibility(View.INVISIBLE);
rela2txt.setVisibility(View.INVISIBLE);
sendSMSaoff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mymsgaoff = aoffTxt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, mymsgaoff);
}
}
);
sendSMSaon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mymsgaon = aonTxt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, mymsgaon);
}
}
);
sendSMS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String myMsg = msgTxt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, myMsg);
}
}
);
sendSMSrela1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String myMsgrela1 = rela1txt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, myMsgrela1);
}
}
);
sendSMSrela2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mymsgrela2 = rela2txt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, mymsgrela2);
}
}
);
return view;
}
private void sendMsg(String theNumber, String myMsg)
{
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(theNumber, null, myMsg, null, null);
}
}
I do not see any text field in your code, if you want to copy the value to the other activity (screen) you have to save the number using
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("numTxt", numTxt.getText());
editor.commit();
and retrieve the number in other activity using
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); String restoredText = prefs.getString("numTxt", null);
TextView textView = (TextView) findViewById(R.id.textViewName); //your textField?
textView.setText(restoredText);
//or with EditText
//EditText editText = (EditText) findViewById(R.id.editTextName);
//editText.setText(restoredText);

How to run specific method from another activity with an intent

I have a radio button activity with 5 choices for the game. It's a quiz game, so the user can choose to play until he or she makes one error, two errors, tree, four and five errors. My question is....is it better to make 5 activities and 5 classes, so I can call intent of each activity when user check that radio button, or, is better to make one activity, for all five choices and depending on what user chose, to count until 1,2,3,4 or 5 errors? I know how do the first option, but I don't know how to do the second one. Here my choice activity:
public class Izbor extends Activity implements OnClickListener, OnCheckedChangeListener{
MediaPlayer buttonBack;
RadioButton rbDeset,rbDvadeset,rbNeogranicenoTriGreske,rbNeogranicenoJednaGreska,rbNeogranicenoPetGresaka;
Button dNazad, dStart;
RadioGroup rGrupa;
TextView tv1;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.izbor);
addListenerOnButton();
}
private void addListenerOnButton() {
Typeface dugmad = Typeface.createFromAsset(getAssets(), "Bebas.ttf");
Typeface pitanjeVrh = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
rbDeset = (RadioButton) findViewById(R.id.radio1);
rbDvadeset = (RadioButton) findViewById(R.id.radio2);
rbNeogranicenoJednaGreska = (RadioButton) findViewById(R.id.radio3);
rbNeogranicenoTriGreske = (RadioButton) findViewById(R.id.radio4);
rbNeogranicenoPetGresaka = (RadioButton) findViewById(R.id.radio5);
dNazad = (Button) findViewById(R.id.bNazad);
dStart = (Button) findViewById(R.id.bStart);
rGrupa = (RadioGroup) findViewById(R.id.radioGroup1);
buttonBack = MediaPlayer.create(Izbor.this, R.raw.back);
tv1 = (TextView) findViewById(R.id.tv1);
dNazad.setTypeface(dugmad);
dStart.setTypeface(dugmad);
rbDeset.setTypeface(dugmad);
rbDvadeset.setTypeface(dugmad);
rbNeogranicenoPetGresaka.setTypeface(dugmad);
rbNeogranicenoJednaGreska.setTypeface(dugmad);
rbNeogranicenoTriGreske.setTypeface(dugmad);
tv1.setTypeface(pitanjeVrh);
rGrupa.setOnCheckedChangeListener(this);
rbDeset.setOnClickListener(this);
rbDvadeset.setOnClickListener(this);
rbNeogranicenoJednaGreska.setOnClickListener(this);
rbNeogranicenoTriGreske.setOnClickListener(this);
rbNeogranicenoPetGresaka.setOnClickListener(this);
dStart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(rbDeset.isChecked()){
startActivity(new Intent("rs.androidaplikacijekvizopstekulture.KVIZ"));
}else if(rbDvadeset.isChecked()){
startActivity(new Intent("rs.androidaplikacijekvizopstekulture.DVADESETPITANJA"));
}else if(rbNeogranicenoJednaGreska.isChecked()){
startActivity(new Intent("rs.androidaplikacijekvizopstekulture.TRIDESETPITANJA"));
}else if(rbNeogranicenoPetGresaka.isChecked()){
startActivity(new Intent("rs.androidaplikacijekvizopstekulture.NEOGRANICENOPETGRESAKA"));
}
}
});
dNazad.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
buttonBack.start();
finish();
}
});
}
public void onCheckedChanged(RadioGroup group, int checkedId) {
}
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
And here is one activity where a user can play until 5 mistakes:
public class NeogranicenoPetGresaka extends Activity implements OnClickListener{
Button bIzlazIzKviza, bOdgovor1, bOdgovor2, bOdgovor3, bOdgovor4;
TextView question, netacniOdg, score;
int counter = 0;
int brojacPogresnihOdgovora = 0;
int brojacTacnihOdgovora = 0;
Runnable mLaunchTask = new Runnable() {
public void run() {
nextQuestion();
}
};
Runnable mLaunchTaskFinish = new Runnable() {
public void run() {
finish();
}
};
private class Answer {
public Answer(String opt, boolean correct) {
option = opt;
isCorrect = correct;
}
String option;
boolean isCorrect;
}
Handler mHandler = new Handler();
final OnClickListener clickListener = new OnClickListener() {
public void onClick(View v) {
Answer ans = (Answer) v.getTag();
if (ans.isCorrect) {
brojacTacnihOdgovora++;
Intent i = new Intent("rs.androidaplikacijekvizopstekulture.TACANODGOVOR");
startActivity(i);
mHandler.postDelayed(mLaunchTask,1200);
}
else{
brojacPogresnihOdgovora++;
Intent i = new Intent("rs.androidaplikacijekvizopstekulture.POGRESANODGOVOR");
startActivity(i);
mHandler.postDelayed(mLaunchTask,2200);
}
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.neograniceno5gresaka);
Typeface dugmad = Typeface.createFromAsset(getAssets(), "Bebas.ttf");
Typeface pitanje = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
bIzlazIzKviza = (Button) findViewById(R.id.bIzlazIzKvizaN);
netacniOdg = (TextView) findViewById(R.id.tvBrojPitanjaN);
question = (TextView) findViewById(R.id.tvPitanjeN);
bOdgovor1 = (Button) findViewById(R.id.bOdgovorN1);
bOdgovor2 = (Button) findViewById(R.id.bOdgovorN2);
bOdgovor3 = (Button) findViewById(R.id.bOdgovorN3);
bOdgovor4 = (Button) findViewById(R.id.bOdgovorN4);
score = (TextView) findViewById(R.id.tvSkor2N);
bOdgovor1.setTypeface(dugmad);
bOdgovor2.setTypeface(dugmad);
bOdgovor3.setTypeface(dugmad);
bOdgovor4.setTypeface(dugmad);
bIzlazIzKviza.setTypeface(dugmad);
netacniOdg.setTypeface(dugmad);
question.setTypeface(pitanje);
score.setTypeface(dugmad);
nextQuestion(); //startuje prvo pitanje!
}
public void onClick(View v) {
// TODO Auto-generated method stub
}
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
public void nextQuestion() {
TestAdapter mDbHelper = new TestAdapter(this);
mDbHelper.createDatabase();
try{ //Pokusava da otvori db
mDbHelper.open(); //baza otvorena
Cursor c = mDbHelper.getTestData();
List<Answer> labels = new ArrayList<Answer>();
labels.add(new Answer(c.getString(2), true));
labels.add(new Answer(c.getString(3), false));
labels.add(new Answer(c.getString(4), false));
labels.add(new Answer(c.getString(5), false));
Collections.shuffle(labels);
if(brojacPogresnihOdgovora < 5){
question.setText(c.getString(1));
bOdgovor1.setText(labels.get(0).option);
bOdgovor1.setTag(labels.get(0));
bOdgovor1.setOnClickListener(clickListener);
bOdgovor2.setText(labels.get(1).option);
bOdgovor2.setTag(labels.get(1));
bOdgovor2.setOnClickListener(clickListener);
bOdgovor3.setText(labels.get(2).option);
bOdgovor3.setTag(labels.get(2));
bOdgovor3.setOnClickListener(clickListener);
bOdgovor4.setText(labels.get(3).option);
bOdgovor4.setTag(labels.get(3));
bOdgovor4.setOnClickListener(clickListener);
//reset your next question and all four options here
netacniOdg.setText("" + brojacPogresnihOdgovora);
score.setText("Score: " + brojacTacnihOdgovora);
}
else{
Intent i = new Intent("rs.androidaplikacijekvizopstekulture.REZULTAT");
startActivity(i);
mHandler.postDelayed(mLaunchTaskFinish,4000);
}
}
finally{ // kada zavrsi sa koriscenjem baze podataka, zatvara db
mDbHelper.close();
}
bIzlazIzKviza.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
}
Considering that the choice is just a small setting to the same game I see absolutely no reason to create one class/activity for each choice, it would be sheer madness.
As for the settings part, just create a numeric only input field that accepts any amount of "errors" ( why not ? ).
OnClick get the input from this field, save the value to the intent extras and start the game with the intent. In the onCreate of the game read the intent extras and get the number of "tries"/"errors".
OK, I tried with onNewIntent, but I can only call one method, and I need at least 3. Here's the code in my choice activity with radio buttons(group):
public void onClick(View v) {
if(rbDeset.isChecked()){
Intent intent = new Intent(Izbor.this, Kviz.class);
intent.putExtra("myMethod", "nextQuestion");
startActivity(intent);
And here's my quiz activity:
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if(intent.getStringExtra("methodName").equals("nextQuestion")){
nextQuestion();
}
}
I tried with ELSE IF but it didn't work. My methods are named: nextQuestion(), nextQuestion2() and nextQuestion3(). These are pretty much same methods only with different counters (one for 10 questions, one for 20 and one for 30). Maybe I don't need 3 methods to do this but honestly I don't know other way to do that.

Declaring button variables as an array with a for loop android

I managed to create buttons in a for loop and saw no reason why not to declare my varibles inside it too. Unfortunately eclipse only identifies the "bt" and doesn't want to replace my [i] with the number it represents in the loop and as a result find the correct id in my layout. Any thoughts on how to make this work? I'm also greatful for any other solution as beatiful as mine, which doesn't work ;)
Button [] bt = new Button[6];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_layout);
bt[0] = (Button) findViewById(R.id.bt0);
bt[1] = (Button) findViewById(R.id.bt1);//This is what i'm trying to replace
bt[2] = (Button) findViewById(R.id.bt2);
bt[3] = (Button) findViewById(R.id.bt3);
bt[4] = (Button) findViewById(R.id.bt4);
bt[5] = (Button) findViewById(R.id.bt5);
for (int i=0; i<6; i++) {
final int b = i;
bt [i] = (Button)findViewById(R.id.bt[i]); <----//Whith this
bt [i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(Start.this, MainActivity.class);
myIntent.putExtra("players", b);
startActivity(myIntent);
//startActivity(new Intent(Start.this, MainActivity.class));
}
});
}
}
I would do the following:
private static final int[] idArray = {R.id.bt0, R.id.bt1, R.id.bt2, R.id.bt3, R.id.bt4, R.id.bt5};
private Button[] bt = new Button[idArray.length];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_layout);
for (int i=0; i<idArray.length; i++) {
final int b = i;
bt [b] = (Button)findViewById(idArray[b]); // Fetch the view id from array
bt [b].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(Start.this, MainActivity.class);
myIntent.putExtra("players", b);
startActivity(myIntent);
//startActivity(new Intent(Start.this, MainActivity.class));
}
});
}
}
If you want to add or remove buttons, just add it to idArray and all other things are dynamic already.
I think if you have group of similar buttons - they all placed inside 1 parent on layout (LinearLayout or RelativeLayout or something else). You can take get parent and retrieve all children. This way you don't need to specify id for each button.
ViewGroup buttonsView = (ViewGroup) findViewById(R.id.buttons);
List<Button> buttons = new ArrayList<Button>();
for (int i = 0; i < buttonsView.getChildCount(); i++) {
buttons.add((Button) buttonsView.getChildAt(i));
}
Also you can store button's number in it's tag so you don't need to create final int variables:
ViewGroup buttonsView = (ViewGroup) findViewById(R.id.buttons);
List<Button> buttons = new ArrayList<Button>();
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(Start.this, MainActivity.class);
myIntent.putExtra("players", (Integer) v.getTag());
startActivity(myIntent);
//startActivity(new Intent(Start.this, MainActivity.class));
}
};
for (int i = 0; i < buttonsView.getChildCount(); i++) {
Button button = (Button) buttonsView.getChildAt(i);
button.setTag(i);
button.setOnClickListener(listener);
buttons.add(buttons);
}

Categories