Putextra keep sending the first entered data - java

This is the function which is used to send data to the Main activity.
public void sendData(){
String name = Bookname.getText().toString();
String number = Integer.parseInt(Bookpage.getText().toString());
String description = Booknote.getText().toString();
Intent back = new Intent(getApplicationContext(),MainActivity.class);
back.putExtra("Bookname",name);
back.putExtra("Booknote",description);
back.putExtra("number",number);
setResult(RESULT_OK, back);
finish();
}
This is where I used the function.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.Color_picker){
Toast.makeText(this, "ColoRS", Toast.LENGTH_SHORT).show();
}
if(item.getItemId() == R.id.Check_icon){
sendData();
}
return true;
}
}
This is how I get the strings in the Main Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
Ref c1 = new Ref(data.getStringExtra("Bookname"), data.getStringExtra("Booknote"),data.getIntExtra("number",0),data.getIntExtra("color", Color.RED));
adapter.add(c1);
}
}
My problem is that the data are only written once and when the function should be sending different data it sends the same data as the first entered data.

If you send your activityOnResult with 1 as REQUEST_CODE is OK
The only problem I guess you are having (I do not have much more information) is since I see and adapter, I guess you should call adapter.notifyDataSetChanged() to see changes on your "list"?
Also you can "clear" the intent, to avoid duplicated stuff, every time you go to onActivityResult() you can do this getIntent().removeExtra("key"); to ensure, next time will come different data.
If you do this, you have to do the other logic good to work with this...

Related

Activity intent child doesn't return data to parent, toast is not shown

Greetings fellow programmers,
I have been having some issues with understanding why my child's intent doesn't return the proper value to my parent's intent properly.
private static final int REQUEST_CODE_CHEAT = 0;
Now here is how I call my explicit intent
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isTrue = mStatements[mStatementIndex].isAnswerTrue();
Intent intent = SubActivity.newIntent(MainActivity.this, isTrue);
startActivityForResult(intent, REQUEST_CODE_CHEAT);
}
});
This is the code for the SubActivity that creates the interfacing Intent
public static Intent newIntent(Context packageContext, boolean answerIsTrue){
Intent intent = new Intent(packageContext, SubActivity.class);
intent.putExtra(EXTRA_ANSWER_SHOWN, answerIsTrue);
return intent;
}
Also, have the following keys to keep track of what goes where
private static final String EXTRA_ANSWER_IS_TRUE = "com.tsourtzis.android.test.answer_is_true";
private static final String EXTRA_ANSWER_SHOWN = "com.tsourtzis.android.test.answer_shown";
Finally some methods to be certain what values are passed
private void setAnswerShownResult(boolean isAnswerShown){
Intent data = new Intent();
data.putExtra(EXTRA_ANSWER_IS_TRUE, isAnswerShown);
setResult(RESULT_OK, data);
}
Here I'm sending back the intent to the MainActivity with setResult();
public static boolean wasAnswerShown(Intent result){
return result.getBooleanExtra(EXTRA_ANSWER_SHOWN, false);
}
Moreover, I have this method here to evaluate the result, but checking first if the user has created it.
public void evaluateStatement(boolean userChoice){
boolean statementValue = mStatements[mStatementIndex].isAnswerTrue();
int textResId = 0;
if(mBoolResult){
textResId = R.string.judgment_toast;
}else{
if(userChoice == statementValue){
textResId = R.string.correct_toast;
}else{
textResId = R.string.incorrect_toast;
}
}
Toast.makeText(this, textResId, Toast.LENGTH_SHORT).show();
}
Notice, I have stated the following my MainActivity after using setResult(...) and a field value for keeping the boolean result from the Sub activity.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(resultCode != Activity.RESULT_OK){
return;
}
if(requestCode == REQUEST_CODE_CHEAT){
if(data == null){
return;
}
mBoolResult = SubActivity.wasAnswerShown(data);
}
}
Finally just to be clear, here is the field that I have in MainActivity.
private boolean mBoolResult;
I'm not looking for any code answer, I just want to understand why it doesn't work. Thank you!
Do you finish() your SubActivity ?
Seeing that the Toast should be shown any time the method evaluateStatement is called, I guess onActivityResult doesn't dispatch the call to it.
Can you explicit where is the onActivityResult you show last? It's unclear since it's calling CheatActivity#wasAnswerShown() as if it is not in CheatActivity (MainActivity?)

startActivityForResult: finish() returning to wrong activity

