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);
}
Related
Hey I was wondering if this is possible. I'm working on a app that takes user input and creates flashcards. When I click the red button I want it to open a new activity displaying the input as a list. I'm not sure how to get the second activity to read the Edittext and put it into a list display.
When you press the green button, a prompt takes user input and post it to the page. When you click the red button it will take you to a list view of what the user entered. I'm a bit stumped on how to pass the information to the next page to display a list.
enter code here package Main Code ;
TextView QuestionTV;
TextView AnswerTV;
//Buttons of Main Flashcard xml
Button addcardbtn;
Button Answerbtn;
Button nextbtn;
//Input and Buttons from dialog_Flashcard xml
EditText QuestionET;
EditText AnswerET;
Button Submitcardbtn;
Button cancelbtn;
Button deletecard;
//counter for array
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flash_cards);
addcardbtn = findViewById(R.id.addcardbtn);
Answerbtn = findViewById(R.id.Answerbtn);
nextbtn = findViewById(R.id.nextbtn);
deletecard = findViewById(R.id.deletecard);
//new array
QuestionArray = new ArrayList<>();
adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, QuestionArray);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, QuestionArray);
AnswerArray = new ArrayList<>();
adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, AnswerArray);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, AnswerArray);
//Text views
QuestionTV = findViewById(R.id.QuestionTV);
AnswerTV = findViewById(R.id.answerTV);
deletecard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplication(), FlashCard_ListView.class));
}
});
addcardbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder flashbuilder = new AlertDialog.Builder(FlashCards.this);
//get layout for the alert box
View fView = getLayoutInflater().inflate(R.layout.dialog_flashcard, null);
//get EditText from the alertbox layout
QuestionET = fView.findViewById(R.id.QuestionET);
AnswerET = fView.findViewById(R.id.AnswerET);
//get buttons from the alertbox layout
Submitcardbtn = (Button) fView.findViewById(R.id.Submitcardbtn);
cancelbtn = fView.findViewById(R.id.cancelbtn);
//make dialog box pop up
flashbuilder.setView(fView);
final AlertDialog dialog = flashbuilder.create();
dialog.show();
//code for the submit button
Submitcardbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!QuestionET.getText().toString().isEmpty() && !AnswerET.getText().toString().isEmpty()){
QuestionArray.add(QuestionET.getText().toString());
AnswerArray.add(AnswerET.getText().toString());
Toast.makeText(FlashCards.this, "Card Created", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
}
});
//code for cancel button
cancelbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
nextbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
QuestionTV.setText(QuestionArray.get(count));
AnswerTV.setText(AnswerArray.get(count));
if (count<QuestionArray.size()-1 || count<AnswerArray.size()-1){
count++;
AnswerTV.setVisibility(View.INVISIBLE);
}else if(count == QuestionArray.size()-1){
count = 0;
AnswerTV.setVisibility(View.INVISIBLE);
}
}
});
Answerbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AnswerTV.setVisibility(View.VISIBLE);
}
});
}
});
}
}
First Activity code
ArrayList<String> QuestionArray = new ArrayList<>();
QuestionArray.add(QuestionET.getText().toString());
ArrayList<String> AnswerArray = new ArrayList<>();
AnswerArray.add(AnswerET.getText().toString());
Intent i = new Intent(FlashCards.this, FlashCard_ListView.class);
i.putExtra("Questions", QuestionArray);
i.putExtra("Answers", AnswerArray);
startActivity(i);
Second Activity Code
Intent i = getIntent();
ArrayList<String> QuestionArray = i.getStringArrayListExtra("Questions");
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, QuestionArray);
QuestionListView.setAdapter(adapter);
ArrayList<String> AnswerArray = i.getStringArrayListExtra("Answers");
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, AnswerArray);
AnswersListView.setAdapter(adapter);
I Figured It out thanks!
Dynamically created EditTexts by Add button, and also I have assigned them unique ID's using setId(), Now what I want to do is to get values from the dynamically created EditTexts when the user taps a button, then store all of them as Sharedpreferences
This is the code
Thank you guys
ADDED CODES
List<EditText> allEds = new ArrayList<EditText>();
Button btnSave, btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LinearLayout layoutmain = (LinearLayout) findViewById(R.id.layoutmain);
btnAdd = (Button) findViewById(R.id.btnadd);
btnSave = (Button) findViewById(R.id.btnsave);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditText ed = new EditText(ActivityOptions.this);
ed.setId(ed.generateViewId());
ed.setTag(allEds.size());
ed.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
layoutmain.addView(ed);
// Add also to the allEds
allEds.add(ed);
}
});
btnSave.setOnClickListener(new View.OnClickListener() {
EditText ed = new EditText(ActivityOptions.this);
#Override
public void onClick(View arg0) {
SharedPreferences.Editor editor = getPreferences(Context.MODE_PRIVATE).edit();
editor.putString("key" + ed.getTag().toString(), ed.getText().toString());
for (EditText ed : allEds) {
editor.putString("key" + ed.getTag().toString(), ed.getText().toString());
}
editor.commit();
}
});
Intent intent = new Intent(this, MainActivity.class);
ArrayList<String> allTexts = new ArrayList<>();
for (EditText e : allEds) {
allTexts.add(e.getText().toString());
}
intent.putExtra("Text", (Serializable) allTexts);
}
}
While creating every new EditText, you generate ids by setId() but I don't see how these are going to be useful in your code.
Instead set the tag of the EditText like this:
ed.setTag(allEds.size());
and add it to the list:
allEds.add(ed);
Now in each EditText's tag you have stored its ordinal number (zero based) in the list and when you want to store its value in SharedPreferences you can do:
SharedPreferences.Editor editor = getPreferences(Context.MODE_PRIVATE).edit();
editor.putString("key" + et.getTag().toString(), ed.getText().toString());
editor.commit();
or by using a loop through all the items in the list:
for (EditText ed : allEds) {
editor.putString("key" + et.getTag().toString(), ed.getText().toString());
}
editor.commit();
This way you stored all the text values of the EditTexts with keys like:
"key0", "key1", "key2",...
Edit
Of you want to open another activity and pass the list to it:
Intent intent = new Intent(this, AnotherActivity.class);
ArrayList<String> allTexts = new ArrayList<>();
for (EditText e : allEds) {
allTexts.add(e.getText().toString())
}
intent.putExtra("Text", (Serializable) allTexts);
and in the other activity's onCreate():
ArrayList<String> list = (ArrayList<String>) getIntent().getSerializableExtra("Texts");
Edit2
Replace the code in btnSave.setOnClickListener() and the lines below, with this code:
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
SharedPreferences.Editor editor = getPreferences(Context.MODE_PRIVATE).edit();
for (EditText ed : allEds) {
editor.putString("key" + ed.getTag().toString(), ed.getText().toString());
}
editor.commit();
Intent intent = new Intent(this, MainActivity.class);
ArrayList<String> allTexts = new ArrayList<>();
for (EditText e : allEds) {
allTexts.add(e.getText().toString());
}
intent.putExtra("Text", (Serializable) allTexts);
startActivity(intent);
}
});
You forgot to add the EditText's to your list, so the save button will know about them and get their inputs.
After that you need to specify the save button (which I believe you did, but I cannot see a reference of it in your code).
Lastly just implement the logic for the save button in its onClick() (save in SharedPreferences).
List<EditText> allEds = new ArrayList<EditText>();
Button btnSave,btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LinearLayout layoutmain = (LinearLayout)findViewById(R.id.layoutmain);
btnAdd = (Button) findViewById(R.id.btnadd);
btnSave = (Button) findViewById(R.id.btnsave);
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditText ed = new EditText(MainActivity.this);
ed.setId(ed.generateViewId());
ed.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
layoutmain.addView(ed);
// Add also to the allEds
allEds.add(ed);
}
});
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
for (EditText ed : allEds) {
editor.putString("saved_text_key", ed.getText().toString());
editor.commit();
}
}
});
}
I have an app, where a user can enter a number and save to listView. The app is split into 3 activities.
The first activity is the MainActivity, which does something else. The second activity is where I enter a number and save it. The code Is below
public class HomeTeamScored extends Activity {
protected static EditText display;
protected static ArrayAdapter<String> adapter;
Button addButton;
CheckBox checkBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rect_activity_home_goal_player);
display = (EditText) findViewById(R.id.editText);
addButton = (Button) findViewById(R.id.btn);
checkBox = (CheckBox) findViewById(R.id.checkBox);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String task = display.getText().toString();
adapter.add(task);
adapter.notifyDataSetChanged();
SavePreferences();
Intent i = new Intent(HomeTeamScored.this, MainActivity.class);
startActivity(i);
finish();
}
});
}
protected void SavePreferences() {
// TODO Auto-generated method stub
SharedPreferences data = getApplicationContext().getSharedPreferences("saveNumber", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = data.edit();
for (int i = 0; i < adapter.getCount(); ++i){
// This assumes you only have the list items in the SharedPreferences.
editor.putString(String.valueOf(i), adapter.getItem(i));
}
editor.commit();
}
}
In my third activity, I retrieve the saved number.
public class ScoreBoardOverview extends Activity {
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rect_activity_score_board_overview);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
lv = (ListView) findViewById(R.id.listView);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
loadPreferences();
}
protected void loadPreferences(){
SharedPreferences data = getApplicationContext().getSharedPreferences("saveNumber", Context.MODE_PRIVATE);
for (int i = 0;; ++i){
final String str = data.getString(String.valueOf(i), "");
if (!str.equals("")){
adapter.add(str);
} else {
break; // Empty String means the default value was returned.
}
}
}
}
All this is working fine, and it adds a number to listView, but the problem is that it overrides the old value, were instead it should add a second row.
Anyone who can help??
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String task = display.getText().toString();
adapter.add(task);
adapter.notifyDataSetChanged();
SavePreferences();
Intent i = new Intent(HomeTeamScored.this, MainActivity.class);
startActivity(i);
finish();
}
});
}
here your adapter item size will be 0 when you call second activity each time. if you want to add second or third item you should write your
protected void loadPreferences(){
SharedPreferences data = getApplicationContext().getSharedPreferences("saveNumber", Context.MODE_PRIVATE);
for (int i = 0;; ++i){
final String str = data.getString(String.valueOf(i), "");
if (!str.equals("")){
adapter.add(str);
} else {
break; // Empty String means the default value was returned.
}
}
}
method in second activity too. and call loadPreferences() after this line
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
your adapter data size will be changed.
I am trying to pass an array list to another activity but it seems that is not enough. I searched all day to pass the array list with "intent" but with no success. I wrote a code for learning purposes. How to pass the data and show the Arraylist in a second activity?
The action button is btn_save. If you want further details let me know.
The code is in
MainActivity (first activity):
public class MainActivity extends AppCompatActivity {
ArrayList<String> addArray = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editTextOne = (EditText) findViewById(R.id.editTextOne);
final EditText editTextTwo = (EditText) findViewById(R.id.editTextTwo);
Button btn_showText = (Button) findViewById(R.id.buttonShow);
final TextView textView = (TextView) findViewById(R.id.textResults);
Button btn_refresh = (Button) findViewById(R.id.btn_refresh);
Button btn_close = (Button) findViewById(R.id.btn_close);
Button btn_save = (Button) findViewById(R.id.btn_save);
final ListView showMe = (ListView) findViewById(R.id.list_items);
btn_showText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = editTextOne.getText().toString();
String textTwo = editTextTwo.getText().toString();
if (text.length() == 0 || textTwo.length() == 0){
textView.setText("You must enter Name & Surname");
}else {
textView.setText(Html.fromHtml(
"<font color=\"red\">"+ text + "</font> " +
"<font color=\"blue\"><b>" + textTwo + " </b></font>"));
}
}
});
btn_refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
startActivity(getIntent());
}
});
btn_close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
System.exit(0);
}
});
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Context context = getApplicationContext();
// CharSequence mytext = "Hahahaha";
// int duration = Toast.LENGTH_SHORT;
// Toast toast = Toast.makeText(context,mytext,duration);
// toast.show();
String text = editTextOne.getText().toString();
String textTwo = editTextTwo.getText().toString();
String getInput = text + textTwo;
if (addArray.contains(getInput)){
Toast.makeText(getBaseContext(), "Item already Added!", Toast.LENGTH_LONG).show();
}
else if (getInput == null || getInput.trim().equals("")){
Toast.makeText(getBaseContext(), "Input field is empty", Toast.LENGTH_LONG).show();
}
else{
addArray.add(getInput);
ArrayAdapter<String> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, addArray);
showMe.setAdapter(adapter);
Intent intent = new Intent(MainActivity.this, ListOfNames.class);
((EditText)findViewById(R.id.editTextOne)).setText(" ");
((EditText)findViewById(R.id.editTextTwo)).setText(" ");
}
}
});
}
public void onButtonClick(View v){
if (v.getId() == R.id.btn_list){
Intent i = new Intent(MainActivity.this, ListOfNames.class);
startActivity(i);
}
}
}
ListOfNames second activity: (almost empty)
public class ListOfNames extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_screen);
}
}
If you are trying to pass a arraylist of string then it will be easy. Just pass arraylist with intent like this:
ArrayList<String> list = new ArrayList<String>();
Intent intent = new Intent(ActivityOne.this, ActivityTwo.class);
intent.putStringArrayListExtra("key", list);
startActivity(intent);
And receive it in ActivityTwo like this:
ArrayList<String> list = getIntent().getStringArrayListExtra("key");
I found a temporary solution for this (The app is not broke). The only problem is the arraylist didn't increased. It contains and show only the last value.
Main Activity:
...
else{
// addArray.add(getInput);
// ArrayAdapter<String> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, addArray);
// showMe.setAdapter(adapter);
Intent intent = new Intent(MainActivity.this, ListOfNames.class);
intent.putExtra("data", getInput);
startActivity(intent);
// ((EditText)findViewById(R.id.editTextOne)).setText(" ");
// ((EditText)findViewById(R.id.editTextTwo)).setText(" ");
}
...
ListOfNames (Second Activity):
public class ListOfNames extends Activity {
ArrayList<String> addArrayT = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_screen);
Bundle bundle = getIntent().getExtras();
String data = bundle.getString("data");
Button btn_more = (Button) findViewById(R.id.btn_more);
ListView showMe = (ListView) findViewById(R.id.list_items);
addArrayT.add(data);
ArrayAdapter<String> adapterT = new ArrayAdapter<>(ListOfNames.this, android.R.layout.simple_list_item_1, addArrayT);
showMe.setAdapter(adapterT);
}
public void onClickMore(View v){
if (v.getId() == R.id.btn_more){
Intent i = new Intent(ListOfNames.this, MainActivity.class);
startActivity(i);
}
}
}
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.