Making a Continue button work using SharedPreferences - java

I'm quite a beginner as far as java and android studio is concerned. So, I'm building a simple riddle game. Each activity consists of a question and a Text Field to place your answer - right answers get you to the next one etc.
The main activity has two buttons: a New Game one (which works fine) and a Continue one - the one that troubles me. Obviously, what I want is that, when pressed, it takes you to the last question you reached. I'm aware that SharedPreferences must be used in order to get this done, my problem is that I fail to think of a piece of code that works (every tutorial I've seen and read was about keeping names - high scores etc).
Here's my code: it may need some polishing, but I'm still learning.
Main Activity java
public class MainMenu extends AppCompatActivity {
private Button mStartInterrogationButton;
private VideoView mLogoprwto;
private Button mContinueButton; //This one is the one I'm asking about
#Override
public void onResume() {
super.onResume();
setContentView(R.layout.activity_main_menu);
mLogoprwto = (VideoView) findViewById(R.id.logoprwto);
mLogoprwto.setVideoPath("android.resource://my.path/"+R.raw.teloslogo);
mLogoprwto.start();
mLogoprwto.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mLogoprwto.start();
}
});
mStartInterrogationButton = (Button)findViewById(R.id.StartInterrogationButton);
mStartInterrogationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startGame();
}
});
}
private void startGame () {
Intent intent = new Intent(this, Question01.class);
startActivity(intent);
finish();
}
#Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
Question One activity java (next ones are the same)
public class FirstQuestion extends AppCompatActivity {
private Button mSayAnswer;
private EditText mAnswerbox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first_question);
mAnswerbox = (EditText)findViewById(R.id.Answerbox);
mSayAnswer = (Button)findViewById(R.id.SayAnswer);
mSayAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String answer = mAnswerbox.getText().toString().trim();
if (answer.equalsIgnoreCase("nothing")){
Intent i = new Intent(getApplicationContext(), QuestionTwo.class);
startActivity(i);
}else if (answer.equalsIgnoreCase("black")) {
Intent i = new Intent(getApplicationContext(), QuestionTwo.class);
startActivity(i);
}else {
}
}
});
}
#Override
public void onBackPressed()
{
startActivity(new Intent(getApplicationContext(), MainMenu.class));
finish();
}
};
Thanks in advance, I've been looking for a solution for this for quite a few days.

One way of doing this is to save whether or not the user has answered each question correctly in the SharedPreferences. Then in your MainActivity, send them to the right question depending on how many they've answered correctly. For example:
SharedPreferences.Editor editor = getSharedPreferences("FILENAME", MODE_PRIVATE).edit();
editor.putBoolean("Question01", true);
editor.apply();
Here, FILENAME is the name of the file to write your SharedPreferences to and 'Question01' would be the tag you would save the boolean under for the first question.
SharedPreferences prefs = getSharedPreferences("FILENAME", MODE_PRIVATE);
boolean question01Answered = prefs.getBoolean("Question01", false);
Then you'd call the above to check if Question01 has been answered or not. In your continue button's onClick() method you could do a series of checks to see how far the user has reached and send them to the appropriate Question Activity.
if (!(question01Answered)) {
// question01Answered is false and has not been answered. Send them to the first question.
Intent intent = new Intent(this, Question01.class);
startActivity(intent);
finish();
} else if (!(question02Ansered)) {
// question02Answered is false and has not been answered. Send them to the second question.
Intent intent = new Intent(this, Question02.class);
startActivity(intent);
finish();
} else if (!(question03Answered)) {
// and so on...
}
EDIT: The first section of code can be called anytime you want to save data for a certain question. For example if your user answers the 5th question right then inside the Question05's activity class, you would run the first piece of code right after you confirm that the user answered correctly. Something like:
public class Question05 extends AppCompatActivity {
...
private void checkIfQuestion05IsCorrect() {
if (correct) {
// They answered right, move to the next question.
// But before we do that, let's save the fact that they answered right.
SharedPreferences.Editor editor = getSharedPreferences("FILENAME", MODE_PRIVATE).edit();
editor.putBoolean("Question05", true);
editor.apply();
} else {
// they got it wrong
}
}
}
As for the second piece of code, call it in the MainActivity right before doing all the checks in your continue button's onClick() method, or whenever else you want to know which questions they've answered and which ones they haven't.
SharedPreferences prefs = getSharedPreferences("FILENAME", MODE_PRIVATE);
boolean question01Answered = prefs.getBoolean("Question01", false);
boolean question02Answered = prefs.getBoolean("Question02", false);
boolean question03Answered = prefs.getBoolean("Question03", false);
// and so on ...
if (!(question01Answered)) {
// question01Answered is false and has not been answered. Send them to the first question.
Intent intent = new Intent(this, Question01.class);
startActivity(intent);
finish();
} else if (!(question02Ansered)) {
// question02Answered is false and has not been answered. Send them to the second question.
Intent intent = new Intent(this, Question02.class);
startActivity(intent);
finish();
} else if (!(question03Answered)) {
// and so on...
}

