I created an application that have 4 activities: login, sport, technology and sporttechnology.
the login activity that contains two check boxes in a listview (named sport and technology) and a button, when press the button the program check the text of the checked check boxes and opens the right activity based on it, if only the sport checkbox have been checked it should opens the sport activity, if only the technology checkbox have been chosen then it will open the technology activity, if both checkboxes have been checked then it will open an activity named "sporttecknology".
when run the app, when I choose only the sport checkbox and then press the button, it opens the sport activity. but when I choose only the technology checkbox and then press the button the app stop working, and also that happens when I choose both checkboxes then press the button,
so is there any error in my code?
private void checkButtonClick() {
Button myButton = (Button) findViewById(R.id.findSelected);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuffer responseText = new StringBuffer();
//responseText.append("The following were selected...\n");
ArrayList<Interestclass> interestList = dataAdapter.interestList;
for (int i = 0; i < interestList.size(); i++) {
Interestclass interest = interestList.get(i);
if (interest.isSelected()) {
responseText.append(interest.getName());//"\n" +
}
}
Toast.makeText(getApplicationContext(), responseText, Toast.LENGTH_LONG).show();
String start = responseText.toString();
if (start.equals("Sport")) {
Intent intentSport = new Intent(MainActivity.this, Sport.class);
startActivity(intentSport);
}
else if (start.equals("Technology")) {
Intent intentTechnology = new Intent(MainActivity.this, Technology.class);
startActivity(intentTechnology);
}
else if (start.equals("SportTechnology")) {
Intent intentSportTech = new Intent(MainActivity.this, SportTechnology.class);
startActivity(intentSportTech);
}
else {
Intent intentTechnology = new Intent(MainActivity.this, Technology.class);
startActivity(intentTechnology);
}
/*
switch (start) {
case "Sport":
Intent intentSport = new Intent(MainActivity.this, Sport.class);
startActivity(intentSport);
break;
case "Technology":
Intent intentTechnology = new Intent(MainActivity.this, Technology.class);
startActivity(intentTechnology);
break;
}*/
}
});
}
Related
I'm creating a security settings part in my app.
There are 3 radio buttons that allow the user to choose between a passcode, TouchID or nothing. All radio buttons are unchecked by default. When clicking on a radio button (e.g. to use passcode), the code checks to see if the user has set up a passcode. If the user hasn't, a dialog is shown and the radio button remains unchecked. The user then goes and sets up a passcode (setUpPasscode button).
Once set up, the passcode activity closes with the return case '2' and the radio button with the passcode option should be checked. It isn't however. When I re-launch the application, the button is checked though. It somehow isn't checked immediately after finishing the previous activity but it is technically checked. What am I doing wrong?
public class SecuritySettings extends AppCompatActivity
{
TextView goBackToSettings;
Button setUpPasscode;
Button setUpTouchID;
RadioButton usePasscodeSelection;
RadioButton useTouchIDSelection;
RadioButton useNeitherSelection;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
Dialog myDialog;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.security_settings);
goBackToSettings = (TextView) findViewById(R.id.closeSettingsButtonID);
setUpPasscode = (Button) findViewById(R.id.setUpPasscodeButtonID);
setUpTouchID = (Button) findViewById(R.id.setUpTouchIDButtonID);
usePasscodeSelection = (RadioButton) findViewById(R.id.usePasscode);
useTouchIDSelection = (RadioButton) findViewById(R.id.useTouchID);
useNeitherSelection = (RadioButton) findViewById(R.id.useNothing);
myDialog = new Dialog(this);
//load state of radio buttons
loadRadioButtons();
// go back to main settings page
goBackToSettings.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent goBackToMainSettings = new Intent(getApplicationContext(), AppSettings.class);
goBackToMainSettings.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(goBackToMainSettings);
finish();
}
});
//Open new activity for setting passcode
setUpPasscode.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent setUpPasscodeActivity = new Intent(getApplicationContext(), SetupPasscode.class);
startActivityForResult(setUpPasscodeActivity, 2);
}
});
// Open new activity for setting up TouchID
setUpTouchID.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent setupTouchIDActivity = new Intent(getApplicationContext(), SetupTouchID.class);
startActivityForResult(setupTouchIDActivity, 1);
}
});
// when clicked, all other buttons become unchecked and the state of the buttons are saved
usePasscodeSelection.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
boolean bCheckForPasscode = doesUserHavePasscode();
// If true, user has a passcode setup
if (bCheckForPasscode)
{
usePasscodeSelection.setChecked(true);
useTouchIDSelection.setChecked(false);
useNeitherSelection.setChecked(false);
saveRadioButtons();
}
else
{
//No passcode detected for user
// Load previous radio button configuration since the selection wasn't valid
loadRadioButtons();
NoOptionSetPopup(null, "You must set up a passcode to enable this option.");
}
}
});
useTouchIDSelection.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
boolean bCheckForTouchID = doesUserHaveTouchIDSetup();
// If true, user has TouchID setup
if (bCheckForTouchID)
{
usePasscodeSelection.setChecked(false);
useTouchIDSelection.setChecked(true);
useNeitherSelection.setChecked(false);
saveRadioButtons();
}
else
{
//No passcode detected for user
// Load previous radio button configuration since the selection wasn't valid
loadRadioButtons();
NoOptionSetPopup(null, "You must set up TouchID to enable this option.");
}
}
});
useNeitherSelection.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
usePasscodeSelection.setChecked(false);
useTouchIDSelection.setChecked(false);
useNeitherSelection.setChecked(true);
saveRadioButtons();
}
});
}
// Open sharedpreferences and get the value that was saved there after setting up passcode using the same key 'string'
public boolean doesUserHavePasscode()
{
sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
String checkHashString = sharedPreferences.getString("hashed_password", null);
if (checkHashString == null)
{
return false;
}
else
{
return true;
}
}
// Open sharedpreferences and get the value that was saved there after setting up TouchID using the same key 'string'
public boolean doesUserHaveTouchIDSetup()
{
sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
boolean bDoesUserHaveTouchIDSetup = sharedPreferences.getBoolean("doesUserHaveTouchIDSetup", false);
return bDoesUserHaveTouchIDSetup;
}
public void NoOptionSetPopup(View v, String message)
{
TextView closePopup;
TextView contents;
myDialog.setContentView(R.layout.no_option_setup_popup);
closePopup = (TextView) myDialog.findViewById(R.id.closePopupButtonID);
contents = (TextView) myDialog.findViewById(R.id.theMessageID);
contents.setText(message);
closePopup.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
//Close popup
myDialog.dismiss();
}
});
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
myDialog.show();
}
// Callback method to get the boolean from SetupPasscode/SetupTouchID activity & override the method
// What is being done here is that after a passcode/TouchID has been setup, we automatically assume that the newly set-up authentication will want to be used by the user.
// The values being returned from the activities only happen when they're successfully done (passed all validation checks).
// We then automatically make the corresponding radio button selected (if passcode setup, then select the 'use passcode on startup' radio button)
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
{
// Case for returning from SetupPasscode class
case 2:
// fetch the boolean value
boolean isDone = data.getBooleanExtra("isDone", false);
usePasscodeSelection.setChecked(isDone);
useTouchIDSelection.setChecked(false);
useNeitherSelection.setChecked(false);
saveRadioButtons();
loadRadioButtons();
break;
// Case for returning from SetupTouchID class
case 1:
// fetch the boolean value
boolean isTouchIDSetup = data.getBooleanExtra("isTouchIDDone", false);
usePasscodeSelection.setChecked(false);
useTouchIDSelection.setChecked(isTouchIDSetup);
useNeitherSelection.setChecked(false);
saveRadioButtons();
loadRadioButtons();
break;
default:
throw new IllegalStateException("Unexpected value: " + requestCode);
}
}
public void saveRadioButtons()
{
sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
editor = sharedPreferences.edit();
editor.putBoolean("usePasscodeOption", usePasscodeSelection.isChecked());
editor.putBoolean("useTouchIDOption", useTouchIDSelection.isChecked());
editor.putBoolean("useNeitherOption", useNeitherSelection.isChecked());
}
public void loadRadioButtons()
{
sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
usePasscodeSelection.setChecked(sharedPreferences.getBoolean("usePasscodeOption", false));
useTouchIDSelection.setChecked(sharedPreferences.getBoolean("useTouchIDOption", false));
useNeitherSelection.setChecked(sharedPreferences.getBoolean("useNeitherOption", false));
}
}
I would suggest to overload the onResume method and checking the state of your radio buttons as that will be the last control where the flow will leave your activity.
Is it possible to define the source of a click? I can access my MainActivity through either clicking on a RecyclerView or through a Notification action. Depending on which it is, I need to provide different info. Is there a way of saying: if click is from recyclerview then..., else if it is from notification action then...?
What I can think of so far is this, but the problem is I am not using buttons as such:
Button mClickButton1 = (Button)findViewById(R.id.clickButton1);
mClickButton1.setOnClickListener(this);
Button mClickButton2 = (Button)findViewById(R.id.clickButton2);
mClickButton2.setOnClickListener(this);
public void onClick(View v) {
switch (v.getId()) {
case R.id.clickButton1: {
// do something for button 1 click
break;
}
case R.id.clickButton2: {
// do something for button 2 click
break;
}
}
}
Thanks!
you have to define two different calling intents for the same activity and put info for each View Example :
mClickButton1.setOnClickListener(new onClickListener(){
public void onClick(View v) {
Intent view1_int = new Intent (this, MainActivity.class);
view1_int.putExtra("Calling Intent" ,"RecyclerView");
startaActivityForResult(view1_int);
}
});
mClickButton2.setOnClickListener(new onClickListener(){
public void onClick(View v) {
Intent view2_int = new Intent (this, MainActivity.class);
view1_int.putExtra("Calling Intent" ,"Notification action");
startaActivityForResult(view1_int);
}
});
and in the onCreate Method in your MainActivity you can say :
String callin_view;
callin_view =getresources.getIntent.getExtras("Calling_Intent");
This will retrieve the name of the calling source you defined
I'm having problem in storing the intent.putExtra inside the android local database. I am creating a game like 4Pics1Word for my project. It has only 25 levels so I created 25 activities and I randomized it. After solving a particular activity, it will then be removed to the ArrayList of Classes, ArrayList<Class>. Now, I used intent.putExtra("ACTIVITY_LIST", activityList); to store the intent and to pass it to the next activity. My problem is I can't store it on local database. When I exit the game the progress is not saved, it starts again from the first level. Any suggestions? Thank you!
Here's my code in my Main Activity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
Button btnStart;
Context context;
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
#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;
switch(number) {
case 1:
activity = first.class;
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;
}
Intent intent = new Intent(getBaseContext(), activity);
intent.putExtra("ACTIVITY_LIST", activityList);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(activityList); // myObject - instance of MyObject
prefsEditor.putString("MyObject", json);
prefsEditor.commit();
startActivity(intent);
}
}
Here's my code in 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?" +
"\n" +
"\n" +
"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;
}
}
}
Everytime you come to MainActivity , you new an ArrayList and add all the activities rather than get the cache from your local SharedPreferences .
When you finish one game in an Activity , you did not save your progress in cache.
After updating the arrayList,save your arrayList like this :
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(activityList); // myObject - instance of MyObject
prefsEditor.putString("MyObject", json);
prefsEditor.commit();
And when you want to read the arrayList saved ,do like this:
String arrayStr = mPrefs.getString("myObject","defValue");
Gson gson = new Gson();
List<Class> array = gson.fromGson(arrayStr,new TypeToken<List<Class>>(){}.getType());
if(array==null){
array = new ArrayList<>();
array.add(...);
}
I have a task to make a simple restaurant menu app in Android. So, the home page consist of Food button and Drink button. If Food button clicked, the food menu page will appear. If Drink button clicked, the drink menu page will appear.
MainActivity.java:
int x = 1;
public int value()
{
x = 1;
return x;
}
public void clickFood(View view)
{
value();
Intent intent = new Intent(MainActivity.this, MenuList.class);
startActivity(intent);
}
public int value2()
{
x = 2;
return x;
}
public void clickDrink(View view)
{
value2();
Intent intent = new Intent(MainActivity.this, MenuList.class);
startActivity(intent);
}
MenuList.java:
mainListView = (ListView) findViewById(R.id.mainListView );
int y = 1;
if(main.x == y)
{
// List of food
fooddrink = new String[]{"Fried Chicken", "Fried Rice"};
}
else
{
// List of drink
fooddrink = new String[]{"Ice Tea", "Ice Coffee"};
}
ArrayList<String> listFoodDrink = new ArrayList<String>();
listFoodDrink.addAll( Arrays.asList(fooddrink) );
listAdapter = new ArrayAdapter<String>(this, R.layout.menu_list_row, listFoodDrink);
mainListView.setAdapter( listAdapter );
The problem, the output of ListView is always display food menu, despite I click Drink button. I find that this is because x value in MainActivity.java doesn't return the value, so the int x value always = 1.
How am I doing wrong?
This is your problem:
MainActivity main = new MainActivity();
You create a new instance of MainActivity (not the one you've "come from") where x = 1.
Make x in MainActivity, for example, static like
static int x = 1;
and use it in MenuList.java as follows:
if(MainActivity.x == y)
{ ...
But!
That is NOT how you should go in Android taking into consideration its component's lifecycle (more on that). Once MainActivity has been destroyed by the system, x, as being static, is always = 1, unless another instance of MainActivity has changed it.
So, you may use several options, one of which would be to store x value somewhere, e.g. in SharedPreferences. Another one would be to pass the value within Intent's extra as per #VVJ's answer.
You have two activities MainActivity and MenuListActivity.In MainActivity there are two buttons Food and Restaurant. You have handle click event for each as follows:
foodButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MenuList.class);
intent.putExtra("type",1);//pass 1 for food
startActivity(intent);
}
});
restaurantButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MenuList.class);
intent.putExtra("type",2);//pass 2 for Restaurant
startActivity(intent);
}
});
Now in your MenuList activity you have to take value of key "type" and based on type value pass appropriate data source to adapter.You can do something like this(in onCreate of MenuList activity):
int type=getActivity().getIntent().getExtras().getInt("type");
i(type==1)
{
// List of food
fooddrink = new String[]{"Fried Chicken", "Fried Rice"};
}
else
{
// List of drink
fooddrink = new String[]{"Ice Tea", "Ice Coffee"};
}
ArrayList<String> listFoodDrink = new ArrayList<String>();
listFoodDrink.addAll( Arrays.asList(fooddrink) );
listAdapter = new ArrayAdapter<String>(this, R.layout.menu_list_row, listFoodDrink);
mainListView.setAdapter( listAdapter );
I am developing a quiz application with two navigation buttons (back and next), and each quiz has an array of 30 questions. Now when btnnext reaches the last question, it should open another activity(Review) when u click on it again
next = (Button)findViewById(R.id.next);
next.setVisibility(View.GONE);
next.setOnClickListener(nextListener);
private View.OnClickListener nextListener = new View.OnClickListener() {
public void onClick(View v) {
setAnswer();
quesIndex++;
if (quesIndex >= QuizFunActivity.getQuesList().length())
quesIndex = QuizFunActivity.getQuesList().length() - 1;
showQuestion(quesIndex,review);
}
};
next = (Button)findViewById(R.id.next);
next.setVisibility(View.GONE);
next.setOnClickListener(nextListener);
private View.OnClickListener nextListener = new View.OnClickListener() {
public void onClick(View v) {
setAnswer();
if (quesIndex != QuizFunActivity.getQuesList().length()-1) {
quesIndex++;
showQuestion(quesIndex,review);
}
else {
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value); //Optional parameters
CurrentActivity.this.startActivity(myIntent);
}
if (quesIndex == QuizFunActivity.getQuesList().length()-1)
next.setText("Finish");
}
};
Add the piece of code for next activity
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value); //Optional parameters
CurrentActivity.this.startActivity(myIntent);
You have to check for the last question and change the button view text to finish.