The app has a MainActivity with 6 editText fields, and a button. There are 5 more activities, named Activity2, Activity3, etc. Now, When a user enters names in editText fields, and press a button, the app should find out how many editText fields are filled, and open the activity with a corresponding number in it's name.
Example:
If only one field is filled, a toast should appear, saying More players.
If two fields are filled, app opens Activity2.
If three fields are filled, app opens Activity3, etc.
Now, to the problem. I am missing something out, and can't find out what. Here is MainActivity.java
public class MainActivity extends AppCompatActivity {
private EditText editText1,editText2,editText3,editText4,editText5,editText6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.btn);
editText1 = findViewById(R.id.editText1);
editText2 = findViewById(R.id.editText2);
editText3 = findViewById(R.id.editText3);
editText4 = findViewById(R.id.editText4);
editText5 = findViewById(R.id.editText5);
editText6 = findViewById(R.id.editText6);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int filledFileds = countFilledFields();
Log.d("filled", String.valueOf(filledFileds));
Class newClass = MainActivity.class;
switch (filledFileds){
case 1:
Context context = getApplicationContext();
CharSequence text = "You need more players!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
break;
case 2:
newClass = Activity2.class;
System.out.println("Activity2");
break;
case 3:
newClass = Activity3.class;
System.out.println("Activity3");
break;
case 4:
newClass = Activity4.class;
System.out.println("Activity4");
break;
case 5:
newClass = Activity5.class;
System.out.println("Activity5");
break;
case 6:
newClass = Activity6.class;
System.out.println("Activity6");
break;
default:
}
Intent intent = new Intent(MainActivity.this, newClass);
}
});
}
private int countFilledFields() {
ArrayList<EditText> editTexts = new ArrayList<>();
editTexts.add(editText1);
editTexts.add(editText2);
editTexts.add(editText3);
editTexts.add(editText4);
editTexts.add(editText5);
editTexts.add(editText6);
int filledNumber = 0;
for(int i = 0;i < editTexts.size() ;i++){
if(editTexts.get(i).getText()!=null && !editTexts.get(i).getText().toString().matches("")){
filledNumber += 1;
}
}
return filledNumber;
}
}
The log shows the exact number, something is not working...
Here is your click listener, with the switch omitted for brevity:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int filledFileds = countFilledFields();
Log.d("filled", String.valueOf(filledFileds));
Class newClass = MainActivity.class;
switch (filledFileds){
...
}
Intent intent = new Intent(MainActivity.this, newClass);
}
The problem is at the very end: you've created an Intent object ... but you're not doing anything with it. Probably you have just forgotten a startActivity() call:
Intent intent = new Intent(MainActivity.this, newClass);
startActivity(intent);
Also, looking this over, you have a problem with the case where the user only enters one EditText. As written, you'll still try to start a new activity (you'll just start a new copy of the same MainActivity, which is probably a bad idea). A better idea would be to only start the new activity if the user fills out enough EditTexts:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int filledFileds = countFilledFields();
Log.d("filled", String.valueOf(filledFileds));
Class newClass = null;
switch (filledFileds){
...
}
if (newClass != null) {
Intent intent = new Intent(MainActivity.this, newClass);
startActivity(intent);
}
}
You're missing one thing:
startActivity(intent);
Related
i'm trying to compile 4 integers from 4 different activities. the first activity is one of the 4 integer. the second activity is where i compile them.. I don't know what's the best way to send a value from different activites. Most of the intent methods i saw uses startActivity but still won't work.
public class QuizSecond extends AppCompatActivity implements View.OnClickListener{
TextView totalQuestionsTextView2;
TextView questionTextView2;
Button ansA2, ansB2, ansC2, ansD2;
Button submitBtn2;
int score= 0;
int totalQuestion2 = QuestionAnswer2.question2.length;
int currentQuestionIndex2 = 0;
String selectedAnswer2 = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_second);
totalQuestionsTextView2 = findViewById(R.id.total_question2);
questionTextView2 = findViewById(R.id.question_preview);
ansA2 = findViewById(R.id.ans_A2);
ansB2 = findViewById(R.id.ans_B2);
ansC2 = findViewById(R.id.ans_C2);
ansD2 = findViewById(R.id.ans_D2);
submitBtn2 = findViewById(R.id.submit_btn2);
ansA2.setOnClickListener(this);
ansB2.setOnClickListener(this);
ansC2.setOnClickListener(this);
ansD2.setOnClickListener(this);
submitBtn2.setOnClickListener(this);
totalQuestionsTextView2.setText("Total questions : "+totalQuestion2);
loadNewQuestion();
}
#Override
public void onClick(View view) {
ansA2.setBackgroundColor(Color.WHITE);
ansB2.setBackgroundColor(Color.WHITE);
ansC2.setBackgroundColor(Color.WHITE);
ansD2.setBackgroundColor(Color.WHITE);
Button clickedButton = (Button) view;
if(clickedButton.getId()==R.id.submit_btn2){
if(selectedAnswer2.equals(QuestionAnswer2.correctAnswers2[currentQuestionIndex2])) {
score++;
}
currentQuestionIndex2++;
loadNewQuestion();
Intent quizIntent = new Intent(QuizSecond.this,ComputeActivity.class);
quizIntent.putExtra("EXTRA_NUMBER",score);
}
else{
//choices button clicked
selectedAnswer2 = clickedButton.getText().toString();
clickedButton.setBackgroundColor(Color.MAGENTA);
}
}
void loadNewQuestion(){
if(currentQuestionIndex2 == totalQuestion2 ){
startActivity(new Intent(QuizSecond.this, ComputeActivity.class));
return;
}
questionTextView2.setText(QuestionAnswer2.question2[currentQuestionIndex2]);
ansA2.setText(QuestionAnswer2.choices2[currentQuestionIndex2][0]);
ansB2.setText(QuestionAnswer2.choices2[currentQuestionIndex2][1]);
ansC2.setText(QuestionAnswer2.choices2[currentQuestionIndex2][2]);
ansD2.setText(QuestionAnswer2.choices2[currentQuestionIndex2][3]);
}
}
second activity:
int number = getIntent().getIntExtra("EXTRA_NUMBER",0); if (number > 3){ Toast.makeText(ComputeActivity.this, "Your Message", Toast.LENGHT_LONG).show();}
Update this
Intent quizIntent = new Intent(QuizSecond.this, ComputeActivity.class);
quizIntent.putExtra("TRANSFER_NUMBER", score);
startActivity(quizIntent);
For some reason my buttons aren't doing anything. I've used this method to implement buttons before and it never gave me an issue. The app has seven different buttons that all move to a different activity.
public class ScheduleActivity extends AppCompatActivity implements View.OnClickListener {
private Button mondayButton,tuesdayButton,wednesdayButton,thursdayButton,fridayButton,saturdayButton,sundayButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule);
mondayButton = findViewById(R.id.monday_button);
tuesdayButton = findViewById(R.id.tuesday_button);
wednesdayButton = findViewById(R.id.wednesday_button);
thursdayButton = findViewById(R.id.thursday_button);
fridayButton = findViewById(R.id.friday_button);
saturdayButton = findViewById(R.id.saturday_button);
sundayButton = findViewById(R.id.sunday_button);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.monday_button:
Intent monday_intent = new Intent(ScheduleActivity.this, MondayActivity.class);
startActivity(monday_intent);
break;
case R.id.tuesday_button:
Intent tuesday_intent = new Intent(ScheduleActivity.this, TuesdayActivity.class);
startActivity(tuesday_intent);
break;
case R.id.wednesday_button:
Intent wednesday_intent = new Intent(ScheduleActivity.this, WednesdayActivity.class);
startActivity(wednesday_intent);
break;
case R.id.thursday_button:
Intent thursday_intent = new Intent(ScheduleActivity.this, ThursdayActivity.class);
startActivity(thursday_intent);
break;
case R.id.friday_button:
Intent friday_intent = new Intent(ScheduleActivity.this, FridayActivity.class);
startActivity(friday_intent);
break;
case R.id.saturday_button:
Intent saturday_intent = new Intent(ScheduleActivity.this, SaturdayActivity.class);
startActivity(saturday_intent);
case R.id.sunday_button:
Intent sunday_intent = new Intent(ScheduleActivity.this, SundayActivity.class);
startActivity(sunday_intent);
}
}
}
You are getting the instances of the buttons but never setting an OnClickListener for them. You need to set the click listener for the buttons:
mondayButton.setOnClickListener(this)
You need to do this to all buttons, this tells your code where to notify the event when the button is clicked.
you are not attaching the listener View.OnClickListener to any of your buttons.
add this in your onCreate() after you init your buttons, your buttons will work
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule);
...
sundayButton = findViewById(R.id.sunday_button);
// attaching listeners
mondayButton.setOnClickListener(this);
tuesdayButton.setOnClickListener(this);
wednesdayButton.setOnClickListener(this);
thursdayButton.setOnClickListener(this);
fridayButton.setOnClickListener(this);
saturdayButton.setOnClickListener(this);
sundayButton.setOnClickListener(this);
}
You have to set the view.setOnClickListener{} on the OnCreate method
private Button mondayButton,tuesdayButton,wednesdayButton,thursdayButton,fridayButton,saturdayButton,sundayButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule);
mondayButton = findViewById(R.id.monday_button);
tuesdayButton = findViewById(R.id.tuesday_button);
wednesdayButton = findViewById(R.id.wednesday_button);
thursdayButton = findViewById(R.id.thursday_button);
fridayButton = findViewById(R.id.friday_button);
saturdayButton = findViewById(R.id.saturday_button);
sundayButton = findViewById(R.id.sunday_button);
mondayButton.setOnClickListener() {
Intent intent = new Intent(...) ;
startActivity(intent) ;
}
}
I have about 50 activities in my app and I have an algorithm which displays the title of like 10 of those activities in the form of buttons in a super activity and sets an onclicklistener to each button which contains an intent and it calls the specific activity. I tried to do this via an array of intents but I got no success. Any suggestions on how I can perform this?
package plkk.developers.com.livfit;
// this is my string which contains name of activities
final String ActivityIdMen[] = { "Deadlift", "Pushups", "Barbell_Bench", "Military_Press", "Barbell_Curl", "Close_Bench", "Seated_Cable", "Chinup", "Overhead_Press",
"Power_Clean", "Jumping_Rope", "Hiit", "Barbell_Bench", "Deadlift", "Lat_Pulldown", "Barbell_Curl", "Skull_Crusher", "Diamond_Dips", "Squats",
"Hill_Running", "Jumping_Rope", "Stationary_Bike", "Hiit", "Chinup", "Torso_Rotation", "Prone_Plank", "Medicine_Squat", "Front_Squat"
};
// this is a fragment of the algorithm where I need help
if(BMI<18.5){
for(i=0;i<=8;i++) {
Button btn = new Button(this);
LinearLayout.LayoutParams P = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
P.weight = 1;
btn.setLayoutParams(P);
btn.setText(ActivityTextMen[i]);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Class clas = null;
try{
clas = Class.forName("plkk.developers.com.livfit."+ActivityIdMen[i]);
}catch (ClassNotFoundException c){
c.printStackTrace();
}
if (clas!=null) {
Intent intent = new Intent(view.getContext(), clas);
startActivity(intent);
}
}
});
ll.addView(btn);
}
// the intent always directs me to the class at i=9 (in the above case. I tried solving it by using array of intents but couldn't do that properly.
Remove the weight assigmnent.
Did you declare your activities in te manifest file?
Updated
Try to set a Tag with the index. Then use the value of the tag of your button to get the value.
if(BMI<18.5){
for(i=0;i<=8;i++) {
Button btn = new Button(this);
LinearLayout.LayoutParams P = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
P.weight = 1;
btn.setTag(i);
btn.setLayoutParams(P);
btn.setText(ActivityTextMen[i]);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Class clas = null;
try{
clas = Class.forName("plkk.developers.com.livfit."+ActivityIdMen[Integer.parseInt(""+btn.getTag())]);
}catch (ClassNotFoundException c){
c.printStackTrace();
}
if (clas!=null) {
Intent intent = new Intent(view.getContext(), clas);
startActivity(intent);
}
}
});
ll.addView(btn);
}
I'm new to android development and I am creating an android application that works like "4 Pics 1 Word" for my project. I'm having difficulties in storing ArrayList in SharedPreferences or in the internal storage of the android phone. The reason why is because I am randomizing the next activity using random generator and ArrayList. Any suggestions or ideas that my help my case? Thank you in advance! I've been stuck here for hours now.
This is my MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
Button btnStart;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnStart = (Button) findViewById(R.id.btnStart);
btnStart.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// We are creating a list, which will store the activities that haven't been opened yet
ArrayList<Class> activityList = new ArrayList<>();
activityList.add(first.class);
activityList.add(second.class);
activityList.add(third.class);
activityList.add(fourth.class);
activityList.add(fifth.class);
Random generator = new Random();
int number = generator.nextInt(5) + 1;
Class activity = null;
// Here, we are checking to see what the output of the random was
switch(number) {
case 1:
activity = first.class;
// We are adding the number of the activity to the list
activityList.remove(first.class);
break;
case 2:
activity = second.class;
activityList.remove(second.class);
break;
case 3:
activity = third.class;
activityList.remove(third.class);
break;
case 4:
activity = fourth.class;
activityList.remove(fourth.class);
break;
default:
activity = fifth.class;
activityList.remove(fifth.class);
break;
}
// We use intents to start activities
Intent intent = new Intent(getBaseContext(), activity);
// `intent.putExtra(...)` is used to pass on extra information to the next activity
intent.putExtra("ACTIVITY_LIST", activityList);
startActivity(intent);
}
}
And here's my first activity:
public class first extends AppCompatActivity implements View.OnClickListener{
EditText etAnswer;
Button btnGo;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
etAnswer = (EditText) findViewById(R.id.etAnswer);
btnGo = (Button) findViewById(R.id.btnGo);
btnGo.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnGo:
String answer = etAnswer.getText().toString();
if(answer.equals("Jose Rizal") || answer.equals("jose rizal") || answer.equals("Rizal") || answer.equals("rizal") ){
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("The famous Rizal monument in Luneta was not the work of a Filipino but a Swiss sculptor named Richard Kissling?" +
"Source: http://www.joserizal.ph/ta01.html");
dlgAlert.setTitle("Did you know that ...");
dlgAlert.setPositiveButton("Next",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ArrayList<Class> activityList = new ArrayList<>();
Bundle extras = getIntent().getExtras();
activityList = (ArrayList<Class>) extras.get("ACTIVITY_LIST");
if(activityList.size() == 0) {
Context context = getApplicationContext();
CharSequence last = "Congratulations! You just finished the game! Please wait for the next update!";
int durationFinal = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, last, durationFinal);
toast.show();
} else {
// Now, the random number is generated between 1 and however many
// activities we have remaining
Random generator = new Random();
int number = generator.nextInt(activityList.size()) + 1;
Class activity = null;
// Here, we are checking to see what the output of the random was
switch(number) {
case 1:
// We will open the first remaining activity of the list
activity = activityList.get(0);
// We will now remove that activity from the list
activityList.remove(0);
break;
case 2:
// We will open the second remaining activity of the list
activity = activityList.get(1);
activityList.remove(1);
break;
case 3:
// We will open the third remaining activity of the list
activity = activityList.get(2);
activityList.remove(2);
break;
case 4:
// We will open the fourth remaining activity of the list
activity = activityList.get(3);
activityList.remove(3);
break;
default:
// We will open the fifth remaining activity of the list
activity = activityList.get(4);
activityList.remove(4);
break;
}
// Note: in the above, we might not have 3 remaining activities, for example,
// but it doesn't matter because that case wouldn't be called anyway,
// as we have already decided that the number would be between 1 and the number of
// activities left.
// Starting the activity, and passing on the remaining number of activities
// to the next one that is opened
Intent intent = new Intent(getBaseContext(), activity);
intent.putExtra("ACTIVITY_LIST", activityList);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
});
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}else{
Context context = getApplicationContext();
CharSequence text = "Wrong! Try Again.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
break;
}
}
}
Okay, this is a horrible hack and I don't endorse it in any way, but since you are so close to finishing your app, I propose a workaround:
Instead of storing an ArrayList<Class> in your SharedPreferences (which is impossible), store a HashSet<String> containing the fully qualified names of your classes via putStringSet().
In order to get the String representations of the fully qualified names of your classes you need to call getName(), e.g. first.class.getName().
Then, you can get your Set<String> from SharedPreferences using getStringSet() and create a Class instance for each String in that set via Class.forName().
I m working on a project i have two categories Cricketers and Animals on one activity as Button and a Text View on other activity i want to change the text of Text View when ever i presses the Button i.e If Cricketer then set text to cricketer same goes for animal.
OnClick Listner for both buttons: On Activity 1
public void onClickcricketer(View view){
Intent i = new Intent(this,offlineQuestionsession.class);
final Button b = (Button)findViewById(R.id.btncricket);
String crickettext = b.getText().toString();
i.putExtra("Cricket",crickettext);
startActivity(i);
}
public void onClickanimal(View view){
Intent i = new Intent(this,offlineQuestionsession.class);
final Button b = (Button)findViewById(R.id.btnanimal);
String animaltext = b.getText().toString();
i.putExtra("Animal",animaltext);
startActivity(i);
}
Code on Activity 2:
Bundle cricketData = getIntent().getExtras();
if (cricketData == null){
return;
}
String Cricket = cricketData.getString("Cricket");
final TextView c = (TextView)findViewById(R.id.txtCategryShow);
c.setText(Cricket);
Bundle AnimalData = getIntent().getExtras();
if (AnimalData == null){
return;
}
String Animal = AnimalData.getString("Animal");
final TextView a = (TextView)findViewById(R.id.txtCategryShow);
a.setText(Animal);
This method just show animal text in Text view.. when i click Crcketer button it shows nothing
First perform an onClick method:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String toExtra = "" + btn.getText();
Intent i = new Intent(this,NextActivity.class);
i.putExtra("key",toExtra);
}
});
then in the new Activity OnCreate method add:
Intent i = getIntent();
String fromExtra = intent.getStringExtra("key");
and finally setText to your TextView:
txt.setText(fromExtra)
It is doing correct, see your code again, On same TextView you are setting text Animal which is null in case of clicking cricket ..
Try this in second activity:
String Cricket = getIntent().getStringExtra("KEY");
final TextView c = (TextView)findViewById(R.id.txtCategryShow);
c.setText(Cricket);
And make your methods like this:
public void onClickcricketer(View view){
Intent i = new Intent(this,YourNewActivity.class);
final Button b = (Button)findViewById(R.id.txv_cricket);
String crickettext = b.getText().toString();
i.putExtra("KEY",crickettext);
startActivity(i);
}
public void onClickanimal(View view){
Intent i = new Intent(this,YourNewActivity.class);
final Button b = (Button)findViewById(R.id.txv_animal);
String animaltext = b.getText().toString();
i.putExtra("KEY", animaltext);
startActivity(i);
}