startActivityForResult() does not work - java

I have a button in Claims.java. When button is pressed, it will show Alert Dialog Window with radio buttons.If the radio button is checked, it will goes to specific activity. In the activity, it has an editText and a save button. I want the value on the editText display on the button(Claims.java) when the save button in the activity is clicked.
Claims.java >> AlertDialog Window in Claims.java >> AlertDialogRadio.java
I use startActivityForResult() to receive a result back from AlertRadioDialog.java. But the problem now is it will display AlertDialogRadio which is not what I want and the text does not display on the textView. How can I do to achieve this?
Claims.java
public class Claims extends Fragment {
private TextView c;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View claims = inflater.inflate(R.layout.claims, container, false);
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
AlertDialogRadio();
}
};
Button button1 = (Button) claims.findViewById(R.id.button10);
Button button = (Button) claims.findViewById(R.id.button8);
button1.setOnClickListener(listener);
c=(TextView)claims.findViewById(R.id.textView49);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(getActivity().getApplicationContext(), CameraMain.class);
startActivity(intent);
}
});
return claims;
}
public void AlertDialogRadio() {
final CharSequence[] ClaimsModel = {"Project", "Petrol", "Car Maintenance"
, "Medical", "Other"};
AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
alt_bld.setTitle("Select a Claims");
alt_bld.setSingleChoiceItems(ClaimsModel, -1, new DialogInterface
.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(), Project1.class);
startActivity(intent);
} else if (item == 1) {
Intent intent = new Intent(getActivity().getApplicationContext(), Petrol.class);
startActivity(intent);
} else if (item == 2) {
Intent intent = new Intent(getActivity().getApplicationContext(), CarMainten.class);
startActivity(intent);
} else if (item == 3) {
Intent intent = new Intent(getActivity().getApplicationContext(), Medical.class);
startActivity(intent);
} else if (item == 4) {
Intent intent = new Intent(getActivity().getApplicationContext(), Other.class);
startActivity(intent);
}
}
});
AlertDialog alert = alt_bld.create();
alert.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("text");
c.setText(result);
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}//onActivityResult
}
Assume the user choose Project.
Project1.java
public class Project1 extends AppCompatActivity {
private static String text;
private static EditText txt;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project);
txt= (EditText)findViewById(R.id.editText36);
Button b=(Button)findViewById(R.id.button17);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent returnIntent = new Intent();
text = txt.getText().toString();
returnIntent.putExtra("text", text);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
}

First of all, you're not using startActivityForResult at all.
Here's how you should proceed:
Claims.java
public static final int PROJECT_REQUEST_CODE = 1;
public static final int CAMERA_REQUEST_CODE = 2;
public static .....
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(), Project1.class);
startActivityForResult(intent, PROJECT_REQUEST_CODE);
}
else if .....
And in OnActivityResult :
if (requestCode == PROJECT_REQUEST_CODE) {
...
}
else if(requestCode == CAMERA_REQUEST_CODE) {
...
}
else if ...

Related

Keep the data save in sharedPreference although pressed back button - Android Studio

