Random XML Layout on button click - java

I have 20 XML layouts. What I want to happen is to show random xml layouts when the button is clicked. I tried and read same problem as mine but i didnt worked.
For example in Level1 class when the user clicked the PositiveButton in the AlertDialog, random XML Layout will be opened (Level 20 or Level 15 not Level 2).
This is code in Level1 class(the same pattern applies for the rest of the classes)
public class Luzon1 extends Activity {
private String [] answers;
private Button answerButton;
private TextView scoreTxt, showClue;
private EditText answerText;
int scoreNew=0;
public Button yes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_luzon1);
}
public void init()
{
//correct answer
answers=new String[]{"Tarlac"};
(R.id.AnswerButton);
answerButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
checkAnswer();
}
});
}
public boolean isCorrect(String answer)
{ return(answer.equalsIgnoreCase(answers[currentQuestion])); }
public void checkAnswer()
{ String answer=answerText.getText().toString();
if(isCorrect(answer))
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Congratulations! You will receive P10!");
builder.setMessage("Did you know that Former bla bla bla Did you know that Former bla bla bla Did you know that Former bla bla bla");
builder.setIcon(android.R.drawable.btn_star_big_on);
builder.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String userData=scoreTxt.getText().toString();
int userNumber=Integer.parseInt(userData);
Intent intent=new Intent(Luzon1.this, Luzon2.class);
intent.putExtra("parameter name", userNumber);
startActivity(intent);
Luzon1.this.finish(); System.exit(0);
} });
AlertDialog alert = builder.create();
alert.show(); // Show Alert Dialog
Thank you so much in advance. and any code snippet will be a great help.

Setting the layout from inside onClick()
If you want this code to be in the onClick() method in your previous activity (the one shown above), use the following code:
#Override
protected void onClick(DialogInterface dialog, int which) {
Random generator = new Random();
int number = generator.nextInt(NUMBER_OF_LEVELS) + 1;
Class activity;
switch(number) {
case 1:
activity = LevelOne.class;
break;
case 2:
activity = LevelTwo.class;
break;
case 3:
activity = LevelThree.class;
break;
case 4:
activity = LevelFour.class;
break;
case 5:
activity = LevelFive.class;
break;
...
case 20:
activity = LevelTwenty.class;
break;
}
Intent intent = (getBaseContext(), activity);
startActivity(intent);
}

Try this:
Declare a public static int count = 0 before onCreate..
then, In onClick increment the count by 1(count++)..
Use switch statement like,(Dont forget to reset counter to 0 when count becomes 20)
void onClick(){
count++;
switch(count) {
case 1:
setContentView(R.layout.yourLayout1);
break;
case 2:
setContentView(R.layout.yourLayout2);
break;
case 3:
setContentView(R.layout.yourLayout3);
break;
case 4:
setContentView(R.layout.yourLayout4);
................................
................................
case 20:
setContentView(R.layout.yourLayout20);
break;
}
if(count==20){
count = 0;
}
}
And also instead of incrementing count each time user clicks, you can use Math.random() and assign it to count (Remember to check(use if statement) Math.random() is returning a value which is below or equal to 20..)
Hope it will help you..

Related

AlertDialog not closing when inforamtion is saved

My previous question is solved, but now I have another one.
My If condition not working properly
Scenario:
1. If user has not filled up his Name, then Alert Dialog is displayed
2. If user has filled up his Name, then Alert Dialog should NOT displayed
In my case, I will get Alert Dialog in any case, it does not care if Name is filled or not.
ArtistProfileView.Java
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_artist_profile_view, container, false);
prefrence = SharedPrefrence.getInstance(getActivity());
userDTO = prefrence.getParentUser(Consts.USER_DTO);
paramsRate.put(Consts.ARTIST_ID, userDTO.getUser_id());
parms.put(Consts.ARTIST_ID, userDTO.getUser_id());
parms.put(Consts.USER_ID, userDTO.getUser_id());
baseActivity.headerNameTV.setText(getResources().getString(R.string.my_profile));
if(artistDetailsDTO.getName().isEmpty()) {
new AlertDialog.Builder(getActivity())
.setView(getLayoutInflater().inflate(R.layout.test5, null))
.setPositiveButton(R.string.okaypopup22,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
my_tag = 1;
dialogPersonalProfile();
}
})
.show();
}
setUiAction(view);
return view;
}
In the same Class, method which calls profile editing
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ivEditPersonal:
my_tag = 1;
dialogPersonalProfile();
break;
case R.id.ivEditAbout:
my_tag = 2;
dialogAbout();
break;
case R.id.ivEditQualification:
dialogQualification();
break;
case R.id.ivEditSkils:
my_tag = 3;
dialogSkills();
break;
case R.id.ivEditProduct:
dialogProduct();
break;
case R.id.ivEditGallery:
dialogGallery();
break;
}
}
At first I misunderstood your question, so I have edited it.
I guess you should try adding equals() method in if condition
if(artistDetailsDTO.getName().toString.equals(""))