Related

How do I pass the number of clicks and reset the count in another activity?

The codes are messy at this point since I've been going back and forth so much. Every time user clicks the yes/no button I want the results of counts the button has been clicked to display in another activity. I also want to reset the number of clicks from the second activity as well. All that's needed in the first activity is the question and the yes/no button. Is this possible? Thanks in advance.
public class MainActivity extends AppCompatActivity {
private static final String TAG = "SurveyActivity";
private static final String YES_INDEX = "yes votes";
private static final String NO_INDEX = "no votes";
Button mYesButton;
Button mNoButton;
Button mResetButton;
TextView mSurveyQuestion;
private int yesVoteCount = 0;
private int noVoteCount = 0;
private int resetVotes = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Use res ID to retrieve inflated objects and assign to variables
mYesButton = findViewById(R.id.yes_button);
mNoButton = findViewById(R.id.no_button);
mResetButton = findViewById(R.id.reset_button);
mSurveyQuestion = findViewById(R.id.survey_question);
mYesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addVote();
}
});
mNoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addVote();
}
});
// Resetting vote count
mResetButton.setOnClickListener(new View.OnClickListener() {
#Override
***Should this supposed to be in the second activity?
}
});
}
private void addVote() {
if (mYesButton.isPressed()) {
yesVoteCount++;
} else if (mNoButton.isPressed()) {
noVoteCount++;
}
}
In your main activity
btnShowResut.setOnClickListener(new View.OnClickListener() {
#Override
// Create intent for going to another activity
Intent intent = new Intent(this, AnotherActivity.class);
// Put counts datas to intent
intent.putExtra("yesCountKey", yesVoteCount);
intent.putExtra("noCountKey", noVoteCount);
// NEW : Go to another activity by calling it instead
// REQUEST_CODE is an integer variable
startActivityForResult(intent, REQUEST_CODE);
}
});
In Another activity, you can retrieve datas in onCreate method like this and send action to clear counts of your main activity.
...
onCreate(...){
...
// Retrieve datas from intent
int yesCount = getIntent().getIntExtra("yesCountKey", 0);
int noCount = getIntent().getIntExtra("noCountKey", 0);
mResetButton.setOnClickListener(new View.OnClickListener() {
#Override
// Send a boolean to main activity for clearing votes
Intent intent = new Intent();
intent.putExtra("resetVotes", true);
setResult(RESULT_OK, intent);
// Close second activity
finish();
}
});
}
Finally in the main activity override this method and clear votes
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == 2000 && resultCode == RESULT_OK){
boolean reset = data.getBooleanExtra("resetVotes", false);
if(reset){
yesVoteCount = 0;
noVoteCount = 0;
}
}
}
As the mentioned above, you can get the counts by using intent extras.
However if you want to reset the counts in in the second activity you might want to start the Activity B as startActivityForResult() see the Android documentation here.
Then when Activity B end you can reset the counts in the call back method onActivityResult().
If you don't want to do it like this the next best way might be to reset the counts onResume() of Activity A so that when you return to the activity you will start with fresh counts. See life cycle documentation here

How to make a scoreboard where the results are calculated in another activity?