I have some problem as I mention in my question. I have two activity, Activity A and Activity B. When I Enter some data in Activity A, then I press next button, it will redirect to Activity B. At Activity B, I also enter some data. When I press back button, the data at Activity A is display as I entered before. When I press next button, the data that I entered at Activity B is missing. Below is my SharedPreferences code.
Activity A:
public class NewSuggestion extends AppCompatActivity {
private EditText etYear, etMonth, etTitle, etOwnValue;
private RadioGroup rgSuggestWill;
private RadioButton radioButton;
private Button btnNext;
ArrayAdapter<CharSequence> adapter;
private Spinner spReviewer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_suggestion);
final ActionBar abar = getSupportActionBar();
View viewActionBar = getLayoutInflater().inflate(R.layout.activity_new_suggestion, null);
ActionBar.LayoutParams params = new ActionBar.LayoutParams(//Center the textview in the ActionBar !
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.MATCH_PARENT,
Gravity.CENTER);
TextView tvTitle = viewActionBar.findViewById(R.id.title);
tvTitle.setText("NEW SUGGESTION");
abar.setCustomView(viewActionBar, params);
abar.setDisplayShowCustomEnabled(true);
abar.setDisplayShowTitleEnabled(false);
//abar.setDisplayHomeAsUpEnabled(true);
abar.setHomeButtonEnabled(true);
etTitle = findViewById(R.id.etTitle);
etYear = findViewById(R.id.etYear);
etMonth = findViewById(R.id.etMonth);
rgSuggestWill =findViewById(R.id.rgSuggestWill);
final Calendar c = Calendar.getInstance();
String mm = c.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.US);
int yy = c.get(Calendar.YEAR);
etYear.setText(new StringBuilder().append(yy));
etMonth.setText(new StringBuilder().append(mm));
spReviewer = findViewById(R.id.spReviewer);
adapter = ArrayAdapter.createFromResource(this,R.array.reviewer,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spReviewer.setAdapter(adapter);
spReviewer.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
btnNext = findViewById(R.id.btnNext);
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPref = getSharedPreferences("MyData",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("title",etTitle.getText().toString());
editor.putString("year",etYear.getText().toString());
editor.putString("month",etMonth.getText().toString());
// get selected radio button from radioGroup
int selectedId = rgSuggestWill.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioButton = findViewById(selectedId);
editor.putString("suggestionwill",radioButton.getText().toString());
if (spReviewer.getSelectedItem().toString().equals("Please choose")){
AlertDialog alertDialog = new AlertDialog.Builder(NewSuggestion.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Please choose your reviewer");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}else{
editor.putString("reviewer",spReviewer.getSelectedItem().toString());
Intent intent = new Intent(NewSuggestion.this,NewSuggestion2.class);
startActivity(intent);
}
editor.apply();
}
});
}
#Override
public void onBackPressed() {
Intent intent = new Intent(NewSuggestion.this, DashboardApp.class);
startActivity(intent);
}
}
Activity B:
public class NewSuggestion2 extends AppCompatActivity {
private EditText etPresent, etDetails, etBenefit;
private ImageView imgAttach,btnCamera,btnGallery;
private Button btnNext,btnClear;
private Intent intent;
private Bitmap bitmap;
private int REQUEST_CODE = 1;
public static final int RequestPermissionCode = 1 ;
public static final String DEFAULT = "N/A";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_suggestion2);
final ActionBar abar = getSupportActionBar();
View viewActionBar = getLayoutInflater().inflate(R.layout.activity_new_suggestion, null);
ActionBar.LayoutParams params = new ActionBar.LayoutParams(//Center the textview in the ActionBar !
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.MATCH_PARENT,
Gravity.CENTER);
TextView tvTitle = viewActionBar.findViewById(R.id.title);
tvTitle.setText("NEW SUGGESTION (Cont..)");
abar.setCustomView(viewActionBar, params);
abar.setDisplayShowCustomEnabled(true);
abar.setDisplayShowTitleEnabled(false);
//abar.setDisplayHomeAsUpEnabled(true);
abar.setHomeButtonEnabled(true);
etPresent = findViewById(R.id.etPresent);
etDetails = findViewById(R.id.etDetails);
etBenefit = findViewById(R.id.etBenefit);
imgAttach = findViewById(R.id.imgAttach);
btnCamera=findViewById(R.id.btnCamera);
EnableRuntimePermission();
btnCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 7);
}
});
btnGallery=findViewById(R.id.btnGallery);
btnGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Photo"),REQUEST_CODE);
}
});
btnNext = findViewById(R.id.btnNext);
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("present", etPresent.getText().toString());
editor.putString("details", etDetails.getText().toString());
editor.putString("benefit", etBenefit.getText().toString());
editor.apply();
Intent intent = new Intent(NewSuggestion2.this,ConfirmSuggestion.class);
startActivity(intent);
}
});
btnClear = findViewById(R.id.btnClear);
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imgAttach.setImageBitmap(null);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 7 && resultCode == RESULT_OK) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
imgAttach.setImageBitmap(bitmap);
}
if(requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null){
Uri uri = data.getData();
try{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
imgAttach.setImageBitmap(bitmap);
}catch (IOException e){
e.printStackTrace();
}
}
}
public void EnableRuntimePermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(NewSuggestion2.this,
Manifest.permission.CAMERA))
{
Toast.makeText(NewSuggestion2.this,"CAMERA permission allows us to Access CAMERA app", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(NewSuggestion2.this,new String[]{
Manifest.permission.CAMERA}, RequestPermissionCode);
}
}
#Override
public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {
switch (RC) {
case RequestPermissionCode:
if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(NewSuggestion2.this,"Permission Granted, Now your application can access CAMERA.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(NewSuggestion2.this,"Permission Canceled, Now your application cannot access CAMERA.", Toast.LENGTH_LONG).show();
}
break;
}
}
#Override
public void onBackPressed() {
}
}
Assign value to present,details,benefit from sharedpref
SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
etPresent = findViewById(R.id.etPresent);
etDetails = findViewById(R.id.etDetails);
etBenefit = findViewById(R.id.etBenefit);
etPresent.setText(sharedPref.getString("present", ""));
etDetails.setText(sharedPref.getString("details", ""));
etBenefit.setText(sharedPref.getString("benefit", ""));
In Activity B make sure you save data in onBackPressed()
#Override
public void onBackPressed() {
editor.putString("present", etPresent.getText().toString());
editor.putString("details", etDetails.getText().toString());
editor.putString("benefit", etBenefit.getText().toString());
editor.apply();
super.onBackPressed();
}
You have to override the onBackPress() method.In Activity B it is necessary to put data in to SharedPreferences.
#Override
public void onBackPressed() {
SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("present", etPresent.getText().toString());
editor.putString("details", etDetails.getText().toString());
editor.putString("benefit", etBenefit.getText().toString());
editor.commit();
}