Global value becomes null in method

I have created a private member of the whole class called Member curMbr;
The activity (rather the fragment, since this is in a frament class) has a listview
with some contributions from members.
I also have a context menu on that list. When clicking on a contribution, I want a (customized) dialog box to show details about the member. (Member ID is part of the contribution objet. )
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
Log.d("FRGCOTIZ02", "create ctxt menu");
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
String[] menuItems = getResources().getStringArray(R.array.ar_menu_ctxt_participant);
// Get selected member
Contribution curCotis = (Contribution) (((ListView)v).getItemAtPosition(info.position));
Participant p = new Participant(helper.getDBItem(DBHelper.TABLE_PARTICIPANT,
DBHelper.COL_ID, curCotis.getParticipant()));
curMbr = new Member(helper.getDBItem(DBHelper.TABLE_MEMBER, DBHelper.COL_ID, p.getMember()));
for (int i = 0; i < menuItems.length; i++) {
menu.add(Menu.NONE, i, i, menuItems[i]);
}
Log.d("FRGCOTIZ01", curMbr.getId_());
}
#Override
public boolean onContextItemSelected(MenuItem item) {
return ( applyContextMenuSelection(item) || super.onContextItemSelected(item) );
}
private boolean applyContextMenuSelection(MenuItem item) {
switch (item.getItemId()) {
case 0: // Summary
final Dialog dlg = new Dialog(this.getContext());
final String sessID;
try {
sessID = KUtil.DATE_FORMAT.format(curSess.getDate());
dlg.setContentView(R.layout.alert_show_charges);
Button btnOK = dlg.findViewById(R.id.btn_alertOK);
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setupAlertDialogCharges(dlg, sessID, curMbr.getId_());
}
});
Button btnCancel = dlg.findViewById(R.id.btn_alertCancel);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dlg.dismiss();
}
});
dlg.show();
} catch (Exception e){
Log.d("FRAGMENT Contribution", e.getMessage());
}
break;
case 1: // Collect
break;
case 2: // Cancel
break;
default:
break;
}
return true;
}
In method onCreateContextMenu, I can get the member and display his ID.
But in method applyContextMenuSelection, there is an exception, saying the meber is null!
Funny enough there is another variable that I am using in that method, and it works fine. Difference is, that variable has been set at creation of the fragment.
How do I solve this?
I have been studying the code for a while and the only thing I could figure was that the issue is somehow linked to the use of contextmenu. It seems to me that variables are set back to their original when the menu action is supposed to be executed. Again, I am not too sure about that.
So, the only solution I found so far was to keep that vale in a "higher" context:
When I can still read the value,
getActivity().getIntent().putExtra(HomeActivity.ID_ENTRY, curMbr.getId_());
When I want to use it,
final String mbrID = getActivity().getIntent().getStringExtra(HomeActivity.ID_ENTRY);

Tell which is pressed using Array of ImageButtons

I have a basic hangman game, and the buttons to make the guesses are all placed on screen with ImageButtons (I had this working perfectly).
I declare the image button ID's like so:
private static final int[] BUTTON_IDS = {
R.id.imageButtonA, R.id.imageButtonB, R.id.imageButtonC, R.id.imageButtonD, R.id.imageButtonE,
R.id.imageButtonF, R.id.imageButtonG, R.id.imageButtonH, R.id.imageButtonI, R.id.imageButtonJ,
R.id.imageButtonK, R.id.imageButtonL, R.id.imageButtonM, R.id.imageButtonN, R.id.imageButtonO,
R.id.imageButtonP, R.id.imageButtonQ, R.id.imageButtonR, R.id.imageButtonS, R.id.imageButtonT,
R.id.imageButtonU, R.id.imageButtonV, R.id.imageButtonW, R.id.imageButtonX, R.id.imageButtonY, R.id.imageButtonZ
};
private List<ImageButton> buttonLetters = new ArrayList<ImageButton>();
Edited to show solution: I register their OnClick by doing:
for (int id: BUTTON_IDS) {
final ImageButton buttonLettersUsage = (ImageButton)findViewById(id);
if (buttonLetters != null) {
assert buttonLettersUsage != null;
buttonLettersUsage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(HangmanActivity.this, " " + buttonLettersUsage.getId(), Toast.LENGTH_SHORT).show();
switch (buttonLettersUsage.getId()){
case R.id.imageButtonQ:
strGuessed = "Q";
break;
case R.id.imageButtonW:
strGuessed = "W";
break;
case R.id.imageButtonE:
strGuessed = "E";
break;
// ... Repeat for rest of buttons ...
default:
break;
}
btnGuessClicked(theIncorrectGuesses, theWord);
buttonLettersUsage.setVisibility(View.INVISIBLE);
}
});
}
}
The problem is now, I've been working on the app some more since implementing this part, and all the buttonLettersUsage.getId()'s have changed.
My question is:
Will they change at any time?
I've not put any new components onto the activity, why have they changed?
Is there a better way to find out which button has been pressed, and give a different value for strGuessed depending on which has been pressed?
Many thanks.
Don't use the numerical ids in the switch case use it as follows.
switch (buttonLettersUsage.getId()){
case R.id.imageButtonA:
strGuessed = "Q";
break;
case R.id.imageButtonB:
strGuessed = "W";
break;
case R.id.imageButtonC:
strGuessed = "E";
break;
// ... Repeat for rest of buttons ...
default:
break;
}
And also don't implement onClickListener like this, use your Activity to implement View.OnClickListener and then set the listener in loop as
buttonLettersUsage.setOnClickListener(this);
Where this is the context of your activity which implements the OnClickListener
YourActivity implements View.OnClickListener{
then in oncreate(){
//add is buton
View buttonAdd = findViewById(R.id.add);
buttonAdd.setOnClickListener(this);}
then
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.add:
{
}
break;}

