Sending data from child activity to the main one - java

After trying lot of things found here, nothing worked.
To make it simple :
I have a main activity with a button.
I have a "child" activity with 2 text fields and a button.
When I click the main activity button, the child activity opens (it works). Then I put some text to the two text fields and when I click the button I want the data from the text fields to be transfered to the main activity, and I can't get this working.
Here is my main activity code
public class MainMenu extends AppCompatActivity {
Button btnAddBib;
public final static int REQUEST_CODE_B = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
btnAddBib = (Button)findViewById(R.id.btnAddBib);
btnAddBib.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(v.getContext(), MainActivity.class);
startActivityForResult(myIntent,REQUEST_CODE_B);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case REQUEST_CODE_B:
String Qte = data.getStringExtra("qte");
String Time = data.getStringExtra("time");
if (Qte != null && !Qte.isEmpty() && Time != null && !Time.isEmpty()) {
final SQLiteDatabase dbBib;
dbBib = openOrCreateDatabase("bibi", Context.MODE_PRIVATE, null);
dbBib.execSQL("CREATE TABLE IF NOT EXISTS bibi(time VARCHAR, qte VARCHAR);");
dbBib.execSQL("INSERT INTO bibi VALUES ('" + Time + "','" +
Qte + "')");
Toast.makeText(getApplicationContext(), "Bibi bien enregistré",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Fail get extraData",
Toast.LENGTH_LONG).show();
}
break;
}
}
And the child activity code :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ajouter_bibi);
btnValideBib = (Button)findViewById(R.id.btnValideBib);
btnValideBib.setBackgroundResource(R.drawable.logo_biberon);
txtTime = (EditText)findViewById(R.id.txtTime);
txtQte = (EditText)findViewById(R.id.txtQte);
Calendar c = Calendar.getInstance();
int hh = c.get(Calendar.HOUR_OF_DAY);
int mm = c.get(Calendar.MINUTE);
txtTime.setText(hh + ":" + mm);
btnValideBib.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent backIntent = new Intent();
backIntent.putExtra("qte", txtQte.getText());
backIntent.putExtra("time", txtTime.getText());
setResult(RESULT_OK, backIntent);
finish();
}
});
The problem :
In the main activity, when I want to get back my Extra Strings I have null fields.
String Qte = data.getStringExtra("qte");
String Time = data.getStringExtra("time");
What is wrong with it ?
Thanks!

Change the code :
backIntent.putExtra("qte", txtQte.getText());
backIntent.putExtra("time", txtTime.getText());
to below code:
backIntent.putExtra("qte", txtQte.getText().toString()); //append .toString() method
backIntent.putExtra("time", txtTime.getText().toString());

Related

Android Studio : How to keep variables from one java file to another

I am developping an application which convert scanned data (barcode) to GoogleSheet data, and I am trying to transfer the barcode number (from Page2.java) into another java file (ListItem.java)
I saw that a usual way to do it is to create intents. So I did it.
But the toast I put in ListItem.java gives me "null" instead of the scanned number (for example 0123456789012)
Please, can you tell me where am I wrong ? Thank you so much !
1st Code (Page2.java , where I get "scanContent2", the variable I need) :
public class Page2 extends Activity implements OnClickListener {
#SuppressLint("ClickableViewAccessibility")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.page2);
scanBtn2 = (Button) findViewById(R.id.scan_button2);
scanBtn2.setOnClickListener(this);
}
public Button scanBtn2;
public String scanContent2;
#Override
public void onClick(View v) {
if (v.getId() == R.id.scan_button2) {
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
scanContent2 = scanningResult.getContents();
Intent intenta = new Intent(getApplicationContext(),ListItem.class);
intenta.putExtra("theScanContent2", scanContent2);
startActivity(intenta);
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
}
2nd code (ListItem.java, where I get "null" on the toast) :
public class ListItem extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item);
String scanContent2 = getIntent().getStringExtra("theScanContent");
Toast toast = Toast.makeText(getApplicationContext(),
"BarCode number: " + scanContent2, Toast.LENGTH_SHORT);
toast.show();
}
}
In the Listitem.java in the following line,
String scanContent2 = getIntent().getStringExtra("theScanContent");
You are trying to get String with key theScanContent, while you are putting scanContent2 with key theScanContent2 in Page2.java in line
intent.putExtra("theScanContent2", scanContent2);
Make sure the keys are same for the Intent while putting the data in intent and accessing the data from the intent to avoid getting null Results.