Start activity from fragment, then get callback

I am trying to get a callback from an activity that I am starting with an intent in my fragment.
I thought I could do this with onActivityResult but it doesn't seem to get called when I finish(); on the activity. Is this possible in a fragment?
Fragment.java
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
getActivity().setTitle("Waiver");
myView = inflater.inflate(R.layout.waiver_layout, container, false);
signBtn = myView.findViewById(R.id.signBtn);
signBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), SignatureActivity.class);
intent.putExtra("signatureAbleId", device.id);
intent.putExtra("signatureAbleType", "App\\Models\\Device");
startActivity(intent);
}
});
return myView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
Log.v("Activity", "The activity has finished");
if(resultCode == 200){
saveWaiver();
}
}
private void saveWaiver(){
Log.v("Save Waiver", "Saving waiver for you.");
}
SignatureActivity.java
public class SignatureActivity extends AppCompatActivity {
private Button btnClear;
private Button btnSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.activity_signature);
Bundle bundle = getIntent().getExtras();
if(bundle != null){
signatureAbleId = bundle.getInt("signatureAbleId");
signatureAbleType = bundle.getString("signatureAbleType");
}
btnClear = findViewById(R.id.btnClear);
btnSave = findViewById(R.id.btnSave);
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSignaturePad.clear();
}
});
btnSave.setOnClickListener(new View.OnClickListener() {
setResult(200);
finish();
});
}
}
Use this. It will help you
Intent intent = new Intent(getContext(), SignatureActivity.class);
Instead of
Intent intent = new Intent(getActivity(), SignatureActivity.class);
And Yes need to change :
startActivity to startActivityForResult
Use startActivityForResult instead of startActivity
startActivityForResult(intent, 11);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == 11){
if(resultCode == 200){
saveWaiver();
}
}else{
super.onActivityResult(requestCode, resultCode, data)
}
}

Edit listView value

