I have an activity called CForm. I would like to call CGForm for result. After i get the result start another activity. The problem is that when i start the details_click method , it executes the CGFORM, but doesn't waits for setting the result in the form, it jumps to the CDFORM.
here is the code for CFORM:
////////////////////////////CForm/////////////////////////
public boolean details_click()
{
if(listview.getCheckedItemPosition()>=0)
{
ArrayList<ComandaClass> listcompos = CClass.C();
int gestiuneId = 0;
if ((configurare.bAlCom) && (listcompos.size() == 0))
{
StocClass.setComandaContextForDB(this);
listGest = StocClass.Gestiuni_Get();
if (listGest.size() > 1)
{
Intent intent = new Intent();
intent.setClass(CForm.this,CGForm.class);
startActivityForResult(intent,GET_CODE);//here i would like to get back the result from CGForm
dGeid=getGIdResult;
}
}
boolean tof = true;
if ((configurare.bGCom) && (gestiuneId == -1))
tof = false;
if (tof)
{
dCid=listCom.get(listview.getCheckedItemPosition()).getCId();
dClid=listCom.get(listview.getCheckedItemPosition()).getClId();
dF=listCom.get(listview.getCheckedItemPosition()).getF();
Intent intent = new Intent();
intent.setClass(CForm.this,CDForm.class);
startActivity(intent);
}
return true;
}
else
{
Toast.makeText(this, "X", 5000).show();
return false;
}
}
public static int getGIdResult=-1;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == GET_CODE)
{
if (resultCode == RESULT_OK)
{
getGIdResult=data.getIntExtra("GIdResult",-1);
}
else
{
getGIdResult=-1;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
CGFORM code:
////////////////////CGForm//////////////////
public class CGForm extends Activity
{
public static ArrayList<StocClass> listG=null;
public static int gid;
ListView listview=null;
Button btnOK=null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.comenzigestiuni);
Locale locale = new Locale("en");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics());
listview=(ListView)findViewById(R.id.listViewDG);
listG = CForm.listGest;
CG_Load();
}//oncreate
private void CG_Load()
{
//..adding data to listview
btnOK=(Button)findViewById(R.id.menuItemOk);
btnOK.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
if (listview.getCheckedItemPosition() >= 0)
{
gestiuneid = listG.get(listview.getCheckedItemPosition()).getGId();
Intent intent = new Intent();
intent.putExtra("GIdResult", gestiuneid);
setResult(RESULT_OK, intent);
finish();
}
}
});
}//CG_Load
#Override
protected void onStop()
{
gestiuneid=-1;
Intent intent = new Intent();
intent.putExtra("GIdResult", gestiuneid);
setResult(RESULT_OK, intent);
super.onStop();
}
}
thanks advanced !
Neither startActivity() nor startActivityForResult() are blocking calls. Anything that is supposed to be done after you receive the result needs to move to your onActivityResult() method.
Related
i m making a quiz app , in my quizzActivity where qestions load i used countDowntimer so when this countdown timer is finished i m displaying alert dialog of Game over with sound , everything working fine
Problem is when my quiz is finished , i am also getting the Gameover sound in my result activity , and in MainActivity.
my QuizzActvity code
ActivityQuizBinding binding;
ArrayList<Questions> qestions;
Questions question;
CountDownTimer timer;
FirebaseFirestore database;
int correctAnswer = 0;
MediaPlayer mMediaPlayer;
int index = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityQuizBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
qestions = new ArrayList<>();
database = FirebaseFirestore.getInstance();
final String cateGoryID = getIntent().getStringExtra("categoryID");
database.collection("categories")
.document(cateGoryID)
.collection("questions")
.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for (DocumentSnapshot snapshot : queryDocumentSnapshots) {
Questions questions = snapshot.toObject(Questions.class);
qestions.add(questions);
}
Collections.shuffle(qestions);
setNextQestions();
}
});
resetTimer();
}
void resetTimer() {
timer = new CountDownTimer(30000, 1000) {
#Override
public void onTick(long l) {
binding.timer.setText(String.valueOf(l / 1000));
}
#Override
public void onFinish() {
new AlertDialog.Builder(QuizActivity.this)
.setIcon(R.drawable.sad)
.setTitle("Oops Game Over!")
.setCancelable(false)
.setMessage(" Please Try Again ")
.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
Intent in = new Intent(QuizActivity.this, MainActivity.class);
startActivity(in);
finish();
}
}).create().show();
mMediaPlayer = new MediaPlayer();
mMediaPlayer = MediaPlayer.create(QuizActivity.this, R.raw.wrong);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setLooping(false);
mMediaPlayer.start();
}
};
}
public void CheckAnwer(TextView textView) {
String selectAnswer = textView.getText().toString();
if (selectAnswer.equals(question.getAnswer())) {
correctAnswer++;
textView.setBackground(getResources().getDrawable(R.drawable.option_right));
} else {
showAnswer();
textView.setBackground(getResources().getDrawable(R.drawable.option_wrong));
}
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(QuizActivity.this)
.setIcon(R.drawable.ic_baseline_person_24)
.setMessage("Are you sure want to Quit Game")
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent in = new Intent(QuizActivity.this, MainActivity.class);
startActivity(in);
finish();
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).create().show();
}
public void setNextQestions() {
if (timer != null) {
timer.cancel();
}
timer.start();
if (index < qestions.size()) {
binding.qestioncounter.setText(String.format("%d/%d", (index + 1), qestions.size()));
question = qestions.get(index);
binding.qestions.setText(question.getQestion());
binding.option1.setText(question.getOption1());
binding.option2.setText(question.getOption2());
binding.option3.setText(question.getOption3());
binding.option4.setText(question.getOption4());
index++;
} else {
reset();
Toast.makeText(this, "Quiz Finsished", Toast.LENGTH_SHORT).show();
Intent in = new Intent(QuizActivity.this, ResultActivity.class);
in.putExtra("correct_answer", correctAnswer);
in.putExtra("total", qestions.size());
startActivity(in);
}
}
void reset() {
binding.option1.setBackground(getResources().getDrawable(R.drawable.option_unselected));
binding.option2.setBackground(getResources().getDrawable(R.drawable.option_unselected));
binding.option3.setBackground(getResources().getDrawable(R.drawable.option_unselected));
binding.option4.setBackground(getResources().getDrawable(R.drawable.option_unselected));
}
void showAnswer() {
if (question.getAnswer().equals(binding.option1.getText().toString()))
binding.option1.setBackground(getResources().getDrawable(R.drawable.option_right));
else if (question.getAnswer().equals(binding.option2.getText().toString()))
binding.option2.setBackground(getResources().getDrawable(R.drawable.option_right));
else if (question.getAnswer().equals(binding.option3.getText().toString()))
binding.option3.setBackground(getResources().getDrawable(R.drawable.option_right));
else if (question.getAnswer().equals(binding.option4.getText().toString()))
binding.option4.setBackground(getResources().getDrawable(R.drawable.option_right));
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.option_1:
case R.id.option_2:
case R.id.option_3:
case R.id.option_4:
if (timer != null) {
timer.cancel();
}
TextView selected = (TextView) view;
CheckAnwer(selected);
break;
case R.id.next_btn:
reset();
setNextQestions();
break;
}
}
}
You have to stop the MediaPlayer before switching to another activity. You may use the OnActivityResult result for stopping Mediaplayer while switching between activities.
Here is the sample code:
public static final int REQUEST_CODE = 1;
Intent in = new Intent(QuizActivity.this, MainActivity.class);
startActivityForResult(in, REQUEST_CODE);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
mMediaPlayer.stop()
}
} catch (Exception ex) {
}
}
Also, make sure that you cancel the CountDownTimer before switching to another activity.
Visitor Details
I have a dialog in Visitor Activity. When I click on the icon, it will redirect to Camera Activity. Then when click Confirm button in Camera Activity, it will send the intent back to previous Activity which is Visitor Activity. The problem is how should I pass the intent result from Camera Activity back to the dialog in Visitor Activity. The intent data should be placed in the Pass No Edit Text. I'm using material dialog without any Fragment that attached to that dialog. It all placed in Visitor Activity. Can someone please help me? Thank you!
private void checkin()
{
final MaterialDialog dialog = new MaterialDialog.Builder(VisitorDetailActivity.this)
.customView(R.layout.sample,false)
.build();
View view = dialog.getCustomView();
final EditText etPassNo = (EditText) view.findViewById(R.id.etPassNo);
final EditText etVehicleNo = (EditText) view.findViewById(R.id.etVehicleNo);
final ImageView ivScanCode = (ImageView) view.findViewById(R.id.ivScanCode);
final TextView tvCancel = (TextView) view.findViewById(R.id.tvCancel);
final TextView tvSubmit = (TextView) view.findViewById(R.id.tvSubmit);
etVehicleNo.setText(model.getFldVehicleNo());
if(barCode != null)
{
etPassNo.setText(barCode);
}
ivScanCode.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Toast.makeText(VisitorDetailActivity.this, "Bar code scanner", Toast.LENGTH_SHORT).show();
Intent i = new Intent(VisitorDetailActivity.this, ScanCodeActivity.class);
startActivityForResult(i,97);
}
});
tvCancel.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
dialog.dismiss();
}
});
tvSubmit.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(etPassNo.getText().toString().trim().isEmpty())
{
Toast.makeText(VisitorDetailActivity.this, "Pass No is required", Toast.LENGTH_SHORT).show();
return;
}
if(selImage == null)
{
proceedCheckin(etPassNo.getText().toString(), etVehicleNo.getText().toString());
}
else
{
proceedCheckinImage(etPassNo.getText().toString(), etVehicleNo.getText().toString());
}
}
});
dialog.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 98 && resultCode == RESULT_OK)
{
selImage = data.getStringExtra("photo");
Glide.with(VisitorDetailActivity.this).load(selImage).into(iDrivingLicense);
}
else if (requestCode == 99 && resultCode == RESULT_OK)
{
selImage = data.getStringExtra("photo");
Glide.with(VisitorDetailActivity.this).load(selImage).into(iDrivingLicense);
}
else if(requestCode == 97 && resultCode == RESULT_OK)
{
barCode = data.getStringExtra("barCode");
}
}
First you need to take the view object globally out of that checkIn methoed
View view;
view = dialog.getCustomView();
final EditText etPassNo = (EditText) view.findViewById(R.id.etPassNo);
Now under your onActivityResult method, as i can see you already getting the barcode there, so just initiate the EditText object again on that same simply set the data in it.
barCode = data.getStringExtra("barCode");
EditText etPassNo = (EditText) view.findViewById(R.id.etPassNo);
etPassNo.setText(barCode);
Let me know if that works.
you can do it using interface
public interface OnBarcodeSelect{
void onBarcodeSelected(String barcode);}
OnBarcodeSelect onBarcodeSelect;
private void checkin()
{
final MaterialDialog dialog = new MaterialDialog.Builder(VisitorDetailActivity.this)
.customView(R.layout.sample,false)
.build();
View view = dialog.getCustomView();
final EditText etPassNo = (EditText) view.findViewById(R.id.etPassNo);
final EditText etVehicleNo = (EditText) view.findViewById(R.id.etVehicleNo);
final ImageView ivScanCode = (ImageView) view.findViewById(R.id.ivScanCode);
final TextView tvCancel = (TextView) view.findViewById(R.id.tvCancel);
final TextView tvSubmit = (TextView) view.findViewById(R.id.tvSubmit);
etVehicleNo.setText(model.getFldVehicleNo());
if(barCode != null)
{
etPassNo.setText(barCode);
}
ivScanCode.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Toast.makeText(VisitorDetailActivity.this, "Bar code scanner", Toast.LENGTH_SHORT).show();
Intent i = new Intent(VisitorDetailActivity.this, ScanCodeActivity.class);
onBarcodeSelect = new OnBarcodeSelect() {
#Override
public void onBarcodeSelected(String barcode) {
//handle barcode here
etPassNo.setText(barcode);
}
}
startActivityForResult(i,97);
}
});
tvCancel.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
dialog.dismiss();
}
});
tvSubmit.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(etPassNo.getText().toString().trim().isEmpty())
{
Toast.makeText(VisitorDetailActivity.this, "Pass No is required", Toast.LENGTH_SHORT).show();
return;
}
if(selImage == null)
{
proceedCheckin(etPassNo.getText().toString(), etVehicleNo.getText().toString());
}
else
{
proceedCheckinImage(etPassNo.getText().toString(), etVehicleNo.getText().toString());
}
}
});
dialog.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 98 && resultCode == RESULT_OK)
{
selImage = data.getStringExtra("photo");
Glide.with(VisitorDetailActivity.this).load(selImage).into(iDrivingLicense);
}
else if (requestCode == 99 && resultCode == RESULT_OK)
{
selImage = data.getStringExtra("photo");
Glide.with(VisitorDetailActivity.this).load(selImage).into(iDrivingLicense);
}
else if(requestCode == 97 && resultCode == RESULT_OK)
{
barCode = data.getStringExtra("barCode");
if(onBarcodeSelect != null){
onBarcodeSelect.onBarcodeSelected(barCode);
}
}
}
I have 3 different buttons: Upload Profile Picture, Upload Photo ID and Upload Criminal Record Photo, but after I call the openFileChooser() method which I created, I don't know how exactly I have to handle that to get 3 different URls.
I mean I did this
public class SignupCarrier extends AppCompatActivity {
EditText editfullname, editemail, editpassword, editconfirmpassword, editaddress, editcity, editstate, editzipcode, editcountry, editphone, editcardnumber, editexpiredate, editcvc;
Button upProfile, upIDPhoto, upCriminalRecord;
private Uri mProfilePic, mIdPhoto,mCriminalRecord;
FirebaseAuth mFirebaseAuth;
private StorageReference mStorageRef;
private StorageTask mUploadTask;
private static final int PICK_IMAGE_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup_carrier);
mFirebaseAuth = FirebaseAuth.getInstance();
upProfile = (Button) findViewById(R.id.profilePic);
upIDPhoto = (Button) findViewById(R.id.idphotoPic);
upCriminalRecord = (Button) findViewById(R.id.criminalRecord);
mStorageRef = FirebaseStorage.getInstance().getReference("carriersPictures");
upProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
upIDPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
upCriminalRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null)
{
mProfilePic = data.getData();
}
}
}
But this would probably work only for upProfile Button, how can I modify the onActivityResult to get for each buttons the URLs?
Thank you! I'm new to Android.
Add Uri as parameter to your openFileChooser() method.
private void openFileChooser(Uri uri)
and call it like this:
upProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser(mProfilePic);
}
});
Update your openFileChooser() method to this:
private void openFileChooser(Uri uri) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
if (uri == mProfilePic) {
startActivityForResult(intent, PICK_IMAGE_REQUEST);
} else if (uri == mIdPhoto) {
startActivityForResult(intent, PICK_IMAGE_REQUEST_ID);
} else if (uri == mCriminalRecord) {
startActivityForResult(intent, PICK_IMAGE_REQUEST_CR);
}
}
You need to declare these constants: PICK_IMAGE_REQUEST_ID, PICK_IMAGE_REQUEST_CR
And in your onActivityResult() method check the requestCode to handle each case
I have 3 classes: MainActivity, HighScoreActivity, and GameScreenActivity. I want to go to the GameScreenActivity via MainActivity, and then when the game has finished, pass the score to the HighScoreActivity. Everything gets passed to the GameScreenActivity successfully, but it doesn't go to the onActivityResult in HighScoreActivity.
I believe it's because of the MainActivity having the startActivityForResult, so the GameScreenActivity's finishQuiz() is expecting to return its data to the MainActivity. How would I pass the GameScreenActivity's data to the HighScoreActivity?
MainActivity()
MainActivity(){
...
private void startQuiz() {
String difficulty = spinnerDifficulty.getSelectedItem().toString();
Intent intent = new Intent(getBaseContext(), GameScreenActivity.class);
intent.putExtra(EXTRA_DIFFICULTY, difficulty);
startActivityForResult(intent, REQUEST_CODE_QUIZ);
}
}
GameScreenActivity()
GameScreenActivity(){
...
private void finishQuiz(){
Intent resultIntent = new Intent(getBaseContext(),
HighScoreActivity.class);
resultIntent.putExtra(EXTRA_SCORE, score);
resultIntent.putExtra(EXTRA_DIFFICULTY, difficulty);
setResult(RESULT_OK, resultIntent);
startActivity(resultIntent);
}
}
HighScoreActivity()
HighScoreActivity(){
...
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_QUIZ){
if (resultCode == RESULT_OK) {
int score = data.getIntExtra(GameScreenActivity.EXTRA_SCORE, 0);
String difficulty = data.getStringExtra(GameScreenActivity.EXTRA_DIFFICULTY);
if (score > highScore10) {
updateHighscore(score, difficulty);
}
}
}
}
}
-------------------------------------------------------------
Trying with the Broadcast method:
GameScreenActivity() with broadcasting methods
GameScreenActivity(){
...
private void finishQuiz(){
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("scoreEvent");
intent.putExtra(EXTRA_DIFFICULTY, difficulty);
intent.putExtra(EXTRA_SCORE, score);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
sendBroadcast(intent);
Intent goToHighScores = new Intent(getBaseContext(), HighScoreActivity.class);
startActivity(goToHighScores);
}
}
HighScoreActivity() with broadcasting methods
HighScoreActivity(){
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_high_score);
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("scoreEvent"));
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_QUIZ){
if (resultCode == RESULT_OK) {
int score = data.getIntExtra(GameScreenActivity.EXTRA_SCORE, 0);
String difficulty = data.getStringExtra(GameScreenActivity.EXTRA_DIFFICULTY);
if (score > highScore10) {
updateHighscore(score, difficulty);
}
}
}
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
#Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
}
Considering HighScoreActivity is running,
You can utilize LocalBroadcastManager to register local broadcastReceiver in HighScoreActivity with IntentFilter. Also, don't forget to unregister in onDestroy()
Now, instead of setResult do sendBroadcast() from GameScreenActivity
Hope this helps. Happy coding!
I have 2 Activity.
FirstActivity with 1 textView and 1 button, and
MainActivity with 4 checkBoxes, 1 textView and 1 button.
First Activity is the first activity which app show to user.
Layouts of my activities
On the FirstActivity i want to check how many checboxes are checked in the textView.
On the MainActivity all working fine, we can select checkboxes and textView show how many is checked. Adittionaly, state of checkboxes and state of textView is save into SharedPreference.
Now i describe my problem, i dont know how to show currently numbers of checked boxes in 1st activity in my app after launch.
I tried to use onActivityResult but i think i do this wrong, and this my button2 with double intent must be also wrong.
What i should fix here and how ?
I paste here code of my 2 Activities:
FirstActivity :
public class FirstActivity extends AppCompatActivity {
private static final String SHARED_PREFS_NAME = "abc";
private Button b1;
private TextView tv2;
private int number;
public static final int REQUEST_CODE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
b1 = (Button)findViewById(R.id.b1);
tv2 = (TextView)findViewById(R.id.tv2) ;
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(FirstActivity.this, MainActivity.class);
startActivityForResult(intent, REQUEST_CODE);
}
});
SharedPreferences preferences = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE);
number = preferences.getInt("NUMBER", 0);
tv2.setText(""+number);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CODE) {
int number = data.getExtras().getInt("number");
tv2.setText(""+number);
number = getIntent().getExtras().getInt("number");
saveNumberToSharedPrefs(number);
}
}
}
private void saveNumberToSharedPrefs(int num){
SharedPreferences preferences = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE); //Create and store this instance in onCreate method of activity, or use it like this.
preferences.edit().putInt("NUMBER", num).apply(); // Use constant value for key
}
}
MainActivity :
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
private int numberOfTrue;
private TextView tv1;
private CheckBox cb1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CheckBox cb2,cb3,cb4;
Button b2;
b2 = (Button)findViewById(R.id.b2);
tv1 = (TextView)findViewById(R.id.tv1);
cb1 = (CheckBox)findViewById(R.id.cb1);
cb1.setChecked(getFromSP("cb1"));
cb1.setOnCheckedChangeListener(this);
cb2 = (CheckBox)findViewById(R.id.cb2);
cb2.setChecked(getFromSP("cb2"));
cb2.setOnCheckedChangeListener(this);
cb3 = (CheckBox)findViewById(R.id.cb3);
cb3.setChecked(getFromSP("cb3"));
cb3.setOnCheckedChangeListener(this);
cb4 = (CheckBox)findViewById(R.id.cb4);
cb4.setChecked(getFromSP("cb4"));
cb4.setOnCheckedChangeListener(this);
loadVariable();
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent output = new Intent();
output.putExtra("number", numberOfTrue);
setResult(Activity.RESULT_OK, output);
finish();
}
});
}
private boolean getFromSP(String key){
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
return preferences.getBoolean(key, false);
}
private void saveInSp(String key,boolean value) {
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
private void saveVariable(int numberOfTrue){
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("key2", numberOfTrue);
editor.commit();
}
private void loadVariable(){
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
int number = sharedPref.getInt("key2", 0);
tv1.setText(""+number);
numberOfTrue=number;
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch(buttonView.getId()){
case R.id.cb1:
saveInSp("cb1",isChecked);
if (isChecked == true){
numberOfTrue++;
}
else
{
numberOfTrue--;
}
break;
case R.id.cb2:
saveInSp("cb2",isChecked);
if (isChecked == true){
numberOfTrue++;
}
else
{
numberOfTrue--;
}
break;
case R.id.cb3:
saveInSp("cb3",isChecked);
if (isChecked == true){
numberOfTrue++;
}
else
{
numberOfTrue--;
}
break;
case R.id.cb4:
saveInSp("cb4",isChecked);
if (isChecked == true){
numberOfTrue++;
}
else
{
numberOfTrue--;
}
break;
}
saveVariable(numberOfTrue);
loadVariable();
}
}
This one if definitely wrong.
Intent intent = new Intent(MainActivity.this, FirstActivity.class);
intent.putExtra("number", numberOfTrue);
startActivityForResult(intent,1);
Intent output = new Intent();
output.putExtra("number", numberOfTrue);
setResult(Activity.RESULT_OK, output);
finish();
You need to left only second part of code. Like this:
Intent output = new Intent();
output.putExtra("number", numberOfTrue);
setResult(Activity.RESULT_OK, output);
finish();
And start your MainActivity like this:
Intent intent = new Intent(FirstActivity.this, MainActivity.class);
startActivityForResult(intent, REQUEST_CODE); // This change is important.
And then do this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) {
number = getIntent().getExtras().getInt("number");
}
}
This way you'll receive number from MainActivity when it'll be closed. But if you want to read this value on FirstActivity start (without going to MainActivity, you need to store checked number in shared preferences and then get value in onCreate() method of FirstActivity.
Write into SharedPreferences in onActivityResult to insure that only "saved" checks will be saved.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) {
number = getIntent().getExtras().getInt("number");
saveNumberToSharedPrefs(number);
}
}
private void saveNumberToSharedPrefs(int num){
SharedPreferences preferences = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE); //Create and store this instance in onCreate method of activity, or use it like this.
preferences.edit().putInt("NUMBER", num).apply(); // Use constant value for key
}
And then you can load your checked number in onCreate method of FirstActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
....
SharedPreferences preferences = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE);
number = preferences.getInt("NUMBER", 0);
}
Update
Here you'r trying to get number from intent in onActivityResult. That's wrong, this way you'll always have number = 0 (default value). On activity result doesn't fill data into intent. All your data is in data variable passed in method.
number = getIntent().getExtras().getInt("number");
saveNumberToSharedPrefs(number);
You need to leave only this:
if (requestCode == REQUEST_CODE) { //also you need to check if result is RESULT_OK
number = data.getExtras().getInt("number");
tv2.setText(""+number);
saveNumberToSharedPrefs(number);
}
FirstActivity
Store values :
Intent intent = new Intent(getBaseContext(), Activity.class);
intent.putExtra("ID", sessionId);
startActivity(intent);
SecondActivity
Fetching Values:
String s = getIntent().getStringExtra("ID");
public static final int REQUEST_CODE = 100;
change on FirstActivity.java
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(FirstActivity.this, MainActivity.class);
startActivityForResult(intent, REQUEST_CODE);
}
});
add onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CODE) {
Log.d("TAG","------"+data.getExtras().getInt("number"));
int number = data.getExtras().getInt("number");
tv2.setText(""+number);
}
}
}
change on MainActivity.java
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Log.d("TAG","------"+numberOfTrue);
Intent output = new Intent();
output.putExtra("number", numberOfTrue);
setResult(Activity.RESULT_OK, output);
finish();
}
});