Android - trying to get data back from Activity 2 to Activity 1 and from method to method

First of all - I've already checked different tutorials, but wasn't able to complete my task :(
I'm calling Activity 2 from onAddEventClicked method in Activity 1 to open the layout and let the user type the name in EditText. Then I want to close Activity 2, send captured name back to Activity 1 and use it to set the name parameter when creating new event in ArrayList: event.setName(dataFromActivity2).
I'm able to save EditText's data to String dataFromActivity2, but how should I pass it from onAddEventClicked method back to onAddEventClicked method and set event.setName(dataFromActivity2) ?
Unfortunately I've tried so many times with no luck. Could you guide me with any hints / tips please? I know that the solution is probably simple, but I'm still a beginner... :( Should I use SharedPreferences insted of startActivityForResult?
ACTIVITY1 :
public class BaseActivity extends AppCompatActivity implements WeekView.EventClickListener, MonthLoader.MonthChangeListener, WeekView.EventLongPressListener, WeekView.EmptyViewLongPressListener, WeekView.EmptyViewClickListener, WeekView.AddEventClickListener {
private static final int TYPE_DAY_VIEW = 1;
private static final int TYPE_THREE_DAY_VIEW = 2;
private static final int TYPE_WEEK_VIEW = 3;
private int mWeekViewType = TYPE_THREE_DAY_VIEW;
private static final int REQUEST_CODE = 0;
String TAG = "***";
private WeekView mWeekView;
private ArrayList<WeekViewEvent> mNewEvents;
...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
String dataFromActivity2= data.getStringExtra("fav");
}
#Override
public void onAddEventClicked(Calendar startTime, Calendar endTime) {
Intent intent = new Intent(this, Test2.class);
startActivityForResult(intent, REQUEST_CODE);
WeekViewEvent event = new WeekViewEvent();
event.setId(7);
event.setName(fav);
event.setStartTime(startTime);
event.setEndTime(endTime);
event.setColor(getResources().getColor(R.color.event_color_03));
Log.d(TAG, "Intent test:" +fav);
mNewEvents.add(event);
mWeekView.notifyDatasetChanged();
}
...
}
ACTIVITY 2:
public class Test2 extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
Button btn = (Button) findViewById(R.id.btn_test);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText et = (EditText)findViewById(R.id.etv_test);
String favourities=et.getText().toString();
Intent intent=new Intent();
intent.putExtra("fav", favourities);
setResult(RESULT_OK,intent);
finish();//finishing activity
Toast.makeText(Test2.this, "INTENT CONTAINS:" + intent.getExtras(), Toast.LENGTH_SHORT).show();
}});}}
You should move your code for event creation into the onActivityResult method:
private Calendar startTime, endTime;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
String dataFromActivity2 = data.getStringExtra("fav");
// create event here
WeekViewEvent event = new WeekViewEvent();
event.setId(7);
event.setName(dataFromActivity2);
event.setStartTime(startTime);
event.setEndTime(endTime);
event.setColor(getResources().getColor(R.color.event_color_03));
Log.d(TAG, "Intent test:" + dataFromActivity2);
mNewEvents.add(event);
mWeekView.notifyDatasetChanged();
}
In onAddEventClicked you have to save its parameters (startTime, endTime) to instance variables - to be able to use them in onActivityResult:
#Override
public void onAddEventClicked(Calendar startTime, Calendar endTime) {
this.startTime = startTime;
this.endTime = endTime;
Intent intent = new Intent(this, Test2.class);
startActivityForResult(intent, REQUEST_CODE);
}

How to use a variable in a new activity?

