Sorry if this is poor etiquette but I have now re-written my entire question as the original question I asked didn't actually relate to my problem as I have just realised. I am having trouble updating the code in an activity after I return to it. The first activity contains a bunch of imageButtons which relate to levels. When the app is first run only the level one button is enabled. When that button is clicked it sends the user to a new activity where they must spell a set amount of words to unlock the next level. This is the code for my level select activity.
public class QuizLevelSelect extends AppCompatActivity {
private static int myLevel;
ImageButton level1, level2, level3, level4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_level_select);
TextView title = (TextView) findViewById(R.id.title);
Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/variane-script.regular.ttf");
title.setTypeface(custom_font);
level1 = (ImageButton)findViewById(R.id.level1);
level2 = (ImageButton)findViewById(R.id.level2);
level2.setEnabled(false);
level3 = (ImageButton)findViewById(R.id.level3);
level3.setEnabled(false);
level4 = (ImageButton)findViewById(R.id.level4);
level4.setEnabled(false);
level1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent i = new Intent(getApplicationContext(), Main2Activity.class);
i.putExtra("intVariableName", 1);
startActivity(i);
finish();
}
});
level2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent i = new Intent(getApplicationContext(), Main2Activity.class);
i.putExtra("intVariableName", 2);
startActivity(i);
finish();
}
});
level3.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent i = new Intent(getApplicationContext(), Main2Activity.class);
i.putExtra("intVariableName", 3);
startActivity(i);
}
});
}
#Override
protected void onResume(){
super.onResume();
ParseQuery<ParseObject> query = ParseQuery.getQuery("Wordbank");
query.whereEqualTo("username", ParseUser.getCurrentUser().getUsername());
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
for (ParseObject object : objects){
myLevel = object.getInt("level");
}
});
if (myLevel == 2){
level2.setEnabled(true);
}
}
}
When the level one button is clicked it starts a new activity where the user has to spell a set amount of words (only 1 at the moment, for testing purposes), when the user has spelled the required words it is supposed to send them back to the level select activity and unlock the level 2 button. This is the code for the second activity that checks they have spelled the words and then updates the level they are at on Parse.com before returning them to the level select activity.
if (count == 1){
ParseQuery<ParseObject> query2 = ParseQuery.getQuery("Wordbank");
query2.whereEqualTo("username", ParseUser.getCurrentUser().getUsername());
query2.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
objects.get(0).put("level", ++intValue);
objects.get(0).saveInBackground();
Intent i = new Intent(getApplicationContext(), QuizLevelSelect.class);
startActivity(i);
finish();
}
}
});
}
All of this works fine except when the user returns to the level select activity, the level 2 button does not become enabled, however if I press back on my phone and then go back into the level select activity it does become enabled. I am assuming this is because when the second activity returns the user to the level select activity the onResume() method is not being run, I have also tried onStart() and onRestart() but neither worked. I know it has something to do with the life cycle of my activities but I dont understand why I have to back out of the activity and then go back into it for the onResume method to run, I thought it ran everytime regardless.
Related
I want to let users choose background colors with animation in BackgroundActivity and saving that changed background color into MainActivity.
When a user clicks backgroundChange button on MainActivity, it moves to BackgroundActivity. Then there are a few different colors to choose. After a user click Save button after choosing color on BackgroundActivity, it is going back to MainAcitivity. My problem is I don't know how to save that changed background color from BackgroundAcivity to MainAcivity.
As a beginner, I cannot understand well how to use SharedPreferences.
I checked several videos and searching many questions for hours about it, but still, I cannot figure out how to use SharedPreferences correctly on my own code.
BackgroundAcivity is really long that I will only put the first part. Could you tell me how to save this background change?
MainActivity
public class MainActivity extends AppCompatActivity {
Button backgroundChange;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
backgroundChange = findViewById(R.id.backgroundChange);
backgroundChange.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, BackgroundActivity.class);
startActivity(intent);
}
});
}
}
BackgroundActivity
public class BackgroundActivity extends AppCompatActivity {
Button btn_blue, btn_purple, btn_orange, btn_save;
View holderBg, dynamicBg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_background);
btn_save = findViewById(R.id.btn_save);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(BackgroundActivity.this, MainActivity.class);
startActivity(intent);
}
});
btn_blue = findViewById(R.id.btn_blue);
btn_purple = findViewById(R.id.btn_purple);
btn_orange = findViewById(R.id.btn_orange);
holderBg = findViewById(R.id.holderBg);
dynamicBg = findViewById(R.id.dynamicBg);
//set the first-time background
holderBg.setBackgroundResource(R.drawable.bg_blue);
holderBg.setScaleY(3);
holderBg.setScaleX(3);
//set the scale of button clicked
btn_blue.setScaleY(1.5f);
btn_blue.setScaleX(1.5f);
btn_blue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//scale animation
btn_blue.animate().translationY(20).scaleX(1.5f).scaleY(1.5f).setDuration(800).start();
//default the scale buttons
btn_purple.animate().translationY(0).scaleX(1).scaleY(1).setDuration(350).start();
btn_orange.animate().translationY(0).scaleX(1).scaleY(1).setDuration(350).start();
//change the background
dynamicBg.animate().scaleX(3).scaleY(3).setDuration(800).start();
dynamicBg.setBackgroundResource(R.drawable.bg_blue);
//change color of button
btn_save.setTextColor(Color.parseColor("#3498db"));
//timer for change the holderbg
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
holderBg.setScaleX(3);
holderBg.setScaleY(3);
holderBg.setBackgroundResource(R.drawable.bg_blue);
dynamicBg.setScaleX(0);
dynamicBg.setScaleY(0);
}
}, 850);
}
});
}
}
You can use a bundle to transfer your data across Activity.
Saving data
Intent intent = new Intent(context, YourActivity.class);
intent.putExtra(KEY, "your value here");
startActivity(intent);
Then to retrieve data.
Intent intent = getIntent();
if (intent != null ) { //Null Checking
String strData= intent.getStringExtra(KEY);
// do your work with `strData`
}
I've been trying to find out the back navigation button to lead to another activity.
Every time when I pressed the back button, it goes to the previous activity which is not what I want. I would like to set the back button that goes to another activity I want, instead of previous one.
For example, I have Activity 1, 2 and 3. I was in Activity 2 and just moved to Activity 3. But when I press the back button, it goes automatically to the previous activity which is Activity 2. I want to make it to Activity 1 and not Activity 2. Can anyone suggest me a solution please?
You can make the button to go to a specific activity, instead of having the default behavior that you described.
It can be something like this:
#Override
public void onClick(View v) {
Intent intent = new Intent(Activity2.this, Activity3.class);
intent.putExtra("variable", information); //this is optional, but can be useful if you need to send a specific info to the next activity
startActivity(intent);
}
Activity 2 is parliamonar, and Activity 3 is federalparliamentary. I replaced parliamonar with Activity 1, but it still didn't solve the problem.
public class federalparliamentary extends AppCompatActivity {
Button federal;
private Object parliamonar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_federalparliamentary);
federal = findViewById(R.id.back160);
federal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reserve = new Intent(getApplicationContext(), parliamonar.class);
startActivity(reserve);
}
});
federal = findViewById(R.id.next164);
federal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reserve = new Intent(getApplicationContext(), sar.class);
startActivity(reserve);
}
});
}
public void onClick(View V) {
Intent back = new Intent((Context) parliamonar, federalparliamentary.class);
startActivity(back);
}
}
public class federalparliamentary extends AppCompatActivity {
Button federal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_federalparliamentary);
federal = findViewById(R.id.back160);
federal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reserve = new Intent(getApplicationContext(), parliamonar.class);
startActivity(reserve);
}
});
federal = findViewById(R.id.next164);
federal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reserve = new Intent(getApplicationContext(), sar.class);
startActivity(reserve);
}
});
}
public void Onclick(View v) {
Intent intent = new Intent(federalparliamentary.this, politicalsystem.class);
startActivity(intent);
}
}
Activity 1 is "politicalsystem".
I added with #Override method, but it says that I have to remove the method, so I added outside, then it says that I have to extract interface, so clicked on it, then it gave me a bunch of list. So I chose onClick(v:View ):void, but it still didn't solve the issue. I tried in another way without #Override, but nothing changed when I tested my app. I also tried inside onCreate method which did not modified the navigation as I desired.
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
Further to my previous post, I now want to invoke a child activity from the main activity a number of times. In my real project (as opposed to the noddy test below), when the child activity is invoked, its header displays, "Enter first data set" then invites the user to enter some data. This data is actually stored in a common class rather than being returned to the main activity. Then the child needs to be called again with a new prompt "Enter second data set", and the same thing happens.
What I cannot work out is how to do this. If I include two calls to the child, every time, only the second call appears to happen, the prompt appearing in the child activity being "Enter second data set" every time. This startActivityForResult() method is I believe, designed to be used when you want to call an activity and wait for the result (which you do with an onActivityResult() do you not), but it does not wait.
How on earth do I do this? Sample code follows.
Thank you to anyone who can clearly explain where I'm going wrong and what the right code should be.
MainActivity code extract
#Override
public void onResume(){
super.onResume();
TextView maintop = (TextView)findViewById(R.id.maintop);
maintop.setText(Common.mess1);
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mainbutton = (Button)findViewById(R.id.mainbutton);
mainbutton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent intent1 = new Intent(MainActivity.this,Child.class);
intent1.putExtra("Prompt", "Enter first data set");
startActivityForResult(intent1,1);
onActivityResult(1,1,intent1);
}
});
mainbutton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent intent2 = new Intent(MainActivity.this,Child.class);
intent2.putExtra("Prompt", "Enter second data set");
startActivityForResult(intent2,1);
onActivityResult(1,1,intent2);
}
});
}
You can only have one click listener in the button, so when you call set for the 2nd time it replaces the listener.
What you need to do is set the click listener for the enter first data, don't call to onActivityResult(1,1,intent1) that's not how you do it, you need override the method, and in onActivityResult call the 2nd.
Something like this:
static final int FIRST_INTENT = 1;
static final int SECOND_INTENT = 2;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mainbutton = (Button)findViewById(R.id.mainbutton);
mainbutton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent intent1 = new Intent(MainActivity.this,Child.class);
intent1.putExtra("Prompt", "Enter first data set");
startActivityForResult(intent1,FIRST_INTENT);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == FIRST_INTENT) {
if (resultCode == RESULT_OK) {
Intent intent2 = new Intent(MainActivity.this,Child.class);
intent2.putExtra("Prompt", "Enter second data set");
startActivityForResult(intent2,SECOND_INTENT);
}
}
}
And in your child activity
//DO SOMETHING
....
setResult(RESULT_OK)
finish();
}
For more check
[http://developer.android.com/intl/es/training/basics/intents/result.html]
[http://developer.android.com/intl/es/reference/android/app/Activity.html#setResult%28int%29]
Hi so even though I have seen a couple of topics about linking activities or returning I can not get my return back to activity to work. I abit of back ground the the app when the user gets an answer wrong or runs out of time it goes to game over taking the score across with it and displaying it on the game over, here's the working code for that if it helps solve my issue:
Main Class:
public void fail(){
{
Intent myIntent = new Intent(MainActivity.this,gameover.class);
myIntent.putExtra("number", score);
MainActivity.this.startActivity(myIntent);
finish();
}
gameover class:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameover);
re_run = (Button) findViewById(R.id.retry);
EndScore = (TextView) findViewById(R.id.show);
int getVal;
getVal = getIntent().getExtras().getInt("number");
String s = String.valueOf( getVal );
EndScore.setText(s);
}
Now the reason I shared the above working code because I have the feeling the intent that takes the user and score to the gameover screen, is messing with the retry/return code as shown below:
private void setButtonOnClickListeners(){
re_run.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Intent retry = new Intent(getApplicationContext(),
MainActivity.class);
startActivity(retry);
}
});
}
From what I can find from those topics these seems to be the correct method. but when the code is run the re_run button does nothing. Any help?
You use "setButtonOnClickListeners()" to implement setOnClickListener and so override the onClick. But when did you call setButtonOnClickListeners?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameover); re_run = (Button)
findViewById(R.id.retry);
EndScore = (TextView) findViewById(R.id.show);
int getVal;
getVal = getIntent().getExtras().getInt("number");
String s = String.valueOf( getVal );
EndScore.setText(s);
setButtonOnClickListeners();
}
You can maybe check that your OnClick is working correctly adding a log line in LogCat. Log.d("GameOver", "Retry onclick ok");
You are finding a view before it was inflated (R.id.retry).
Change the sequence of commands to:
super.onCreate(savedInstanceState);
setContentView(R.layout.gameover);
re_run = (Button) findViewById(R.id.retry);
Also try changing the intent to:
Intent retry = new Intent(GameOver.this, MainActivity.class);
retry.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
I personally used startActivityForResult(Intent) to start the game over screen, and once the player inputted his name or pressed something or quit the activity with Back, then it returned a value to onActivityResult(..) in which I called finish().
EDIT:
Game ends, so I started activity using
Intent i = new Intent();
i.putExtra("Score", scoreCount);
i.setClass(context, HighScoreInputActivity.class);
context.startActivityForResult(i, 0);
Then when you insert the scores and stuff, you close the game screen in GameActivity with
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
this.finish();
}