I have 3 activities, A, B and C.The flow of activity is from A to B then C. From C, all the images and value will be returned to B then A. All the returned value and image will be loaded in listView A.
The listView is clickable and once it is clicked, it will intent to B to do some edition. But the problem now is when I edit the text value in B and return to A, I get a new list instead of updating the old one.
What's wrong here ? Anyone can help?
Activity C
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_fit_screen);
selectImage();
b = (ImageView) findViewById(R.id.imageView3);
t = (EditText) findViewById(R.id.editText38);
cancel=(Button)findViewById(R.id.button15);
ok=(Button)findViewById(R.id.button16);
cancel.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0) {
finish();
}
});
ok.setOnClickListener(new View.OnClickListener()
{ // return to B
public void onClick(View arg0)
{
Intent returnIntent=new Intent();
text=t.getText().toString();
b.setDrawingCacheEnabled(true);
b.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
b.layout(0, 0, b.getMeasuredWidth(), b.getMeasuredHeight());
b.buildDrawingCache(true);
returnIntent.putExtra("text", text);
if (b.getDrawingCache() != null) {
Bitmap bitmap = Bitmap.createBitmap(b.getDrawingCache());
if (bitmap == null) {
Log.e("TAG", "getDrawingCache() == null");
}
Global.img = bitmap;
}
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
Activity B
ImageButton imageButton;
ImageView viewImage;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project);
txt = (EditText) findViewById(R.id.editText36);
txt1=(TextView)findViewById(R.id.textView57);
Button b = (Button) findViewById(R.id.button17);
addListenerOnButton();
viewImage = (ImageView) findViewById(R.id.imageView2);
if(getIntent().getExtras()!=null) { //if has value pass from A
final String Amount = getIntent().getExtras().getString("result");
final String description1 = getIntent().getExtras().getString("description");
txt1.setText(description1);
txt.setText(Amount);
}
b.setOnClickListener(new View.OnClickListener() { // return to A
public void onClick(View arg0) {
Intent returnIntent = new Intent();
a = "Project";
text = txt.getText().toString(); // amount
returnIntent.putExtra("text", text);
returnIntent.putExtra("a", a);
returnIntent.putExtra("c", c);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
viewImage.setImageBitmap(Global.img);
}
public void addListenerOnButton() {
imageButton = (ImageButton) findViewById(R.id.imageButton);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Global.img=null;
Intent i = new Intent(B.this,C.class);
startActivityForResult(i, PROJECT_REQUEST_CODE);
}
});
}
public void onActivityResult(int requestCode,int resultCode, Intent data)
{
if(requestCode==PROJECT_REQUEST_CODE) { // receive fom C
if(data!=null&&data.hasExtra("text")) {
c = data.getStringExtra("text");
txt1.setText(c);
viewImage.setImageBitmap(Global.img); // image from C can be shown here
}
}
else if (requestCode==CAMERA_REQUEST_CODE)
{
}
}
}
Activity A
public class Claims1 extends Fragment {
ListView listV;
String description;
String result="";
String name;
long as=0;
TextView c;
ImageView v;
ArrayAdapter<String> adapter;
ArrayList<String> m_listItems = new ArrayList<String>();
String Text;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
setHasOptionsMenu(true);
View claims = inflater.inflate(R.layout.receipt_text, container, false);
v=(ImageView)claims.findViewById(R.id.imageView4);
listV = (ListView) claims.findViewById(R.id.listView1);
android.support.v7.app.ActionBar myActionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
myActionBar.setHomeButtonEnabled(true);
ImageView imageView = new ImageView(myActionBar.getThemedContext());
imageView.setScaleType(ImageView.ScaleType.CENTER);
imageView.setImageResource(R.mipmap.create);
adapter=new ArrayAdapter<String>(getActivity(),R.layout.claims,R.id.textView1,m_listItems);
android.support.v7.app.ActionBar.LayoutParams layoutParams = new android.support.v7.app.ActionBar.LayoutParams(
android.support.v7.app.ActionBar.LayoutParams.WRAP_CONTENT,
android.support.v7.app.ActionBar.LayoutParams.WRAP_CONTENT, Gravity.RIGHT
| Gravity.CENTER_VERTICAL); // for icon in action bar
layoutParams.rightMargin = 40;
imageView.setLayoutParams(layoutParams);
myActionBar.setCustomView(imageView);
listV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
if(name.equals("Project")) {
Intent intent = new Intent(Claims1.this.getActivity(), B.class);
intent.putExtra("bitmap",true);
intent.putExtra("name",name);
intent.putExtra("result",result);
startActivityForResult(intent,0);
}
}
});
return claims;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.my_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.create1:
AlertDialogRadio();
return true;
}
return (super.onOptionsItemSelected(item));
}
public void AlertDialogRadio() {
final CharSequence[] ClaimsModel = {"B", "Petrol"};
AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
alt_bld.setTitle("Select a Class");
alt_bld.setSingleChoiceItems(ClaimsModel, -1, new DialogInterface
.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(),B.class);
startActivityForResult(intent, 0);
} else if (item == 1) {
Intent intent = new Intent(getActivity().getApplicationContext(), Petrol.class);
startActivityForResult(intent, 1);
}
dialog.dismiss();
}
});
AlertDialog alert = alt_bld.create();
alert.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 0:
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description = data.getStringExtra("c");
as = Long.parseLong(result);
Log.d("FIRST", "result:"+result);
Text=" "+name+" "+"RM"+result+"";
m_listItems.add(Text);
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
case 1:
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description = data.getStringExtra("c");
if (Global.img != null) {
v.setImageBitmap(Global.img);
}
as = Long.parseLong(result);
c.setText(" " + name + "------" + "RM " + result);
break;
}
}
Edited
Add a global variable in A - private int mClickedPosition;
Add mClickedPosition = position; in OnItemClick
then
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 0:
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description = data.getStringExtra("c");
as = Long.parseLong(result);
Log.d("FIRST", "result:"+result);
Text=" "+name+" "+"RM"+result+"";
m_listItems.set(mClickedPosition,Text);
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
11-16 18:15:54.751 23044-23044/com.example.project.project
E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.project.project, PID: 23044
java.lang.RuntimeException: Failure delivering result ResultInfo{who=android:fragment:0, request=0, result=-1, data=Intent {
(has extras) }} to activity
{com.example.project.project/com.example.project.project.MainActivity}:
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at android.app.ActivityThread.deliverResults(ActivityThread.java:3681)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3724)
m_listItems.set(mClickedPosition,Text);
in your activity A onActivityResult method when you return from activity B after editing you are adding new item into arraylist using this code m_listItems.add(Text);
instead of adding new item you update the array list using this code
m_listItems.set(position Text);
Try edit your code like this:
case 0:
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description = data.getStringExtra("c");
as = Long.parseLong(result);
Log.d("FIRST", "result:"+result);
Text=" "+name+" "+"RM"+result+"";
if (m_listItems.size() == 0) {
m_listItems.add(Text);
} else {
m_listItems.set(mClickedPosition,Text);
}
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;