I added a variable that pass form the first activity to the second one.
I want to use the info that has accepted from the first activity, at the new activity, and will save it on new double variable, display it as permanent on a textView.
Now, it appears only when I am clicking on the regular button that start the new activity.
As first step, I guess, I need to remove - "startActivity(intent1);".
How should I move on from here?
Java code:
First Activity (Name : settings.java)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
}
public void onClick (View v){
Intent intent = new Intent(settings.this, WaitressRecord.class);
startActivity(intent);
}
protected void onClickWait (View v) {
//--- Casting & Converting EditText "etSalaryWaitress" to Double "doubleSW".
btnWaitress =(Button)findViewById(R.id.btnWaitress);
etSalaryWaitress = (EditText) findViewById(R.id.etSalaryWaitress);
doubleSW = Double.parseDouble(etSalaryWaitress.getText().toString());
//---Casting Radio Button(s).
rbPercentage = (RadioButton)findViewById(R.id.rbPercentage);
rbShekel = (RadioButton)findViewById(R.id.rbShekel);
if (doubleSW < 100 ) {
if (rbPercentage.isChecked()) {
HafrashaP = 1 - (doubleSW / 100.0);
strHafPer = String.valueOf(HafrashaP);
Toast.makeText(settings.this, strHafPer, Toast.LENGTH_SHORT).show();
// start the SecondActivity
Intent intent1 = new Intent(this, WaitressRecord.class);
intent1.putExtra(Intent.EXTRA_TEXT, strHafPer);
startActivity(intent1);
} else if (rbShekel.isChecked()) {
HafrashaS = -doubleSW;
strHafShek = String.valueOf(HafrashaS);
Toast.makeText(settings.this, strHafShek, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(settings.this, "לא הוזנה סוג ההפרשה", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(settings.this, "מספר שגוי", Toast.LENGTH_SHORT).show();
}
}
New Activity: (Name : WaitressRecord.java)
public class WaitressRecord extends AppCompatActivity {
String strHafPer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_waitress_record);
// get the text from MainActivity
Intent intent1 = getIntent();
strHafPer = intent1.getStringExtra(Intent.EXTRA_TEXT);
// use the text in a TextView
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(strHafPer);
}
}
//First Activity
Intent intent= new Intent(this, SecondActivity.class);
Bundle extra = new Bundle();
mBundle.putString(VARIABLE_KEY, value);
intent.putExtras(mBundle);
startActivity(intent);
//on the second Acitivty
intent intent = getIntent();
Bundle bundleExtra;
//Null Checking
if (intent != null ) {
bundleExtra = getIntent().getExtras();
// Be sure your check your "VARIABLE KEY SAME AS in THE FIRST ACTIVITY
String resultString = extras.getString("VARIABLE_KEY");
}

Retrieve contact from mobile's phone directory

This code can open a built-in contacts directory on a mobile device. However, when I select a contact, the app reports "done", but doesn't retrieve the contact number -- the user can't send a message.
How do I retrieve the contact number? List View is not a solution: I need to return just the one number, not extra information.
Here's my code:
public EditText no;
public EditText msg;
public Button cancel;
public Button snd;
public String Number,name,Message;
public int run=0;
public static final int PICK_CONTACT=1;
public void callContacts(View v)
{
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent,PICK_CONTACT);
}
#Override
public void onActivityResult(int reqCode,int resultCode,Intent data)
{
super.onActivityResult(reqCode,resultCode,data);
if(reqCode==PICK_CONTACT)
{
if(resultCode== ActionBarActivity.RESULT_OK)
{
Uri contactData = data.getData();
Cursor c = getContentResolver().query(contactData,null,null,null,null);
if(c.moveToFirst())
{
name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.CONTENT_URI.toString()));
Toast.makeText(this,"done",Toast.LENGTH_SHORT).show();
}
}
}
}
and here is the onCreate method
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
no = (EditText)findViewById(R.id.num);
msg = (EditText)findViewById(R.id.sms);
cancel = (Button)findViewById(R.id.cancel);
snd = (Button)findViewById(R.id.snd);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
msg.setText("");
no.setText("");
callContacts(null);
}
});
snd.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Number = no.toString();
Message = msg.getText().toString();
SmsManager manager = SmsManager.getDefault();
ArrayList<String>long_sms = manager.divideMessage(Message);
manager.sendMultipartTextMessage(Number,null,long_sms,null,null);
Toast.makeText(getApplicationContext(),"Sent Successfully",Toast.LENGTH_SHORT).show();
}
});
}
Here is the code just for selecting one phone number from contact list. i found this code simplest. let me know if there is any problem.
start activity with pick intent on phone data type:
findViewById(R.id.choose_contact_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent pickContact = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(pickContact, PICK_CONTACT_REQUEST);
}
});
Now set onAcitivityResult();
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
switch (requestCode){
case PICK_CONTACT_REQUEST:
if (resultCode == RESULT_OK){
Uri contactUri = intent.getData();
Cursor nameCursor = getContentResolver().query(contactUri, null, null, null, null);
if (nameCursor.moveToFirst()){
String name = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
((EditText)findViewById(R.id.person_name)).setText(name);
((EditText)findViewById(R.id.enter_mobile)).setText(number);
nameCursor.close();
}
}
break;
}
}

