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.
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`
}
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 have an activity that loads text views into it. I add a click listener to these text views and want them to open up an activity with different values based on what I click. It ends up that no matter which I click, the same results show up, and more precisely, I use the same info in creating it - which I don't want to do.
public void setTextToTextView (JSONArray jsonArray)
{
RelativeLayout layout = (RelativeLayout) findViewById(R.id.activity_main);
String s = "";
for (int i = 0; i < jsonArray.length(); i++) {
TextView info = new TextView(this); //actually really confused as to what the context I'm setting is - why this? Just saw other people do it like so
JSONObject json = null;
try {
json = jsonArray.getJSONObject(i);
s = s + "ID : " + json.getString("Id") + " Parent: " + json.getString("Parent") +
" Content: " + json.getString("Content") + " User: " + json.getString("User") +
" Timestamp: " + json.getString("Timestamp") + "\n\n";
} catch (JSONException e) {
e.printStackTrace();
}
info.setText(s);
try {
info.setId(Integer.parseInt(json.getString("Id")));
} catch (JSONException e) {
e.printStackTrace();
}
info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this,
NewActivity.class);
myIntent.putExtra("key", v.getId()); //this is always the same
startActivity(myIntent);
}
});
layout.addView(info);
}
}
Using two text views, this results in the ID of the second view to always be the value of the key,value pair in the activity I start. I'm not sure what I'm doing wrong at the moment. I believe my problem is in this section, as I can't see where else it might come from.
Any help or suggestions on my code in general would be welcomed. Thank you.
This still isn't solved, so I'll focus on the problem area:
info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this,
NewActivity.class);
myIntent.putExtra("key", v.getId()); //this is always the same
startActivity(myIntent);
}
});
No matter what changes I make, this will always give me the exact same v.getId/v.getTag - every time.
I create a new project with your code but the result is correct just as what you hope.Are you sure that your third TextView does not cover the previous ones?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout layout = (LinearLayout)findViewById(R.id.activity_main);
int [] a = {1,2};
String [] s = {"textView1","textView2"};
for(int i =0; i <a.length; i++)
{
TextView info = new TextView(this); //actually really confused as to what the context I'm setting is - why this? Just saw other people do it like so
info.setText(s[i]);
info.setId(a[i]);
info.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(),
"clicked:"+v.getId(),Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(MainActivity.this,
NewActivity.class);
myIntent.putExtra("key", v.getId()); //this is always the same
startActivity(myIntent);
}
});
layout.addView(info);
}
The gif:
As a first step, I would move the OnclickListener to outsdie the loop, as it always does the same thing:
View.OnClickListener view_ocl = new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent myIntent = new Intent(MainActivity.this, NewActivity.class);
myIntent.putExtra("key", v.getId()); //this is always the same
startActivity(myIntent);
}};
for(int i =0; i <jsonArray.length(); i++)
{
// ... as before
info.setOnClickListener(view_ocl);
layout.addView(info);
}
As you do, you need to explicitly set the Id, or in some way put an identifier in the view so that your onClick code (which is the same for each View), knows which View has been clicked. At the moment you are reliant on whatever arbitrary Id the system gives to the view.
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.
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;
}*/
}
});
}