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();
}
});
Related
I'm trying to load a image from my phone and apply it to an ImageView. I need this image when I re-open the app to be kept in the ImageView.
I'm trying to do something like that with shared preferences. But I get the following log error:
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'android.content.SharedPreferences$Editor android.content.SharedPreferences$Editor.putString(java.lang.String, java.lang.String)' on a null object reference
private static final int PICK_IMAGE = 100;
static SharedPreferences sharedPref;
static SharedPreferences.Editor editor;
private static final String PREFS_NAME = "preferenceName";
Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
PROFILE_IMG = (ImageView)findViewById(R.id.profile_image);
PHOTObutton = (Button)findViewById(R.id.photo_btn);
// Get from the SharedPreferences
sharedPref = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
String imageUriString = sharedPref.getString("imageURI", null);
Uri imageUri = Uri.parse(imageUriString);
PROFILE_IMG.setImageURI(imageUri);
//open gallery-- select profile photo
PHOTObutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openGallery();
}
});
}
private void openGallery() {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE){
imageUri = data.getData();
sharedPref = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
editor.putString("imageURI", imageUri.toString());
editor.commit();
PROFILE_IMG.setImageURI(imageUri);
}
}
What am I doing wrong?
This error is because your editor is null. Try this
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE){
imageUri = data.getData();
SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("imageURI", imageUri.toString());
editor.commit();
PROFILE_IMG.setImageURI(imageUri);
}
}
you forgot to inizile the editor add this into your onactivity result
editor=sharedPref.edit()
editor.putString("imageURI", imageUri.toString());
editor.commit();
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);
}
}
}
In my app I want to make a profile page with default image profile and allow to user to change it by take a picture from camera or choose image from gallery, I did that successfully and here's my code:
public class MainActivity extends AppCompatActivity {
private static final int pick = 1, capture = 2;
Uri imgeUri, touri;
ImageView imp;
SharedPreferences sh;
SharedPreferences.Editor editor;
String S;
boolean d=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("eee","in resume");
setContentView(R.layout.activity_main);
sh = getSharedPreferences("my" ,Context.MODE_PRIVATE);
editor=sh.edit();
imp = (ImageView) findViewById(R.id.profile_image);
if(d==false) {
imp.setImageResource(R.drawable.photo);
}
else{
imp.setImageURI(Uri.parse(sh.getString("link", null)));
}
}
public void changepic(View V) {
final String[] items = {"Take picture", "Choose Picture",
"cancle"};
AlertDialog.Builder build = new AlertDialog.Builder(this);
build.setTitle("Add Photo");
build.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (items[which].equals("Choose Picture")) {
Log.d("test","bh");
Intent i = new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivityForResult(i, pick);
} else if (items[which].equals("Take picture")) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, capture);
}
}
}).create().show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == pick && resultCode == RESULT_OK) {
imgeUri = data.getData();
Log.d("test","pick");
imp.setImageURI(imgeUri);
editor.putString("link",String.valueOf(imgeUri));
//Log.d("test",f);
editor.commit();
d=true;
} else if (requestCode == capture && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imp.setImageBitmap(imageBitmap);
}
}
But the problem is when selecting an image I save it in shared preference the image appears just fine when I'am in activity when go to another and return back this disappear and the activity show the default image, i know the reason it because every time i return to profile activity this was created again and the boolean variable d was false again.
How can i fix that when i must call the get preference.?
In the "onActivityResult()" method, save the imageUri (or imagePath) obtained to sharedPreferences.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor edit = preferences.edit();
edit.putString(key, value);
edit.apply();
Instead of using boolean, check if sharedPreference value is not a null string.If the sharedPreference value is not a null string, update the imageview with imageUri (or imagePath) from sharedPreference.
For loading image in imageView, i recommend you to use photo loading libraries like Picasso or Glide.
I have an application in which multiple activities are shown in a certain order, which can change based on events in the current activity. I have a "master" activity which manages which activities are shown. Each ativity is started with startActivityForResult() with a requestCode unique to that activity.
When the activity finsishes, I set the resultCode to a value which will have meaning to the master activity. In the master activity's onActivityResult method, I have a switch (requestCode), which will tell me which activity has returned, and in each case block I work with the resultCode to determine which activity to start next.
The problem I'm having, is that at times, seemingly randomly, the application behaves quite erratically, showing activities out of sequence.
I've been unable to replicate the issue while debugging, so all the information I have looks good, but the end users are constantly complaining about the erratic behaviour.
How can I test to see where the problem is?
The code from the master activity's onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case Settings.SCREEN_UPDATE:
ShowActivity(LoginActivity.class, Settings.SCREEN_LOGIN);
break;
case Settings.SCREEN_LOGIN:
if (resultCode == RESULT_OK) {
Settings.CurrentReport = new Report();
Settings.CurrentReport.setUserId(data.getIntExtra("userId", -1));
selectStore();
} else {
finish();
}
break;
case Settings.SCREEN_PRODUCT: // Coming back from the product selection screen
if (resultCode == RESULT_OK) {
ShowActivity(ActionActivity.class, Settings.SCREEN_ACTION);
} else if (resultCode == RESULT_CANCELED){
ShowActivity(OptionsActivity.class, Settings.SCREEN_OPTIONS);
}
break;
case Settings.SCREEN_ACTION: // Coming back from the action screen, regardless of result, show options screen.
ShowActivity(OptionsActivity.class, Settings.SCREEN_OPTIONS);
break;
case Settings.SCREEN_OPTIONS: // All choices return result_ok. Check the "mode" extra
String mode = data.getStringExtra("mode");
processOption(mode);
break;
case Settings.SCREEN_SESSION:
if (resultCode == RESULT_CANCELED) {
ShowActivity(OptionsActivity.class, Settings.SCREEN_OPTIONS);
} else if (resultCode == RESULT_OK ){
ShowActivity(ActionActivity.class, Settings.SCREEN_ACTION);
}
break;
} // switch (requestCode)
} // protected void onActivityResult(int requestCode, int resultCode, Intent data) {
private void processOption(String mode) {
if (mode.equals("select")) {
ShowActivity(ProductActivity.class, Settings.SCREEN_PRODUCT);
} else if (mode.equals("repeat")) {
Settings.CurrentReport.repeatItem();
ShowActivity(ActionActivity.class, Settings.SCREEN_ACTION);
} else if (mode.equals("session")) {
ShowActivity(SessionActivity.class, Settings.SCREEN_SESSION);
} else { // mode equals "end"
confirmFinish();
}
}
private void ShowActivity(Class cls, int requestCode) {
Intent activity = new Intent(this, cls);
startActivityForResult(activity, requestCode);
}
Then, the code from one of the other activities handling the finish() event:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.options);
Button btn;
btn = (Button)findViewById(R.id.btnSelect);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = getIntent();
intent.putExtra("mode", "select");
setResult(RESULT_OK, intent);
finish();
}
});
btn = (Button)findViewById(R.id.btnRepeat);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = getIntent();
intent.putExtra("mode", "repeat");
setResult(RESULT_OK, intent);
finish();
}
});
btn.setEnabled(Settings.CurrentReport.hasPreviousItem());
btn = (Button)findViewById(R.id.btnSession);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = getIntent();
intent.putExtra("mode", "session");
setResult(RESULT_OK, intent);
finish();
}
});
btn = (Button)findViewById(R.id.btnEnd);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = getIntent();
intent.putExtra("mode", "end");
setResult(RESULT_OK, intent);
finish();
}
});
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
Intent i = getIntent();
i.putExtra("mode", "end");
setResult(RESULT_OK, i);
finish();
break;
}
return super.onKeyDown(keyCode, event);
}
Im just guessing, but maybe Intent intent = getIntent(); is causing the problems. You could try to replace it with Intent intent = new Intent();
getIntent() returns the intent that started the current activity and shouldn't be used as a result.
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.