Display text to another class

I have a showAddForm button like the imej below in Claims.java.
When the + button is pressed, it will show Alert Dialog Window with radio buttons. When the radio button is checked, it will goes to specific activity. In the activity, it has an editText and a save button. I want the value on the editText display on the showAddForm button when the save button in the activity is clicked. How can I do to achieve this?
Claims.java
public class Claims extends Fragment {
private TextView c;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View claims = inflater.inflate(R.layout.claims, container, false);
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
AlertDialogRadio();
}
};
Button button1 = (Button) claims.findViewById(R.id.button10);
Button button = (Button) claims.findViewById(R.id.button8);
button1.setOnClickListener(listener);
c=(TextView)claims.findViewById(R.id.textView49);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(getActivity().getApplicationContext(), CameraMain.class);
startActivity(intent);
}
});
return claims;
}
public void AlertDialogRadio() {
final CharSequence[] ClaimsModel = {"Project", "Petrol", "Car Maintenance"
, "Medical", "Other"};
AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
alt_bld.setTitle("Select a Claims");
alt_bld.setSingleChoiceItems(ClaimsModel, -1, new DialogInterface
.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(), Project1.class);
startActivity(intent);
} else if (item == 1) {
Intent intent = new Intent(getActivity().getApplicationContext(), Petrol.class);
startActivity(intent);
} else if (item == 2) {
Intent intent = new Intent(getActivity().getApplicationContext(), CarMainten.class);
startActivity(intent);
} else if (item == 3) {
Intent intent = new Intent(getActivity().getApplicationContext(), Medical.class);
startActivity(intent);
} else if (item == 4) {
Intent intent = new Intent(getActivity().getApplicationContext(), Other.class);
startActivity(intent);
}
}
});
AlertDialog alert = alt_bld.create();
alert.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("text");
c.setText(result);
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}//onActivityResult
}
Assume the user choose Project.
Project1.java
public class Project1 extends AppCompatActivity {
private static String text;
private static EditText txt;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project);
txt= (EditText)findViewById(R.id.editText36);
Button b=(Button)findViewById(R.id.button17);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent returnIntent = new Intent();
text = txt.getText().toString();
returnIntent.putExtra("text", text);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
}
Now when I click save button in Project1.java, it return to the AlertDialogRadio which is not I want and the text still not displaying on the textView!!! ANYONE CAN HELP?????
You can use startActivityForResult() and override onActivityResult() in your activity. You can use setResult() in the second activity to pass whatever you want to your caller activity.
Example here and here
edit:
If you want it to use from a Fragment, you have to write this in your Activity that is holding the Fragment:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
This will pass the result to your fragment, so you can handle the result inside your fragment.
And as I already mentioned, you have to use startActivityForResult() instead of startActivity()
as #keybee said you should use startActivityForResult() to start the project.class from your dialog.
In the Project1.Class when you click save use setResult() to send the value back to the claims.class(Dont do startActivity() again. just use finish() ).
and in your Claims.class use onActivityResult(int requestCode, int resultCode, Intent data) to recieve the value sent from the project1.class.
you can do a setText() on showAddForm button in the onActivityResult(int requestCode, int resultCode, Intent data) function

Get certain intents