I am making an app for a local card game for three players, where there are two activities. One, which is kind of a calculator which calculates the results, and second, where the mentioned results are (to be) displayed. However, as I am not expert with java and programming in general, it is not working.
What now happens in my app is that the result of player one (Tom in my case), is taken from the calculator activity and displayed in the first textView und Player One's name. But when I repeat this operation, with the intent of displaying the second result in the second textView, it just overwrites the first textView. I have already tried the following:
using startActivity
using startActivityForResult
finishing the calculator activity (called MainActivity) with finish()
using Bundle instead of Intent, but
none of these did work though.
In the calculator activity (called MainActivity):
final Button zapsat = (Button)findViewById(R.id.button3);
zapsat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final TextView tomVysledek = (TextView)findViewById(R.id.textView_tom2);
//final TextView tataVysledek = (TextView)findViewById(R.id.textView_tom3);
//final TextView kubaVysledek = (TextView)findViewById(R.id.textView_tom4);
Intent intent = new Intent(MainActivity.this, Results.class);
intent.putExtra("tomVysledek", tomVysledek.getText().toString());
startActivity(intent);
}
});
In onCreate of the Results activity (where I want to display the results):
TextView textView_tomV1 = (TextView) findViewById(R.id.textView_tomV1);
TextView textView_tomV2 = (TextView) findViewById(R.id.textView_tomV2);
.
.
.
TextView textView_tomV5 = (TextView) findViewById(R.id.textView_tomV5);
int tomZapis = 0;
Intent intent = getIntent();
try {
tomZapis = Integer.parseInt(intent.getStringExtra("tomVysledek"));
} catch (Exception e){}
String tomZapis_tv = Integer.toString(tomZapis);
if (textView_tomV1.getText().equals("0")) {
textView_tomV1.setText(tomZapis_tv);
} else if (textView_tomV2.getText().equals("0")){
textView_tomV2.setText(tomZapis_tv);
} else if (textView_tomV3.getText().equals("0")){
textView_tomV3.setText(tomZapis_tv);
} else if (textView_tomV4.getText().equals("0")) {
textView_tomV4.setText(tomZapis_tv);
} else if (textView_tomV5.getText().equals("0")) {
textView_tomV5.setText(tomZapis_tv);
} else {
Toast.makeText(Results.this, "Už není místo :(", Toast.LENGTH_LONG).show();
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intentres = new Intent(Results.this, MainActivity.class);
startActivityForResult(intentres, 1);
}
});
As I said, it always displays the result in the first textView (textView_tomV1), instead of finding the first empty textView and filling it with the variable. I believe that is because the startActivity actually restarts the activity, but I am not sure about that, and even if it was the case, I wouldn't know what to do with it, either.
I am not sure if it will solve your problem but when you write this
else if (textView_tomV2.getText().equals("0"))
you compare "Editable" with a String...
You should add toString() like so
textView_tomV2.getText().toString().equals("0")
and it will compare Strings