Value in editText doesn't change when save button is clicked

I have two widget in Activity A, one is textView and another is button. Both will be used to access Activity B.
And in Activity B, I have one editText, two textView , one save button and one image button.
If using button in A , Flow: A>>B>>C>>return value and image from C to B then A.
If using textView in A, Flow: pass value and image from A to B , for edit, then click save button to return the edit value and image to A.
Activity B
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().getBooleanExtra("bitmap",false)) //if textField in A clicked
{
viewImage.setImageBitmap(Global.img);
}
else
{
viewImage.setImageBitmap(null);
}
if(getIntent().getExtras()!=null) { // if have 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() { // Back 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);
final int k1 = getIntent().getExtras().getInt("k");
returnIntent.putExtra("k1", k1);
returnIntent.putExtra("c",c);
// returnIntent.putExtra("image",Global.img);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
public void onActivityResult(int requestCode,int resultCode, Intent data)
{ //receive value and image from C
if(requestCode==PROJECT_REQUEST_CODE) {
if(data!=null&&data.hasExtra("text")) {
c = data.getStringExtra("text");
txt1.setText(c);
viewImage.setImageBitmap(Global.img);
}
}
else if (requestCode==CAMERA_REQUEST_CODE)
{
}
}
Activity A
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { //receive data from B
int button = data.getIntExtra("k1", 0);
if (button == 1) {
switch (requestCode) {
case 0:
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;
}
c.setOnClickListener(new View.OnClickListener() { // if c is not null, it can intent to B.Otherwise it is not clickable
#Override
public void onClick(View view) {
if ((name != null && name.trim().length() > 0) && (result != null && result.trim().length() > 0)) {
Toast.makeText(getActivity().getApplicationContext(), "not null", Toast.LENGTH_LONG).show();
if (name.equals("Project")) {
Intent intent = new Intent(getActivity(), Project1.class);
Global.img = null;
v.setDrawingCacheEnabled(true);
v.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
v.getMeasuredWidth(), v.getMeasuredHeight());
v.buildDrawingCache(true);
intent.putExtra("name", name);
intent.putExtra("result", result);
intent.putExtra("description", description);
if (v.getDrawingCache() != null) {
Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());
if (bitmap == null) {
Log.e("TAG", "getDrawingCache() == null");
}
Global.img = bitmap;
startActivity(intent);
}
}
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(getActivity().getApplicationContext(), fk + "", Toast.LENGTH_LONG).show();
AlertDialogRadio(a1);
}
});
public void AlertDialogRadio(final int k) {
final CharSequence[] ClaimsModel = {"B", "Petrol", "Car Maintenance"};
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(), B.class);
intent.putExtra("k",k);
startActivityForResult(intent, 0);
}else{...}
}
Problem: When the textView is clicked and intent to B, the save button doesn't return the changed value and image to A. The value and image not changing.
It looks like there is some caching because of which the old state is retained and not updated. I suggest you try activity.recreate() function which forces the activity to create a new instance.
Activity.Recreate()

Categories

Resources