Return to Last Opened Activity if the App Re-open with Some Condition

I have a few interesting question here about how to return to latest activity if the game was restart/re-open because I have a new game button and continue button.So when continue button clicked it will return to last activity that opened before and the condition is activity is random from activityone to activityfive
I will explain with my code
this is menu.class
public class menu extends Activity {
int level;
Button newgame, continues, continuelocked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.menu);
continuelocked=(Button)findViewById(R.id.buttoncontinuelocked);
continues=(Button)findViewById(R.id.buttoncontinue);
newgame=(Button)findViewById(R.id.buttonnewgame);
newgame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
Intent i =new Intent(menu.this, intro.class);
startActivity(i);
}
});
}
public void onResume() {
super.onResume();
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
level = pref.getInt("Level", 0);
if(level == 0)
{
continuelocked.setVisibility(View.VISIBLE);
continues.setVisibility(View.GONE);
}
if(level == 1)
{
continuelocked.setVisibility(View.GONE);
continues.setVisibility(View.VISIBLE);
}
SharedPreferences.Editor editor = pref.edit();
editor.putInt("Level", level);
editor.commit();
continues=(Button)findViewById(R.id.buttoncontinue);
continues.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
//How to set this method to return to latest activity that i play before
//if i use random levelactivity?
});
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
and in intro.class I do this method to make activity random,
check my code below here -
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
button5 = (Button)findViewById(R.id.button5);
if(v==button5) {
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("Level", 1);
editor.commit();
// Here, we are generating a random number
Random generator = new Random();
int number = generator.nextInt(5) + 1;
// The '5' is the number of activities
Class activity = null;
// Here, we are checking to see what the output of the random was
switch(number) {
case 1:
// E.g., if the output is 1, the activity we will open is ActivityOne.class
activity = ActivityOne.class;
break;
case 2:
activity = ActivityTwo.class;
break;
case 3:
activity = ActivityThree.class;
break;
case 4:
activity = ActivityFour.class;
break;
default:
activity = ActivityFive.class;
break;
}
// We use intents to start activities
Intent intent = new Intent(getBaseContext(), activity);
startActivity(intent);
}
and in every Activity "One to Five" I put the same random activity code
#Override
public void onClick(View v) {
// Here, we are generating a random number
Random generator = new Random();
int number = generator.nextInt(5) + 1;
// The '5' is the number of activities
Class activity = null;
// Here, we are checking to see what the output of the random was
switch(number) {
case 1:
// E.g., if the output is 1, the activity we will open is ActivityOne.class
activity = ActivityOne.class;
break;
case 2:
activity = ActivityTwo.class;
break;
case 3:
activity = ActivityThree.class;
break;
case 4:
activity = ActivityFour.class;
break;
default:
activity = ActivityFive.class;
break;
}
// We use intents to start activities
Intent intent = new Intent(getBaseContext(), activity);
startActivity(intent);
}
}
So My question is
First. How to open the last Activity with a Continue button if Activity was Random?
Second. if in every Activity had a same Random code to One until Five, How to set Disabled to Activity that already Opened before?
Anyone can explain about this?
UPDATED
I have found a solution with my second answer, but i dont try it yet so i dont know it work or not
so i changed the code like this
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
button5 = (Button)findViewById(R.id.button5);
if(v==button5) {
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("Level", 1);
editor.commit();
layout7.setVisibility(View.GONE);
layout7.setVisibility(View.VISIBLE);
// Here, we are generating a random number
Random generator = new Random();
number = generator.nextInt(5) + 1;
// The '5' is the number of activities
Class activity = null;
// Here, we are checking to see what the output of the random was
switch(number) {
// E.g., if the output is 1, the activity we will open is ActivityOne.class
case 1: if(one == 1){
activity = ActivityOne.class;
}
else if(one == 2){
Random generatorone = new Random();
number = generatorone.nextInt(5) + 1;
}
break;
case 2: if(two== 1){
activity = ActivityTwo.class;
}
else if(two== 2){
Random generatortwo = new Random();
number = generatortwo.nextInt(5) + 1;
}
break;
case 3:if(three== 1){
activity = ActivityThree.class;
}
else if(three== 2){
Random generatorthree = new Random();
number = generatorthree.nextInt(5) + 1;
}
break;
case 4:if(four == 1){
activity = ActivityFour.class;
}
else if(four == 2){
Random generatorFour = new Random();
number = generatorFour.nextInt(5) + 1;
}
break;
default:if(five== 1){
activity = ActivityFive.class;
}
else if(five== 2){
Random generatorfive = new Random();
number = generatorfive.nextInt(5) + 1;
}
break;
}
// We use intents to start activities
Intent intent = new Intent(getBaseContext(), activity);
startActivity(intent);
}
};
i think, if the int was show ==2 its mean the Activity was already opened before. so it will random again till found activity with ==1
can anyone correct my code above? it is right or not?
and my first question still dont have an answer
First. How to open the last Activity with a Continue button if Activity was Random and the app was re-open/restart?
Thank you in advance, have a good day
For your first question, once you open your random Activity you can use SharedPreferences to store an ID for that Activity, and once you press your continue button, you can read this preferences, get this ID, and open the respective Activity.
For example, create an utility class to handle the SharedPreferences.
public class ActivityManager {
private static ActivityManager instance = null;
private SharedPreferences sharedPref;
private Context context_;
private final String prefName = "preferencesHandler";
public static ActivityManager getInstance(Context context) {
if (instance == null) {
instance = new ActivityManager(context);
}
return instance;
}
private ActivityManager(Context context) {
context_ = context;
sharedPref = context_.getSharedPreferences(prefName,Context.MODE_PRIVATE);
}
public void saveActivity(int ID) {
editor = sharedPref.edit();
// Key,Value
editor.putInt("activity_id",ID);
editor.commit();
}
public int getActivityID() {
// Key, Default Value
return sharedPref.getInt("activity_id",0);
}
}
And once you open each one of your random Activity, set some ID to them and save it using the class above. Then when needed, retrieve that value with getActivityID(). That should do the trick.
For more info on how to use SharedPreferences, please read this link.
EDIT: On your specific case, there's this part of your code:
// Here, we are checking to see what the output of the random was
switch(number) {
case 1:
// E.g., if the output is 1, the activity we will open is ActivityOne.class
activity = ActivityOne.class;
break;
case 2:
activity = ActivityTwo.class;
break;
case 3:
activity = ActivityThree.class;
break;
case 4:
activity = ActivityFour.class;
break;
default:
activity = ActivityFive.class;
break;
}
You can easily use that number variable as an ID. So, once you randomly get that number, you can also save it using the SharedPreferences. And when you press the continue Button, simply read that value and use a switch-case again to get the correct Activity.

I am not allowed to pass a string from resource file within a switch case [Android]

I have few buttons and I have the following click listener for the same:
private View.OnClickListener onclick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.home:
break;
case R.id.contact:
break;
case R.id.terms:
break;
case R.id.touch:
show(R.string.about_us); //Error here
break;
}
}
};
On each button click I display the same popup, only the text differs. I have text in strings.xml file
below is my dialog function:
public void show(String message){
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.terms);
//dialog.setTitle("Terms & Conditions");
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText(message);
text.setTypeface(helv_light);
ImageButton dialogButton = (ImageButton) dialog.findViewById(R.id.button1);
// dialogButton.setTypeface(helv_light);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
in case R.id.touch: My IDE complains with the following message:
show(java.lang.string) cannot be applied to (int).
If I replace show(R.string.about_us); with show(""+R.string.about_us); The error goes away, what do I miss here?
Use getResources().getString for getting string from strings.xml :
show(v.getContext().getResources().getString(R.string.about_us));
R.string.about_us is an int value, is not a string. To keep both you can overload show, providing the integer parameter, and call
public void show(final int messageId) {
sendMessage(getResources().getString(messageId));
}
The R.string.* values are ints. You need to use getResources().getString(R.string.str_id) to get the actual string value.

Categories