how I process NullPointerException on android? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I want
when I click the button.
showing Connectingreceiver.class
but NullpointerException.
I think I not well use context.
advice for me
thanks android senior developer.
private OnClickListener mConnectOnClick = new OnClickListener() {
Context context= ConfiguredNetworkContent.this;
#Override
public void onClick(View v) {
Intent intent = new Intent(context,Connectingreceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
public class Connectingreceiver extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.connecting_dialog);
}
}
Check this :
private View.OnClickListener mConnectOnClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), Connectingreceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
v.getContext().startActivity(intent);
}
Update :
Straight forward explanation is you need a Context to start a Activity. And in Onclick() there is a passing View in which Context already existed. So, I only used it to start activity.
where this context? Context context;
fix Context context = getApplicationContext;
Try this
// Add this line after Main class
Button yourButton;
In below code don't forget to edit "yourButtonIDfromXML"
// Add below code in OnCreate method after setContentView
Button yourButton = (Button) findViewById(R.id.yourButtonIDfromXML);
yourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ConfiguredNetworkContent.this, Connectingreceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
});
The "context" - is null. You need to do null check s to avoid Null Pointer Crash. It is the easiest exception to resolve.
If your are doing OnClick event in
Activity:- Use these lines.
public static void startReceiver() {
Intent intent = new Intent(YourActivityName.this, Connectingreceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
Fragment :-
Use these lines
private OnClickListener mConnectOnClick = new OnClickListener() {
Context context;
#Override
public void onClick(View v) {
if(getActivity() != null) {
startActivity(getActivity());
}
}
And use same the startActivity() method
Also, rename your startActivity method. It is an inbuilt android method.
Prefer using camel cases for your class name. Connectingreceiver --> ConnectingReceiver.
I think I not well use context.
You have to use it if needed, But as per your codes there is no initialization of context.
First initialize your context either with ApplicationContext or ActivityContext like here
Context context = YourActivity.this;
then you can use startActivity(intent);. You don't need to write context.startActivity(intent);. only startActivity will be enough at all.
UPDATE :
Do not pass any context their just simply do
customstartActivity();
And inside customstartActivity() method
public static void customstartActivity (){
// Intent intent = new Intent(yourActivity.this, Connectingreceiver.class);
// Intent intent = new Intent(ContextWrapper.getBaseContext(), Connectingreceiver.class);
Intent intent = new Intent(getApplicationContext(), Connectingreceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}

Android back button freezes when using onkeydown method or overriding onbackbuttonpressed

public boolean onKeyDown(int keyCode, KeyEvent event){
if (isSub2&&keyCode == KeyEvent.KEYCODE_BACK) {
Intent intent = new Intent(ctxx, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
isReturning = true;
return false;
}
else {
return super.onKeyDown(keyCode, event);
}
}
}
There are two Activities Main--Sub2.
When you push a button in Main you can go to Sub2.
This code is in Sub2. I want to use back button on the bottom to make the MainActivity put on the top of stack not killing Sub2.
When I run it on the phone it works all right at first,
but after few more times of going back in Sub2 and going to Sub2 again
the back button stops working.
I don't know what is making the back button freeze.. any ideas?
ps) i've tried using handlers inside the method and overriding onBackButtonPressed() instead of using onKeyDown..
but no difference at all..
Not sure why your button freezes. It would be helpful to see what you are doing in the main activity. Here's an example that works for me and does not freeze:
You can put this in the main activity:
#Override
protected void onStart() {
super.onStart();
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SubActivity.class);
//****** Uncomment the following line if you want to re-use the subactivity instead of launching a new one
//intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
});
}
And this in the sub-activity:
#Override
public void onBackPressed() {
//super.onBackPressed();
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}

android onClick not firing?

EDIT: onClick is working properly now. The issue was that the button was trying to fire the onClick from the Parent class. now that is fixed. Of course that means a new issue is happening, that is the onActivityResult is never getting called.
So I am not really sure what the hell is going on, when I hit the button nothing happens, nothing in logcat, nothing, as if there is not code, but I am pretty sure this is written correctly, any thoughts?
public class myClass extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.store_selector);
Button getStore = (Button)findViewById(R.id.getStore);
getStore.setOnClickListener(buttonGetStoreOnClickListener);
}
Button.OnClickListener buttonGetStoreOnClickListener
= new Button.OnClickListener(){
public void onClick(View arg0) {
Intent intent = new Intent("com.blah.Blah.client.android.SCAN");
intent.setPackage("com.blah.Blah");
intent.putExtra("com.blah.Blah.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
};
};
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == 0)
{
if (resultCode == RESULT_OK)
{
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
Log.i("debug tag", "contents: "+contents+" format: "+format);
Intent myIntent = new Intent(this, Ads.class);
myIntent.putExtra("key", contents);
startActivity(myIntent);
setContentView(R.layout.activity_ads);
// Handle successful scan
}
else if (resultCode == RESULT_CANCELED)
{
// Handle cancel
Log.i("xZing", "Cancelled");
}
}
}
};
This is the class you need to import:
import android.view.View.OnClickListener;
And this is the method you should have:
OnClickListener onButtonListener = new OnClickListener() {
#Override
public void onClick(View v) {
// Your code here
}
};
Test it and let me know if it worked.
Regards
Are you sure you got the right button with Button getStore = (Button)findViewById(R.id.getStore); ?
If yes, then it can be something that sometimes happens to me sometimes.
When this happens, my logcat doesn't show anything. What I do to solve this, is to open the Devices view (Window, show view, other, Android, Devices) and select my device. Then when I look at the logcat again, everything's there.

Categories

Resources