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);
Related
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
public class JobSignup extends AppCompatActivity {
private Button btn;
private ImageView imageview;
private static final String IMAGE_DIRECTORY = "/demonuts";
private int GALLERY = 1, CAMERA = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_job_signup);
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myRef = database.getReferenceFromUrl("https://rozgarinepal100.firebaseio.com/");
final TextView userName = (TextView) findViewById(R.id.userName);
final EditText writeName = (EditText) findViewById(R.id.writeName);
ImageButton sendDataToFirebase = (ImageButton) findViewById(R.id.sendDataToFirebase);
final TextView dateOfBirth = (TextView) findViewById(R.id.dateOfBirth);
final EditText enterDateOfBirth = (EditText) findViewById(R.id.enterDateOfBirth);
if ( writeName.getText().toString().length() == 0)
{
writeName.setError("Username Compulsory");
}
// if( TextUtils.isEmpty(writeName.getText())) {
// /**
// * You can Toast a message here that the Username is Empty
// **/
//
// writeName.setError("First name is required!");
//
// }
sendDataToFirebase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myRef.child("0").child(userName.getText().toString()).setValue(writeName.getText().toString());
//myRef.child("NAME:").setValue("Kathmandu University");
myRef.child("0").child(dateOfBirth.getText().toString()).setValue(enterDateOfBirth.getText().toString());
}
});
}
public void onClick(View v) {
Intent i = new Intent(this, HomeActivity.class);
startActivity(i);
}
}
My code is running fine and database is also saved on click but on click it is not going to the next class using intent.Here in the onclick listener function i have added link for database when the button is clicked on android.Database is running fine on click operation but i am not able to go the next class which i have created.I have the only problem to go the next class when the same button is clicked.I am trying to enable the database and goto the next class using same button.
Try this, It will work...
sendDataToFirebase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myRef.child("0").child(userName.getText().toString()).setValue(writeName.getText().toString());
//myRef.child("NAME:").setValue("Kathmandu University");
myRef.child("0").child(dateOfBirth.getText().toString()).setValue(enterDateOfBirth.getText().toString());
Intent i = new Intent(JobSignup.this, HomeActivity.class);
startActivity(i);
}
});
So, I've been struggling on this for a while and have searched on here for hours without finding anything that really helped. I have a custom class Streak. When the user creates a new Streak in my Main Activity, I want for that streak to be added to a list of total streaks, which I would then access from an AllStreaks activity. I have tried using Gson, but received errors. What I have below is working for the time being, but since my global variable has to be declared as new. I don't really want to use a MySQL database as this info needs to be quickly editable and I don't want to have to constantly connect to that to potentially change just one detail.
Sorry if my code is a mess or this makes no sense, I'm coming to realize I'm really shitty at programming anyway.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private SharedPreferences prefs;
private SharedPreferences.Editor editor;
private String userID;
private int streakCounter;
private int mainStreakCounter;
private RelativeLayout quickAdd;
private EditText quickSubmitStreak;
private Button quickSubmitButton;
private Button mainStreak1;
private Button mainStreak2;
private Button mainStreak3;
private Button mainStreak4;
private Button allStreaks;
private Button addStreak;
private Dialog pickDialog;
private Button healthButton;
private Button mentalButton;
private Button personalButton;
private Button professionalButton;
private Button socialButton;
private Button submitStreakButton;
private TextView todaysDate;
private EditText chooseDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/*
Creates shared preferences and editor
*/
prefs = getSharedPreferences("carter.streakly", MODE_PRIVATE);
editor = prefs.edit();
// Checks if it's the first time the user opens the app. If so, generates a unique user ID and stores it in shared prefs
if (prefs.getBoolean("firstTime", true)){
userID = UUID.randomUUID().toString();
editor.putString("user", userID);
editor.putBoolean("firstTime", false);
editor.commit();
}
streakCounter = 0; // CHANGE TO streakCounter = prefs.getInt("streakCounter", 0) later
mainStreakCounter = 0; // CHANGE TO mainStreakCount = prefs.getInt("mainStreakCounter", 0) later
quickSubmitStreak = (EditText) findViewById(R.id.enter_goal);
quickSubmitButton = (Button) findViewById(R.id.submit_button);
mainStreak1 = (Button) findViewById(R.id.main_goal_1);
mainStreak2 = (Button) findViewById(R.id.main_goal_2);
mainStreak3 = (Button) findViewById(R.id.main_goal_3);
mainStreak4 = (Button) findViewById(R.id.main_goal_4);
allStreaks = (Button) findViewById(R.id.main_goal_5);
addStreak = (Button) findViewById(R.id.add_streak_button);
/*
if (streakCounter > 4){
quickAdd.setVisibility(View.INVISIBLE);
}
mainStreak1.setText(prefs.getString("mainKeyOne", ""));
mainStreak2.setText(prefs.getString("mainKeyTwo", ""));
mainStreak3.setText(prefs.getString("mainKeyThree", ""));
mainStreak4.setText(prefs.getString("mainKeyFour", ""));
/*
Sets the text to the lowest unused main streak to the inputted streak name
Stores the streak name in shared prefs so it will be there for next time app opens
Increases the total streak count
*/
quickSubmitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mainStreakCounter < 4){
switch(mainStreakCounter){
case 0:
mainStreak1.setText(quickSubmitStreak.getText().toString());
editor.putString("mainKeyOne", quickSubmitStreak.getText().toString()).commit();
break;
case 1:
mainStreak2.setText(quickSubmitStreak.getText().toString());
editor.putString("mainKeyTwo", quickSubmitStreak.getText().toString()).commit();
break;
case 2:
mainStreak3.setText(quickSubmitStreak.getText().toString());
editor.putString("mainKeyThree", quickSubmitStreak.getText().toString()).commit();
break;
case 3:
mainStreak4.setText(quickSubmitStreak.getText().toString());
editor.putString("mainKeyFour", quickSubmitStreak.getText().toString()).commit();
break;
default:break;
}
}
mainStreakCounter++;
AllStreaks.streakList.add(new Streak(quickSubmitStreak.getText().toString()));
// ADD THESE TO SHARED PREFERENCES AT SOME POINT
}
});
/*
Brings user to the All Streaks activity, and passes the LinkedList<Streak> streakList
*/
allStreaks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AllStreaks.class);
startActivity(intent);
}
});
/*
Shows an Alert Dialog that allows users to enter in the type of streak they want
*/
addStreak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
createCustomDialog();
}
});
}
private void createCustomDialog(){
pickDialog = new Dialog(MainActivity.this);
pickDialog.setContentView(R.layout.dialog_add_streak);
final EditText chooseName = (EditText) pickDialog.findViewById(R.id.dialog_acitivty_name);
healthButton = (Button) pickDialog.findViewById(R.id.dialog_health);
mentalButton = (Button) pickDialog.findViewById(R.id.dialog_mental);
personalButton = (Button) pickDialog.findViewById(R.id.dialog_personal);
professionalButton = (Button) pickDialog.findViewById(R.id.dialog_professional);
socialButton = (Button) pickDialog.findViewById(R.id.dialog_social);
submitStreakButton = (Button) pickDialog.findViewById(R.id.dialog_submit_button);
todaysDate = (TextView) pickDialog.findViewById(R.id.dialog_today);
chooseDate = (EditText) pickDialog.findViewById(R.id.dialog_input_date);
pickDialog.show();
healthButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editor.putInt("AddCategory", 0).commit();
editor.putString("Category", "Health");
editor.commit();
recolorCategory();
}
});
mentalButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editor.putInt("AddCategory", 1).commit();
editor.putString("Category", "Mental");
editor.commit();
recolorCategory();
}
});
personalButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editor.putInt("AddCategory", 2).commit();
editor.putString("Category", "Personal");
editor.commit();
recolorCategory();
}
});
professionalButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editor.putInt("AddCategory", 3).commit();
editor.putString("Category", "Professional");
editor.commit();
recolorCategory();
}
});
socialButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editor.putInt("AddCategory", 4).commit();
editor.putString("Category", "Social");
editor.commit();
recolorCategory();
}
});
todaysDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
todaysDate.setTextColor(Color.rgb(51,51,255));
chooseDate.setTextColor(Color.rgb(0,0,0));
editor.putInt("todayOrChosen", 1).commit();
}
});
chooseDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chooseDate.setTextColor(Color.rgb(51,51,255));
todaysDate.setTextColor(Color.rgb(0,0,0));
editor.putInt("todayOrChosen", 2).commit();
}
});
submitStreakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*
If the user selected today's date, enter the days kept as 0. If the user selected how long they've kept the streak for, enter the days kept as chooseDate
*/
if(prefs.getInt("todayOrChosen", 1) == 1){
//streakList.add(new Streak(chooseName.getText().toString(), prefs.getString("Category", ""),
//new SimpleDateFormat("dd-MM-yyyy").format(new Date()), 0));
AllStreaks.streakList.add(new Streak(chooseName.getText().toString(), prefs.getString("Category", ""),
new SimpleDateFormat("dd-MM-yyyy").format(new Date()), 0));
}
else {
//streakList.add(new Streak(chooseName.getText().toString(), prefs.getString("Category", ""),
//new SimpleDateFormat("dd-MM-yyyy").format(new Date()), Integer.parseInt(chooseDate.getText().toString())));
AllStreaks.streakList.add(new Streak(chooseName.getText().toString(), prefs.getString("Category", ""),
new SimpleDateFormat("dd-MM-yyyy").format(new Date()), Integer.parseInt(chooseDate.getText().toString())));
}
/*
Update streakList in Shared Preferences
*/
/*
Display an Alert Dialog indicating that a streak has been added
*/
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Streak Added")
.setPositiveButton("OK", null)
.create()
.show();
pickDialog.dismiss();
}
});
}
/*
Highlights which category is currently chosen
*/
private void recolorCategory(){
Button[] categoryList = {healthButton, mentalButton, personalButton, professionalButton, socialButton};
int recolorIndex = prefs.getInt("AddCategory", 0);
categoryList[recolorIndex].setTextColor(Color.rgb(51,51,255));
for (int i = 0; i < 5; i++){
if (i != recolorIndex) categoryList[i].setTextColor(Color.rgb(153, 255, 102));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
AllStreaks.java:
public class AllStreaks extends AppCompatActivity {
public static ArrayList<Streak> streakList = new ArrayList<>();
private SharedPreferences prefs;
private SharedPreferences.Editor editor;
private ArrayList<Streak> allStreakList;
private TableLayout mTableLayout;
private TableRow mTableRow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_streaks);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/*
if (streakList == null){
Button streakButton = new Button(this);
streakButton.setText("Try again");
}
else{
for (int j = 0; j < streakList.size(); j++){
allStreakList.add(streakList.get(j));
}
}*/
prefs = getSharedPreferences("carter.streakly", MODE_PRIVATE);
editor = prefs.edit();
mTableLayout = (TableLayout) findViewById(R.id.all_streak_table);
int i = 0;
while (i < streakList.size()){
if (i % 2 == 0){
mTableRow = new TableRow(this);
mTableLayout.addView(mTableRow);
}
Button streakButton = new Button(this);
streakButton.setText(String.valueOf(streakList.get(i).getDaysKept()));
streakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(AllStreaks.this, EnlargedActivity.class);
startActivity(intent);
}
});
mTableRow.addView(streakButton);
i++;
}
}
}
you cannot pass object directly.you have to parcelable or serialize it. but in parecelable is part of android where serialzation is part of java so i suggest you to use parcelable.
you can make model class to parcelable from this link if you dont want to code for parcelabel.
parcelable creator
you can achieve like this.
class Car implements Parcelable {
public int regId;
public String brand;
public String color;
public Car(Parcel source) {
regId = source.getInt();
brand = source.getString();
color = source.getString();
}
public Car(int regId, String brand, String color) {
this.regId = regId;
this.brand = brand;
this.color = color;
}
public int describeContents() {
return this.hashCode();
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(regId);
dest.writeString(brand);
dest.writeString(color);
}
public static final Parcelable.Creator CREATOR
= new Parcelable.Creator() {
public Car createFromParcel(Parcel in) {
return new Car(in);
}
public Car[] newArray(int size) {
return new Car[size];
}
};}
And you can pass it like below.
ArrayList carList = new ArrayList();
carList.add(new Car('1','Honda','Black');
carList.add(new Car('2','Toyota','Blue');
carList.add(new Car('3','Suzuki','Green');
Intent i = new Intent(getApplicationContext(), CarDetailActivity.class);
i.putParcelableArrayListExtra("cars", carList);
this.startActivity(i);
you can get it like below:
Intent i = this.getIntent();
ArrayList<Car> carList = (ArrayList<Car>)i.getParcelableArrayListExtra("cars");`
You need to use Parcelable or Serializable interface.
and the pass it with intent
Intent mIntent = new Intent(context, ResultActivity.class);
mIntent.putParcelableArrayListExtra("list", mArraylist);
startActivity(mIntent);
fetch it in ResultActivity
Bundle bundle = getIntent().getExtras();
mArraylist1 = bundle.getParcelableArrayList("list");
Check this thread for reference
Do this on your Streak class and try,
Streak implements Parcelable
Since your modal class has not serialized, it may not able to pass via bundle. You can do that by implementing the Parcelable interface.
Parcelable is an Android specific interface where you implement the
serialization yourself. It was created to be far more efficient that
Serializable, and to get around some problems with the default Java
serialization scheme.
Serializable is a standard Java interface. You simply mark a class
Serializable by implementing the interface, and Java will
automatically serialize it in certain situations.
Courtsy
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.
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);
}