I'm trying to send 2 parameter from one activity to another,but for some reason only one of the parameter is passed. what could it be?
Sending Activity:
showActivity(OrderActivity.class, new Pair("CUSTOMER_ID", customerId), new Pair("CUSTOMER_TYPE", customerType));
Receiving Activity : The customer id is showing 0 but the type data is got
Bundle extras = getIntent().getExtras();
long customerId = extras.getLong("CUSTOMER_ID");
int customerType = extras.getInt("CUSTOMER_TYPE");
Log.d("===customer ", " id : " + customerId + " type : " + customerType);
the showActivity looks like this
protected void showActivity(Class<? extends BaseKaizenActivity> clazz, Pair<String, Object> ... parameters) {
Intent intent = new Intent(this, clazz);
if (parameters != null) {
for (Pair<String, Object> pair : parameters) {
if (pair.second instanceof Integer) {
intent.putExtra(pair.first, (Integer)pair.second);
}
else if (pair.second instanceof Parcelable) {
intent.putExtra(pair.first, (Parcelable)pair.second);
}
}
}
startActivity(intent);
}
if (pair.second instanceof Integer) {
intent.putExtra(pair.first, (Integer)pair.second);
}
else if (pair.second instanceof Parcelable) {
intent.putExtra(pair.first, (Parcelable)pair.second);
}
Seems like you fogot to write a clause for Long.It gose neither of if nor else if,so has not been put into extradata.
why are u using that? just use put and get method of intent its very simple.eg.
intent.putExtra("backPressed", true);
getIntent().getBooleanExtra("backPressed", false);
this is my working code and got no problem.
Related
I am trying to learn work manager chaining with passing output of one to another
Here are my objectives,
I have two work request WR1 (gets me the url) and WR2 (sends request to the url)
I can't and should not start the WR2 until the WR1 completes.
WR1 is supposed to return a url to which i have to send to WR2 as inputData
I can mostly do this without chaining. But i would to like explore it in the chaining.
Here is my snippet in progress. Please help.
WorkManager mWorkManager = WorkManager.getInstance(this);
//WR1
OneTimeWorkRequest urlRequest = new
OneTimeWorkRequest.Builder(UriResolveWorker.class).build();
//WR2
OneTimeWorkRequest pullRequest = new
OneTimeWorkRequest.Builder(PullReplicator.class).build();
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mWorkManager.beginWith(urlRequest)
.then(pullRequest) // I should be able to pass the result of urlRequest.
.enqueue();
}
});
mWorkManager.getWorkInfoByIdLiveData(urlRequest.getId()).observe(this, new
Observer<WorkInfo>() {
#Override
public void onChanged(WorkInfo workInfo) {
if (workInfo != null) {
WorkInfo.State state = workInfo.getState();
// I will get the URL here and i want to pass this to WR2
message = workInfo.getOutputData().getString("work_result");
tvStatus.append("\n"+"state : "+state.toString() + "message : " +message + "\n");
}
}
});
mWorkManager.getWorkInfoByIdLiveData(pullRequest.getId()).observe(this, new Observer<WorkInfo>() {
#Override
public void onChanged(WorkInfo workInfo) {
if (workInfo != null) {
WorkInfo.State state = workInfo.getState();
String count = workInfo.getOutputData().getString("work_result");
tvStatus.append("\n"+"state : "+state.toString() + " No of Documents : " +count + "\n");o
}
}
});
Before returning the Result object in doWork() method of UriResolveWorker class, You can pass the url to Result.success().
First create object of Data.Builder() and then put the url into:
Data.Builder outputDataBuilder = Data.Builder();
outputDataBuilder.putString(KEY_URL_STRING, url.toString());
after that, create Data object with outputDataBuilder:
Data outputData = outputDataBuilder.build();
now you can return the Result with outputData :
return Result.success(outputData);
Workmanager sends the data to pullRequest when the first one has been done.
Please check the state of the WorkRequest before getting the data.
For example:
private final Observer<WorkInfo> urlWorkInfo = workInfo -> {
if (workInfo == null) {
return;
}
WorkInfo.State state = workInfo.getState();
if (state.isFinished()) {
String url = workInfo.getOutputData()
.getString(KEY_URL)
if (url != null) {
Log.d(TAG_MAIN_ACTIVITY, url);
} else {
Log.d(TAG_MAIN_ACTIVITY, "Url not found!");
}
} else if (state == WorkInfo.State.RUNNING) {
Log.d(TAG_MAIN_ACTIVITY, "Associated WorkRequest is being executed");
}
};
I know it's been a while since you asked this question, but maybe it might help someone in the feature:
In WR1 (Worker 1) you will have output with specific key - data that you want in your second worker (WR2):
Result.success(workDataOf(MY_TEST_KEY to someData.toString()))
Now if you want to get that data in WR2 you cannot send it trough setInputData() method when creating your OneTimeWorkRequest and chaining it.
As everything is forwarded from WR1 to WR2, in WR2 you have to fetch that data like:
inputData.getString(WR1.MY_TEST_KEY)
And than use it as you want in your WR2.
Hopefully this will help someone in the future, official documentation can be found here: https://developer.android.com/topic/libraries/architecture/workmanager/how-to/chain-work
I have constants set up for my Flavor names:
public static final String FLAVOR_NAME_PRO = "pro";
public static final String FLAVOR_NAME_FREE = "free";
Inside my Activity's onCreate() I assign the boolean mUsingProFlavor a value:
mUsingProFlavor = BuildConfig.FLAVOR.equals(FLAVOR_NAME_PRO);
In a clickListener created later on I have this:
if (mUsingProFlavor) {
customerId = getCustomerId();
Intent intent = new Intent(MainActivity.this, CustomerProfileActivity.class);
intent.putExtra("customerId", customerId);
startActivity(intent);
} else {
showProOnlyFeatureAlertDialog(MainActivity.this, mAlertDialog);
}
This is the only way for the user to access CustomerProfileActivity, and yet somehow I'm getting crash reports indicating that one of my Free users is crashing inside of CustomerProfileActivity.
Any idea how this could happen?
if (mUsingProFlavor) {
customerId = getCustomerId();
Intent intent = new Intent(MainActivity.this, CustomerProfileActivity.class);
intent.putExtra("customerId", customerId);
startActivity(intent);
} else {
showProOnlyFeatureAlertDialog(MainActivity.this, mAlertDialog);
}
Your -> if(mUsingProFlavor) is the issue here.
Since mUsingProFlavor is a String, you have to modify your if-check. Currently it is acting as boolean.
if (mUsingProFlavor.equals("pro")) {
customerId = getCustomerId();
Intent intent = new Intent(MainActivity.this, CustomerProfileActivity.class);
intent.putExtra("customerId", customerId);
startActivity(intent);
} else {
showProOnlyFeatureAlertDialog(MainActivity.this, mAlertDialog);
}
I was able to pass a string (a sentence) to Google's NLP API (configured in a separate class called NLPService.java) from my Main Activity Class, but I want to be able to return the result (a certain entity string) from the NLPService Class back to my Main Activity for further processing. Is it possible for me to pass the entities string back to my Main Activity? In Android Studio, I have created a NLPService.java with the following code:
//New NLP Model
public void analyzeText(String textToAnalyze) {
Document doc = new Document();
doc.setContent(textToAnalyze)
.setType("PLAIN_TEXT");
final String[] result = new String[1];
if (textToAnalyze != null && !doc.isEmpty()) {
doc.setContent(textToAnalyze);
//Config request to be sent to Google NLP
Features features = new Features();
features.setExtractEntities(true);
final AnnotateTextRequest request = new AnnotateTextRequest();
request.setDocument(doc);
request.setFeatures(features);
AsyncTask.execute(new Runnable() {
public void run() {
try {
returnResponse(NLPService.documents().annotateText(request).execute());
result[0] = returnResponse(NLPService.documents().annotateText(request).execute());
Log.i("getAsyncResponse", "RESULT: " + result[0]);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
public String returnResponse(AnnotateTextResponse response) {
final List<Entity> entityList = response.getEntities();
String entities = "";
for (Entity entity : entityList) {
entities += "\n" + entity.getName().toUpperCase() + " " + entity.getType();
}
return entities;
}
`
The common approach will be using Broadcast (LocalBroadcastManager) to pass the data you intended to send from service to any activity.
Example of Previous post
Or you can use SharedPreferences which is unlikely.
I need to pick contacts in my app and would like to exclude those which are stored in my SIM card. Is it possible with ACTION_PICK?
No, it's not possible
Unfortunately, it's not possible for now.
To proof it, let's dive into source code of ContanctsListActivity.
Here's an onCreate() method of the Activity. In it, ContactApp reads Intent(ACTION_PICK) we passing to it and handles it respectively:
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
mIconSize = getResources().getDimensionPixelSize(android.R.dimen.app_icon_size);
mContactsPrefs = new ContactsPreferences(this);
mPhotoLoader = new ContactPhotoLoader(this, R.drawable.ic_contact_list_picture);
// Resolve the intent
final Intent intent = getIntent();
// Allow the title to be set to a custom String using an extra on the intent
String title = intent.getStringExtra(UI.TITLE_EXTRA_KEY);
if (title != null) {
setTitle(title);
}
String action = intent.getAction();
String component = intent.getComponent().getClassName();
// When we get a FILTER_CONTACTS_ACTION, it represents search in the context
// of some other action. Let's retrieve the original action to provide proper
// context for the search queries.
if (UI.FILTER_CONTACTS_ACTION.equals(action)) {
mSearchMode = true;
mShowSearchSnippets = true;
Bundle extras = intent.getExtras();
if (extras != null) {
mInitialFilter = extras.getString(UI.FILTER_TEXT_EXTRA_KEY);
String originalAction =
extras.getString(ContactsSearchManager.ORIGINAL_ACTION_EXTRA_KEY);
if (originalAction != null) {
action = originalAction;
}
String originalComponent =
extras.getString(ContactsSearchManager.ORIGINAL_COMPONENT_EXTRA_KEY);
if (originalComponent != null) {
component = originalComponent;
}
} else {
mInitialFilter = null;
}
}
Log.i(TAG, "Called with action: " + action);
mMode = MODE_UNKNOWN;
if (UI.LIST_DEFAULT.equals(action) || UI.FILTER_CONTACTS_ACTION.equals(action)) {
.....
else if (Intent.ACTION_PICK.equals(action)) {
// XXX These should be showing the data from the URI given in
// the Intent.
final String type = intent.resolveType(this);
if (Contacts.CONTENT_TYPE.equals(type)) {
mMode = MODE_PICK_CONTACT;
} else if (People.CONTENT_TYPE.equals(type)) {
mMode = MODE_LEGACY_PICK_PERSON;
} else if (Phone.CONTENT_TYPE.equals(type)) {
mMode = MODE_PICK_PHONE;
} else if (Phones.CONTENT_TYPE.equals(type)) {
mMode = MODE_LEGACY_PICK_PHONE;
} else if (StructuredPostal.CONTENT_TYPE.equals(type)) {
mMode = MODE_PICK_POSTAL;
} else if (ContactMethods.CONTENT_POSTAL_TYPE.equals(type)) {
mMode = MODE_LEGACY_PICK_POSTAL;
}
....
// VERY LONG IF WITH DIFFERENT MODE-SELECTION
....
}
.....
if (mMode == MODE_JOIN_CONTACT) {
setContentView(R.layout.contacts_list_content_join);
} else if (mSearchMode) {
setContentView(R.layout.contacts_search_content);
} else if (mSearchResultsMode) {
setContentView(R.layout.contacts_list_search_results);
} else {
setContentView(R.layout.contacts_list_content);
}
setupListView();
...
}
It's very long method (and I also suggest to check setupListView() method), but pretty straightforward. And, as you can see, there's no parameter you can pass to specify source of contacts you want to pick from. Only thing you can configure here is the particular mMode ContactsApp to use (MODE_PICK_CONTACT, MODE_PICK_PHONE, etc.) - but unfortunately number of possible modes is very limited by 6 and non of them suits you.
(If anyone needs to pass mMode to ContanctsListActivity - use intent's setType() method, for example: intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);)
Workaround
As a workaround - as tiny sunlight's suggested in comments - render non-SIM contacts within the app and pick the one you needed from there.
How to get all android contacts but without those which are on SIM - this link looks like most promising one explaining how to query cursor with all contacts, apart from SIM ones.
I hope, it helps
I am passing values between two activities and fetching the values like this:
Bundle extras = getIntent().getExtras();
if (extras != null)
{
initialUrl = extras.getString("initialUrl");
isFollow = extras.getString("isFollow");
}
if (isFollow == "true") {
editUrl.setText(initialUrl);
setUpWebView(initialUrl);
} else if (isFollow == "false") {
editUrl.setText("http://www.google.com");
setUpWebView("http://www.google.com");
}
the problem is I can see the values being retrieved in the debug window by adding watch to the variables but when the compiler enters the statement if(isFollow=="true"), the condition fails. The else case is also not dealt with. What else do i need to do to ensure that my if condition is satisfied properly?
You should use
isFollow.equals("true")
in your statements.
If String type of data is put in bundle then Try with the following code
String isFollow = null;
Bundle extras = getIntent().getExtras();
if (extras != null)
{
initialUrl = extras.getString("initialUrl");
isFollow = extras.getString("isFollow");
}
if (isFollow.equals("true")) {
editUrl.setText(initialUrl);
setUpWebView(initialUrl);
} else if (isFollow.equals("false")) {
editUrl.setText("http://www.google.com");
setUpWebView("http://www.google.com");
}
If Boolean type of data is put in bundle then Try with the following code
boolean isFollow = null;
Bundle extras = getIntent().getExtras();
if (extras != null)
{
initialUrl = extras.getString("initialUrl");
isFollow = extras.getBoolean("isFollow");
}
if (isFollow) {
editUrl.setText(initialUrl);
setUpWebView(initialUrl);
} else {
editUrl.setText("http://www.google.com");
setUpWebView("http://www.google.com");
}
You need to test either
isFollow.equals("true") or if it is a boolean and not a string, either
isFollow == true or just plain isFollow
(note the no quotes on the second one)
I know this is a really late answer but it would be better to do this if you are passing a Boolean into the intent from the sender:
Boolean isFollow = extras.getBoolean("isFollow");
if(isFollow) {
//Do stuff
}