So I have 3 activities: MainActivity, AddEntryActivity, and CategoryActivity. I want to use startActivityForResult from Main -> AddEntry, and then AddEntry -> Category and have the data from Category passed back to AddEntry where it's used as a field in the Entry object result I'm sending back to Main. The problem is, when I call finish() in AddEntryActivity (after returning from CategoryActivity), CategoryActivity opens again. I think it may be a problem with the intents/contexts but I'm new to android dev so I can't figure out what the problem is. Any help would be appreciated!
I am currently calling startActivityForResult() from MainActivity (on button press) to get to AddEntry.
case R.id.addEntryButton:
Intent in = new Intent(this, AddEntryActivity.class);
startActivityForResult(in, 111);
break;
Then from AddEntryActivity, I call another startActivityForResult to get to CategoryActivity (on button press again).
case R.id.chooseCategory:
Intent catAct = new Intent(this, CategoryActivity.class);
startActivityForResult(catAct, 222);
break;
From CategoryActivity, the user can choose a category and it's sent back to AddEntryActivity (I've checked that this works).
In CategoryActivity:
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Intent i = getIntent();
String category = (String) getListAdapter().getItem(position);
i.putExtra("Category", category);
setResult(RESULT_OK, i);
finish();
}
In AddEntryActivity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 222 && resultCode == RESULT_OK) {
String cat = data.getStringExtra("Category");
category.setText(cat);
categoryString = cat;
}
}
Then, in AddEntryActivity, when the confirm button is pressed I want to return to MainActivity with a new Entry object containing the category field that was returned from CategoryActivity. So I have this:
case R.id.confirmEntryButton:
Entry entry = new Entry(descString, amountString, date.getText().toString(), categoryString);
Intent main = new Intent(this, MainActivity.class);
main.putExtra("newEntry", entry);
setResult(RESULT_OK, main);
finish();
The problem is, when the confirm button is pressed, the CategoryActivity screen pops up again. The weird thing is, the onActivityResult method in MainActivity (below) actually runs as when you close the CategoryActivity screen via the back button, you can see that the entry object has been added so I can't seem to figure out what's causing the category screen to pop up.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 111 && resultCode == RESULT_OK) {
Entry entry = data.getParcelableExtra("newEntry");
entries.add(entry);
entryListView.setAdapter(eAdapter);
}
}
Check your switch case statement to make sure it isn't missing a break and falling through to the next part.

Why am I getting a null pointer exception when passing an ArrayList of strings from one activity to another?

I am trying to get an arraylist in ScanLocate activity from an UpdateLocation activity.
I'm using startActivityForResult method to call the scan method which populates the ArrayList wifiList, I then want to send the ArrayList to the Update Location class.
I start by calling startActivityForResult in Update Location:
private void getScan(){
//Create an intent to start ScanLocate
final Intent i = new Intent(this, ScanLocate.class);
//Start scanLocate with request code
startActivityForResult(i, REQUEST_READINGS);
}
Next, in ScanLocate I created the sendData method (note: the check confirms that the ArrayList data is intact at that point):
private void sendData(){
//create a new intent as container for the result
final Intent readings = new Intent(this, UpdateLocation.class);
//check that data is in wifiList
for(String s:wifiList){
Log.v(TAG,"List Items: " + s);
}
//create bundle for string array
Bundle b = new Bundle();
b.putStringArrayList(key, wifiList);
//add readings to send to updateLoc
readings.putExtras(b);
//set code to indicate success and attach Intent
setResult(RESULT_OK, readings);
//call finish to return
finish();
}
The final part is back in UpdateLocation with the onActivityResult:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent readings){
super.onActivityResult(requestCode, resultCode, readings);
//check if request code matches the one set above
if(requestCode == REQUEST_READINGS){
//check if sendData() in ScanLocate was successful
if(resultCode == RESULT_OK){
//get the readings from the Intent
Log.v(TAG, "HERE");
result = getIntent().getExtras().getStringArrayList(ScanLocate.key);
Log.v(TAG, "HERE2");
for(String s : result) {
Log.v(TAG, "Location 5: " + s);
}
}else{
//ScanLocate was unsuccessful
}
}
}
The first "Here" is displayed however it then falls down on the next line, getStringArrayList() throws a null pointer exception.
I have looked through the documentation and at previous questions on here and I cannot see what is going wrong.
Any advice would be appreciated, thanks.
Previous questions:
startactivityforResult not working
How to pass an ArrayList to the StartActivityForResult activity
You don't need to call getIntent(), use the parameter provided by the method:
result = readings.getStringArrayListExtra(ScanLocate.key);

