I am working on an android app whose main purpose is to update the working location of the employees by admin. Now when I want to change/update the location of an employee from my recycler view(list of employees connected with my UserManagerAdapter), I have to pass the user name of that employee to the place picker intent so that when the admin pick the desired location, the database of that user will be changed accordingly.
My Steps(2 Steps)
I have passed the username to the place picker intent as bundle.
My UserManagerAdapter
holder.locationTv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
launchPicker(data.get(position).getUserName());
}
});
private void launchPicker(String userName) {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
Bundle bundle = new Bundle();
bundle.putString(USERNAME,userName);
try {
fragment.startActivityForResult(builder.build(fragment.getActivity()),PLACE_PICKER_REQUEST,bundle);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
I received the location request inside of a fragment and update the location of that particular user
My ManageUserFragment
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == PLACE_PICKER_REQUEST){
if(resultCode == RESULT_OK){
Place place = PlacePicker.getPlace(getContext(),data);
address = place.getAddress().toString();
String latLng = place.getLatLng().toString();
latLang = latLng;
//update user's decided location
Bundle bundle = data.getExtras();
String userName = bundle.getString(USERNAME);// it returns null, Why?
updateLocation(latLang,userName);
Toast.makeText(getContext(), latLng, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getContext(), getContext().getText(R.string.locationError), Toast.LENGTH_SHORT).show();
}
}
}
My constant is
public static final String USERNAME="Username";
Now,
My problem is
Why bundle.getString(USERNAME) always return null?
How to pass data to place picker intent so that we can receive it in
onActivityResult ?
After replicating your case and researching for a little bit, I found out that the third parameter in startActivityForResult() is not used to pass a bundle of values to the onActivityResult, it's used to pass options to Android itself, you can find those here. So if you want to pass any data you have to use an intent with putExtra("USERNAME", username), and you can retrieve it with getStringExtra("USERNAME"). It's explained in this answer as well.
Related
Team
My question is, how do I read the result from the startAtcivityForResult.
When the button is pressed, it calls bStock(), which makes a URL call and retrieves data. I have verified the URL call is correct and that I do get data.
I have used finishActivity(1) to not display the actual content or result. For the sake of this message here is what I get when not using finishActivity(1)
My goal is to read the result and only display certain values like name and last price. Here is my code
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setContentView(R.layout.content_layout_id);
final Button buttonStock = findViewById(R.id.buttonS);
buttonStock.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
bStock();
}
});
}
static final int REQUEST_CODE = 1;
protected void bStock() {
String url = "http://dev.markitondemand.com/Api/v2/Quote/jsonp?symbol=AG";
Uri uri = Uri.parse(url);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
i.setPackage("com.android.chrome");
startActivityForResult(i, REQUEST_CODE);
finishActivity(1);
}
#Override
protected void onActivityResult ( int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE) {
// Make sure the request was successful
//if (resultCode == RESULT_OK) { // 0 -1
// Get the URI that points to the selected contact
Uri o = data.getData();
Toast.makeText(MainActivity.this, "Name ", Toast.LENGTH_LONG).show();});
}
}
I am using a Toast (for now) just to display the name, but I do not know how to read data. Any help would be appreciated.
Jesse
That does not work as you expect, because the activity you are trying to start (chrome browser) is not prepared to return the result you want, to you. The intent (VIEW) tells the browser, to do just that -- view the given URL.
For activities that are not your own, you have to carecully check their description to see if they support any calls for results, and how they return it -- e.g. there is a 'take a picture' intent, that will return the picture taken to you via some uri data.
Most of the time, startActivityForResult is used to start your own activities, which you want to return data to the calling activity. In that case, you can define yourself, on how to pass the results back to the calling activity.
you may need to iterate through a cursor
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request it is that we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// Get the URI that points to the selected contact
Uri contactUri = data.getData();
// We only need the NUMBER column, because there will be only one row in the result
String[] projection = {Phone.NUMBER};
// Perform the query on the contact to get the NUMBER column
// We don't need a selection or sort order (there's only one result for the given URI)
// CAUTION: The query() method should be called from a separate thread to avoid blocking
// your app's UI thread. (For simplicity of the sample, this code doesn't do that.)
// Consider using CursorLoader to perform the query.
Cursor cursor = getContentResolver()
.query(contactUri, projection, null, null, null);
cursor.moveToFirst();
// Retrieve the phone number from the NUMBER column
int column = cursor.getColumnIndex(Phone.NUMBER);
String number = cursor.getString(column);
// Do something with the phone number...
}
}
}
I'll just go straight to the problem. In UploadNotesActivity.java....
First, I pick a .pdf file using intent
chooseNotesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
// Start the Intent
startActivityForResult(intent, RESULT_LOAD_FILE);
}
});
and then, in `onActivityResult, I save the filePath of the picked file.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_FILE && resultCode == RESULT_OK && data != null) {
data.putExtra("filePath", data.getData().getPath());
choosenFile.setText(data.getStringExtra("filePath"));
} else {
Toast.makeText(this, "Error in choosing file",
Toast.LENGTH_LONG).show();
}
}
click Upload button to start upload the file
uploadNotesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onUploadButtonClick();
}
});
the onUploadButtonClick()
private void onUploadButtonClick() {
final String serverUrlString = "http://XXXX/uploadNotes.php";
if (getIntent().getStringExtra("filePath").isEmpty()) {
Log.d(TAG, "filePath is null");
} else {
Log.d(TAG, getIntent().getStringExtra("filePath"));
}
final String fileToUploadPath = getIntent().getStringExtra("filePath");
final String paramNameString = "uploaded_file";
String fileName[] = fileToUploadPath.split("/");
final MultipartUploadRequest request =
new MultipartUploadRequest(this, UUID.randomUUID().toString(), serverUrlString);
request.addFileToUpload(fileToUploadPath, paramNameString,
fileName[fileName.length-1]+".pdf", ContentType.APPLICATION_OCTET_STREAM);
request.setNotificationConfig(R.drawable.ic_launcher,
getString(R.string.app_name),
getString(R.string.uploading),
getString(R.string.upload_success),
getString(R.string.upload_error),
false);
// if you comment the following line, the system default user-agent will be used
request.setCustomUserAgent("UploadServiceDemo/1.0");
// set the intent to perform when the user taps on the upload notification.
// currently tested only with intents that launches an activity
// if you comment this line, no action will be performed when the user taps
// on the notification
// request.setNotificationClickIntent(new Intent(this, MainActivity.class));
// set the maximum number of automatic upload retries on error
request.setMaxRetries(2);
try {
request.startUpload();
} catch (Exception exc) {
Toast toast = Toast.makeText(getApplicationContext(), "Malformed upload request. " + exc.getLocalizedMessage(), Toast.LENGTH_LONG);
toast.show();
}
}
But the problem is, it will throw null pointer exception, which I don't quite get the reason.
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.isEmpty()' on a null object reference
at com.fyp.mycyberlaw.Lecturer.UploadNotesActivity.onUploadButtonClick(UploadNotesActivity.java:73)
at com.fyp.mycyberlaw.Lecturer.UploadNotesActivity.access$100(UploadNotesActivity.java:19)
at com.fyp.mycyberlaw.Lecturer.UploadNotesActivity$2.onClick(UploadNotesActivity.java:53)
line 73: if (getIntent().getStringExtra("filePath").isEmpty())
line 19: public class UploadNotesActivity extends Activity
line 53: onUploadButtonClick();
Seems like the filePath in line 73 is empty and the way I save filePath into bundle (?) is incorrect. How to get the filePath from onActivityResult? Here's the .java class, just in case. Thank you in advance. Really need your help.
An Intentobject is used to pass params between activities. Ones you receives the file path you must to keep it in your activity.
Create a filePathvariable inside your activity, set it on onActivityResult and read it on onUploadButtonClick.
Notice that must save variable value during the onSaveInstanceState callback and restore it in onCreate because every time you turn your phone the activity is destroyed and recreated. Check this for more information: Recreating an Activity
I'm trying to pass a string from another activity to this one and then send it into an array and then into a listview. whenever i run this i get "Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference"
it seems like the error has something to do with the fourth line with the 'extras' bundle but how is that a null object reference i defined it right there no?
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
Bundle extras = intent.getExtras();
switch(requestCode) {
case ACTIVITY_EDIT:
String title = extras.getString(add.TITLE);
String password = extras.getString(add.PASSWORD);
adapter.add(title);
break;
}
}
Here's where the 'PASSWORD' and 'TITLE' variables are defined in the other Activity:
public void onClick(View v) {
EditText titleBox = (EditText)findViewById(R.id.titleText);
TITLE = titleBox.getText().toString();
EditText passBox = (EditText)findViewById(R.id.passwdText);
String pass = passBox.getText().toString();
EditText confBox = (EditText)findViewById(R.id.editText3);
String conf = confBox.getText().toString();
if (pass.equals(conf)) {
PASSWORD = pass;
this.finish();
} else {
Toast.makeText(this, "Passwords don't match", Toast.LENGTH_SHORT);
}
}
When you pass data from one activity to another using a Bundle, the data is received inside onCreate() method of the second activity not inside onActivityResult() unless you've specifically implemented that.
Check this answer on how to start another activity and how to pass data to another activity : https://stackoverflow.com/a/20170125/1239966
I'm very new to Android Dev and am having issues trying to get an editText to pull out one contact. I've created 3 editTexts that will take a contact each and will send a SMS to the selected contact(s).
http://imgur.com/IbAT1hX
I've tried several things that I've found online, but they all crash and I don't really understand what I'm doing.
I know that I have to create a onClickListener():
contact.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
The other question that I have is, since I need to select one contact per EditText, do I have to copy the same code for the three EditTexts?
After the contact is selected I would like to display just the name of the contact.
Any help would be appreciated!
You can do like i did in one of my app (I did this on button click you and use your edittext)
Open The contact
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent= new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
});
Then after user select you can get the result in OnActivityResult Method and process the contact uri to load details of contact
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (PICK_CONTACT) :
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// TODO Fetch other Contact details as you want to use
Set the name of contact in your editText
}
}
break;
}
}
I've tested my android app successfully using Paypal Sandbox environment. I am about to release my app, so want to change the paypal configuration to 'PRODUCTION'
To do this, I've changed the following for production:
private static final String CONFIG_ENVIRONMENT = PaymentActivity.ENVIRONMENT_PRODUCTION;
private static final String CONFIG_CLIENT_ID = "my client id for production";
private static final String CONFIG_RECEIVER_EMAIL = "live-id#gmail.com";
Now when I try to make a payment using my another paypal account, I am getting error:
Login Failed
System error. Please try again later.
Same thing happens using the emulator with production settings.
My question is do I have to make any other changes to move from sandbox to production env?
Thanks
UPDATE 1
All the above settings are for the 'production' environment.
Using direct payment
I've noticed problems using paypal from my app when I name the String before onCreate so what I did was..
//When you want to initiate payment...
public void onBuyPressed(View pressed) {
PayPalPayment thingToBuy = new PayPalPayment(new BigDecimal(valuez), "USD", iu);
PaymentActivity.ENVIRONMENT_LIVE);//etc
I dont know if "PRODUCTION" or "LIVE" makes a difference but give it a try.
I'm going to add more hope this helps this is what i did
get rid of all those paypal strings before onCreate and just when they get ready to pay have textbox with onClick is onBuyPressed...
public void onBuyPressed(View pressed) {
TextView inptP =(TextView)findViewById(R.id.WHATHEYAREBUYING);
String iu =inptP.getText().toString();
TextView inptt =(TextView)findViewById(R.id.WHATITCOST);
String it =inptt.getText().toString();
try{
double valuez =Double.parseDouble(it);
if(valuez> 0)
{
PayPalPayment thingToBuy = new PayPalPayment(new BigDecimal(valuez), "USD", iu);
Intent intent = new Intent(this, PaymentActivity.class);
TextView id =(TextView)findViewById(R.id.MYPAYPALID);
String uname = id.getText().toString();
TextView iz =(TextView)findViewById(R.id.MYPAYPALEMAIL);
String insane = iz.getText().toString();
TextView name =(TextView)findViewById(R.id.MYCUSTOMERSNAME);
String custname = name.getText().toString();
Time now = new Time();
now.setToNow();
// comment this line out for live or set to PaymentActivity.ENVIRONMENT_SANDBOX for sandbox
intent.putExtra(PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT, PaymentActivity.ENVIRONMENT_LIVE);
// it's important to repeat the clientId here so that the SDK has it if Android restarts your
// app midway through the payment UI flow.
intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, uname);
// Provide a payerId that uniquely identifies a user within the scope of your system,
// such as an email address or user ID.
intent.putExtra(PaymentActivity.EXTRA_PAYER_ID, custname);
intent.putExtra(PaymentActivity.EXTRA_RECEIVER_EMAIL, insane);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
startActivityForResult(intent, 0);
}
else{
Toast.makeText(getApplicationContext(), "You haven't entered anything.",
Toast.LENGTH_LONG).show();
}} catch (NumberFormatException e) {
}}
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
//THINGS YOU WANT IT TO WHEN THE PAYMENT IS FINISHED GO BETWEEN HERE
//AND HERE
if (confirm != null) {
try {
Log.i("paymentExample", confirm.toJSONObject().toString(4));
// TODO: send 'confirm' to your server for verification.
// see https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
// for more details.
} catch (JSONException e) {
Log.e("paymentExample", "an extremely unlikely failure occurred: ", e);
}
}
}
else if (resultCode == Activity.RESULT_CANCELED) {
Log.i("paymentExample", "The user canceled.");
}
else if (resultCode == PaymentActivity.RESULT_PAYMENT_INVALID) {
Log.i("paymentExample", "An invalid payment was submitted. Please see the docs.");
}}
No need to put PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT for live.
This is my code which is working fine.
Declare these constants is class scope. NOTE: There are two client ids in page of your application in developer Paypal. One in "Test credentials" and The other under "Live credentials" that you should click on "show" link in order to see it. Select client id of "Live credentials" if you want to release your application.
private static final String PAYPAL_CLIENT_ID = "YOUR-CLIENT-IT";
private static final String PAYPAL_RECEIVER_EMAIL = "YOUR-EMAIL";
Then define service in onCreate():
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// start Paypal service
Intent intent = new Intent(this, PayPalService.class);
// live: don't put any environment extra
// sandbox: use PaymentActivity.ENVIRONMENT_SANDBOX
intent.putExtra(PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT, PaymentActivity.ENVIRONMENT_PRODUCTION);
intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, PAYPAL_CLIENT_ID);
startService(intent);
}
When user hit a button following method will run:
private void openDonateBtnPressed(BigDecimal donation) {
PayPalPayment payment = new PayPalPayment(donation, "USD", "Donation");
Intent intent = new Intent(this, PaymentActivity.class);
// comment this line out for live or set to PaymentActivity.ENVIRONMENT_SANDBOX for sandbox
intent.putExtra(PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT, PaymentActivity.ENVIRONMENT_PRODUCTION);
// it's important to repeat the clientId here so that the SDK has it if Android restarts your
// app midway through the payment UI flow.
intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, PAYPAL_CLIENT_ID);
// Provide a payerId that uniquely identifies a user within the scope of your system,
// such as an email address or user ID.
intent.putExtra(PaymentActivity.EXTRA_PAYER_ID, "<someuser#somedomain.com>");
intent.putExtra(PaymentActivity.EXTRA_RECEIVER_EMAIL, PAYPAL_RECEIVER_EMAIL);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payment);
startActivityForResult(intent, 0);
}
and this is onActivityResult():
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
Toast.makeText(RateTheAppActivity.this, R.string.rate_donation_received, Toast.LENGTH_LONG).show();
Log.d(TAG, confirm.toJSONObject().toString(4));
} catch (JSONException e) {
Log.e(TAG, "an extremely unlikely failure occurred: ", e);
}
}
}
else if (resultCode == Activity.RESULT_CANCELED) {
Log.d(TAG, "The user canceled.");
}
else if (resultCode == PaymentActivity.RESULT_PAYMENT_INVALID) {
Log.e(TAG, "An invalid payment was submitted. Please see the docs.");
}
}