So lets say i have 4 buttons , and each button contains an intent which navigates to an activity.They all navigate to a single same activity . When i click the first button i want that new activity to show "Hi" , When i click the second button i want it to show "Bye" and so on . How do i do that ?
Here is a simple code to start with
public class Intentt extends Activity {
Button b1,b2,b3,b4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intentt);
b1 = (Button)findViewById(R.id.button2);
b2 = (Button)findViewById(R.id.button3);
b3 = (Button)findViewById(R.id.button4);
b4 = (Button)findViewById(R.id.button5);
b1.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intentt.this,MainActivity.class);
startActivity(i);
}
});
b2.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intentt.this,MainActivity.class);
startActivity(i);
}
});
b3.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intentt.this,MainActivity.class);
startActivity(i);
}
});
b4.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intentt.this,MainActivity.class);
startActivity(i);
}
});
}
Just pass some data through intent extras, or intent extra Bundle:
Intent i=new Intent(context,MainActivity.class);
i.putExtra(id, 453);
context.startActivity(i);
Example:
Button b1, b2, b3, b4;
Context context = this;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intentt);
b1 = (Button) findViewById(R.id.button2);
b2 = (Button) findViewById(R.id.button3);
b3 = (Button) findViewById(R.id.button4);
b4 = (Button) findViewById(R.id.button5);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, MainActivity.class);
i.putExtra(MainActivity.ID_ACTION, MainActivity.ACTION_1);
startActivity(i);
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, MainActivity.class);
i.putExtra(MainActivity.ID_ACTION, MainActivity.ACTION_2);
startActivity(i);
}
});
}
And then in that activity you can switch on that values getting them like that:
String id = intent.getStringExtra("id");
int id = intent.getIntExtra("id",-1);
and then use the if-elseif-else or switch statement(s) to change the actions based on the passed action, so you can display your messages
To properly recieve them you need to set activity's launchMode to "standard" because of this bug in AndroidManifest.xml and create
public static final int ACTION_1 = 1;
public static final int ACTION_2 = 2;
public static final int ACTION_NULL = -1;
public static final String ID_ACTION = "action_id";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int id = getIntent().getIntExtra(ID_ACTION, -1);
if (id == ACTION_NULL) {
Log.d("TAG", "id is null");
Toast.makeText(MainActivity.this, "id is null!", Toast.LENGTH_SHORT).show();
} else if (id == ACTION_1) {
Log.i("TAG", "ALLOHA! from button 1");
Toast.makeText(MainActivity.this, "Aloha from button 1!", Toast.LENGTH_LONG).show();
} else if (id == ACTION_2) {
Log.i("TAG", "Hello from button 2");
Toast.makeText(MainActivity.thi,"Hello from button 2!", Toast.LENGTH_LONG).show();
}
}
In each intent you could pass parameterts
Intent i=new Intent(context,SendMessage.class);
i.putExtra("KEY_MESSAGE", "Hola amigo");
In the other activity
Intent i = getIntent();
String message = i.getStringExtra("KEY_MESSAGE")
Toast.make(this,message,Toast.LENGTH_SHORT).show()
Re write the button click listener as follows :
b1.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intentt.this,MainActivity.class);
i.putExtra("Data","Hi");
startActivity(i);
}
});
b2.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intentt.this,MainActivity.class);
i.putExtra("Data","Hello");
startActivity(i);
}
});
b3.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intentt.this,MainActivity.class);
i.putExtra("Data","Bye");
startActivity(i);
}
});
b4.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intentt.this,MainActivity.class);
i.putExtra("Data","See you");
startActivity(i);
}
});
In your MainActivity class onCreate Method, you can access the passed data by :
String passedData = getIntent().getStringExtra("Data");
you can use this passedData to display on screen.
Do it like this:
public class Intentt extends Activity implements View.OnClickListener {
Button b1,b2,b3,b4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intentt);
b1 = (Button)findViewById(R.id.button2);
b2 = (Button)findViewById(R.id.button3);
b3 = (Button)findViewById(R.id.button4);
b4 = (Button)findViewById(R.id.button5);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
b4.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button2:
Intent i = new Intent(Intentt.this,MainActivity.class);
i.putExtra('"STRING_I_NEED"', "Hi");
startActivity(i)
break;
case R.id.button3:
Intent i = new Intent(Intentt.this,MainActivity.class);
i.putExtra('"STRING_I_NEED"', "Bye");
startActivity(i)
break;
case R.id.button4:
break;
.
.
.
}
}
}
After that in your mainActivity retrieve string that you sent with:
Bundle extras = getIntent().getExtras();
String s = extras.getString("STRING_I_NEED");

Categories

Resources