Android - Get result from change default SMS app dialog

I am working on restoring SMS on KITKAT. Referring to this article I have added the things which are required to set my app as default app for SMS. After adding all required things in manifest file I have write the following code:
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
mDefaultSmsApp = Telephony.Sms.getDefaultSmsPackage(mContext);
Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, mContext.getPackageName());
mContext.startActivity(intent);
}
The above code shows this dialog but I am unable to get the result from this activity/dialog either user clicked on Yes or No because I want to add listener or get any code which should represent that the user clicked on these buttons.
Thanks.
One way to do this is to fire the Intent with startActivityForResult(), and then check the resultCode in the onActivityResult() method. Please note that I've changed the code in the example to run in an Activity's Context.
private static final int DEF_SMS_REQ = 0;
private String mDefaultSmsApp;
...
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
mDefaultSmsApp = Telephony.Sms.getDefaultSmsPackage(this);
if (!getPackageName().equals(mDefaultSmsApp))
{
Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, getPackageName());
startActivityForResult(intent, DEF_SMS_REQ);
}
}
...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch (requestCode)
{
case DEF_SMS_REQ:
boolean isDefault = resultCode == Activity.RESULT_OK;
...
}
}
As mentioned in a comment below, apparently checking the result code is not 100% reliable. A safer check is to simply compare your app's package name to the current default in onActivityResult(). There's no need to check the result code at all, like the answer linked in the comment shows.
String currentDefault = Sms.getDefaultSmsPackage(this);
boolean isDefault = getPackageName().equals(currentDefault);
The way you can react on "yes" button click:
private String mDefSmsPackage;
#Override
public void onCreate(#Nullable Bundle state) {
//...
mDefSmsPackage = Telephony.Sms.getDefaultSmsPackage(getActivity())
}
#Override
public void onResume() {
super.onResume();
String newDefSmsPkg = Telephony.Sms.getDefaultSmsPackage(getActivity());
if (!TextUtils.equals(mDefSmsPackage, newDefSmsPkg)) {
mDefSmsPackage = newDefSmsPkg;
//ON DEF SMS APP CAHNGE...
}
}

onActivityResult() Does not get called?

I have an MainActivity which has two TextView. User has an option to start another activity and choose data from ListView to fill those TextView. My main activity has an OnClickListener which starts an Activty from which user can select data and come back to main activity.My OnClickListener code looks likes this:
private static final int PICK_START = 0;
private static final int PICK_END = 1;
#Override
public void onClick(View v) {
Log.i(MainActivity, "view clicked");
int id = v.getId();
if (id == R.id.searchR) {
//do nothing
} else if (id == R.id.startSearch) {
Intent startIntent = new Intent(this, SList.class);
startActivityForResult(startIntent, PICK_START);
} else if (id == R.id.endSearch) {
Intent startIntent = new Intent(this, SList.class);
startActivityForResult(startIntent, PICK_END);
}
}
When the above onClick method gets called and after that its starts another activity SList.class.In that I have a listview from which user can select the value and upon selecting value the result will be set and activity will finish itself.Code for this is:
sListview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Station selectedS = sArray.get(position);
Intent returnIntent = new Intent();
returnIntent.putExtra("_id", selectedS.getId());
returnIntent.putExtra("name", selectedS.getName());
setResult(RESULT_OK, returnIntent);
finish();
}
});
In above code activity sets the result and finishes itself.Till here everything is working accordingly.But after that when the previous activity is started, the onActivityResult() method nevers gets called.The code for onActivityResult() is :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(MainActivity, "" + requestCode);
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// Check which request we're responding to
if (requestCode == PICK_START) {
//data.getStringExtra("_id");
Log.i(MainActivity, data.getStringExtra("name"));
} else if (requestCode == PICK_END) {
Log.i(MainActivity, data.getStringExtra("name"));
}
}
}
I dont know why onActivityResult is never triggered .Someone even
wrote on his blog that There is bug in android API. In
startActivityForResult(intent, requestCode); This function does work
as long as requestCode = 0. However, if you change the request code to
anything other than zero, the ApiDemos will fail (and onActivityResult()
won't be called).
I found the solution to my problem.I just needed to restart my eclipse and my code started working.

Categories