I have a buttonClickListener that is intended to uninstall multiple apps so I've run a for loop for that and I want to start onActivityResult after the completion of all uninstallation process. SO far onActivityResult runs after each uninstallation. I want only one onActivityResult at the end. Is there any way I can do that?
btnSelection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < appList.size(); i++) {
AllApps singleApp= appList.get(i);
if (singleApp.isSelected()) {
String app_pkg_name = singleApp.getPackageName();
Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
intent.setData(Uri.parse("package:" + app_pkg_name));
intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
startActivityForResult(intent, UNINSTALL_REQUEST_CODE);
}
}
}
});
And this is the onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==UNINSTALL_REQUEST_CODE){
//things to do
}
}
First , is not possible but you can just simply execute onActivityResult for the last command and in order to do that, you need to have a filtered list first
btnSelection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// filter selected apps
List<AllApps> temp = new ArrayList<>();
for(AllApps app : appList){
if(app.isSelected())
temp.add(app);
}
// invoke app uninstallations
for (int i = 0; i < temp.size()-1; i++) {
startActivity(uninstallAppIntent(temp.get(i)));
}
// invoke get result for last entry
startActivityForResult(uninstallAppIntent(temp.get(temp.size()-1)), UNINSTALL_REQUEST_CODE);
}
});
// to avoid code duplicity
Intent uninstallAppIntent(Allapps singleApp){
String app_pkg_name = singleApp.getPackageName();
Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
intent.setData(Uri.parse("package:" + app_pkg_name));
intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
return intent;
}
One possible solution:
You can put variable i on data of intent and check if i==app.size() on onActivityResult.
Its A Simple use case of a If statement . you can take a boolean or just check appropriate condition. Checkout the code below .
btnSelection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AllApps singleApp=null;
for (int i = 0; i < appList.size(); i++) {
if (appList.get(i).isSelected()) {
singleApp=appList.get(i);
}
}
if(singleApp!=null){
String app_pkg_name = singleApp.getPackageName();
Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
intent.setData(Uri.parse("package:" + app_pkg_name));
intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
startActivityForResult(intent, UNINSTALL_REQUEST_CODE);
}
}
});
NOTE IF appList contains multiple selected items then the last indexed item will be used . In this case if you want first selected item the you should break the loop .
Related
I'm trying to use onActivityResult to send a title, I've looked at the google implementation for the same task but it doesn't work me. Can someone help?
code for onActivityResult in mainActivity.
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
System.out.println("There is something coming to this function" + requestCode);
if(requestCode == NEW_TITLE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK){
Title title = new Title(data.getStringExtra(notesSection.EXTRA_REPLY));
mTitleViewModel.insert(title);
}else{
Toast.makeText(getApplicationContext(), R.string.empty_not_saved, Toast.LENGTH_LONG).show();
}
}
code in my notesSection activity.
finishFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// System.out.println("Button Has Been Clicked From Notes Section");
Intent replyIntent = new Intent();
if (TextUtils.isEmpty(titleEdit.getText())){
// System.out.println("Empty?");
setResult(RESULT_CANCELED, replyIntent);
}else{
// System.out.println("Sending Something Supposedly");
String title = titleEdit.getText().toString();
// System.out.println("Sending " + title);
replyIntent.putExtra(EXTRA_REPLY, title);
setResult(RESULT_OK, replyIntent);
}
finish();
// startActivity(new Intent(notesSection.this, MainActivity.class));
}
});
FYI: When I print something in the onActivityResult function, nothing shows up on my run terminal, I don't know why this is, but I don't think the function is being reached for some reason. I will send more code if necessary.
Thanks.
In your first activity try starting second activity like this
static int NEW_TITLE_ACTIVITY_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
---
---
---
// i assume you are starting activity on some button click
// so add following line in you button on click event
startActivityForResult(new Intent(MainActivity.this,notesSection.class),NEW_TITLE_ACTIVITY_REQUEST_CODE);
}
then override following method in your FIRST ACTIVITY
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == NEW_TITLE_ACTIVITY_REQUEST_CODE)
{
// do whatever you want
}
}
Also update your finish fab on click listener
finishFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent replyIntent = new Intent();
if (TextUtils.isEmpty(titleEdit.getText())){
setResult(RESULT_CANCELED, replyIntent);
}
else{
replyIntent.putExtra("TITLE", titleEdit.getText().toString());
setResult(RESULT_OK, replyIntent);
}
finish();
}
});
Actually, this procedure has changed recently. You might want to take a look at the official documentation so that you can implement it according to your needs.
I am trying to pass Bundle from second activity to the first(launch) activity. In order not to get NPE on launch, I am checking if bundle != null, however, it looks, like even after returning from second activity with Bundle, it still doesn't run the "if" body.
Here is my part of code of first activity
Bundle bundle = getIntent().getExtras();
if (bundle!=null) {
Player player = new Player();
player.setStatus(bundle.getInt("Status"));
player.setName(bundle.getString("Name"));
addPlayerToList(player);
Log.e("Player with a name " + player.getName(), "Has been created");
}
And code of second activity
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = nameEditText.getText().toString();
if (defaultRadioButton.isChecked()) {
status=0;
} else if (driverRadioButton.isChecked()) {
status=1;
} else {
Toast.makeText(getApplicationContext(), "Suka viberi galochku", Toast.LENGTH_SHORT).show();
}
Intent i = new Intent(getApplicationContext(),StartActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("Status",status);
bundle.putString("Name", name);
Log.d("Object " + name, "Status: " + status);
startActivity(i);
}
});
Thanks for any help/advice
Use startActivityForResult() for this situation.
1) You open second activity from the first using this method, not startActivity()
2) Do whatever you want in the second activity
3) Set result bundle
4) Finish activity
5) Open bundle in the first activity
In your case it will look like:
1) Call second activity like this:
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, REQUEST_SECOND_ACTIVITY); // request code const
2-4)
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = nameEditText.getText().toString();
if (defaultRadioButton.isChecked()) {
status=0;
} else if (driverRadioButton.isChecked()) {
status=1;
} else {
Toast.makeText(getApplicationContext(), "Suka viberi galochku", Toast.LENGTH_SHORT).show();
}
final Intent returnIntent = new Intent();
returnIntent.putExtra("Status", status); // set values
returnIntent.putExtra("Name", name);
setResult(Activity.RESULT_OK, returnIntent); // set result code
finish(); // finish this activity and go back to the previous one
}
});
5) Override this method in the first activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case REQUEST_SECOND_ACTIVITY: // same request code const
if(resultCode == Activity.RESULT_OK){
Player player = new Player();
player.setStatus(data.getIntExtra("Status"));
player.setName(data.getStringExtra("Name"));
addPlayerToList(player);
}
break;
}
}
try Intent.putExtra() instead of putting data into a bundle, and use Intent.getStringExtra() to get a String data;
In your code, there is no code to put your bundle into intent. actually you never pass the bundle to first activity. you can use this answer to solve your problem.
good luck!
I have activity A where it has a ADD button when I click on the button it displays the list of users with check boxes in Second Activity and when I select the users and click the conform button it should display in all the users Activity A.I am using adapter to display the users.
from this button I am getting the list of checked values
private void checkButtonClick()
{
conform = (Button)findViewById(R.id.Confirm);
conform.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
StringBuffer responseText = new StringBuffer();
responseText.append("The following were selected...\n");
ArrayList<Namelist> stateList = contactadapteruser.listexample;
Bundle b=null;
Namelist state;
for(int i=0;i<stateList.size();i++)
{
state = stateList.get(i);
b = new Bundle();
b.putString("selected",state.getName());
if(state.isSelected())
{
responseText.append("\n" + state.getName());
}
}
Intent i= new Intent(Contactselectuser.this,Contactrepresentativedetails.class);
i.putExtras(b);
startActivity(i);
}
});
}
from this button I am getting the I am retrieving the values
send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i2 = getIntent();
Bundle b1 = i2.getExtras();
String name1 = b1.getString("selected");
tweet.setText(name1+",\t");
}
});
My problem I am unable to get the users which are checked.
Can any one help me .
use start activity for result to start your second activity.
Intent intent = new Intent(this, SecondActivity.class);
startActivityForResult(intent, 1);
from second activity before closing you can send
Intent return_intent = new Intent();
return_intent.putExtra("your_user_list",user_list);
setResult(RESULT_CODE,return_intent);
finish();
Now in your FirstActivity override onActivityResult() method
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_CODE){
// GET YOUR USER LIST HERE AND USE IT FOR YOUR PURPOSE.
user_list=data.getExtra("your_user_list");
}
}
}
You can use broadcast sender and receiver also for your case. But above method is good for your task.
ArrayList<Namelist> stateList = contactadapteruser.listexample;
// convert your ArrayList to a String[]
String[] arr = new String[stateList.size()];
for (int i = 0; i < arr.length; i++)
{
arr[i] = stateList.get(i).getName();
}
Then using this question as a source, put the String array in your intent:
Bundle b = new Bundle();
b.putStringArray("selected", arr);
Intent i = new Intent(Contactselectuser.this,Contactrepresentativedetails.class);
i.putExtras(b);
startActivity(i);
Then to read the String array from your other activity:
Bundle b = getIntent().getExtras();
String[] array = b.getStringArray("selected");
Picture 1. This is my create_layout.
Picture 2. This is my custom contact list when I clicked on add member button.
Picture 3. NOW HERE IS THE PROBLEM. When press on the select button. I wanted to list the chosen contact value back to my first image layout. But it is opening a duplicate of my first layout and appearing there.
Here is my code.
#Override
public void onClick(View v) {
StringBuilder checkedcontacts= new StringBuilder();
System.out.println("............"+ma.mCheckStates.size());
for(int i = 0; i < name1.size(); i++)
{
if(ma.mCheckStates.get(i)==true)
{
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");
}
else
{
System.out.println("..Not Checked......"+name1.get(i).toString());
}
}
Intent i = new Intent (getApplicationContext(), CreateTab.class);
i.putExtra("str",checkedcontacts.toString());
startActivity(i);
finish();
}
});
I know the problem is that I make an intent so that when user clicks on select button, it will point back to CreateTab class which will repeat the onCreate. But how can I prevent from the onCreate again?
you should you use onActivityResult() method to read the returned result.
Do this in your CreateTab.class
Intent i = new Intent(getApplicationContext(), AddMember.class);
startActivityForResult(i, 100); // 100 is some code to identify the returning result
Method to read the result from newly created activity
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == 100){
String str = data.getExtras().get("str");
}
}
Send result back to old activity when StartActivityForResult() is used
Intent i = new Intent();
i.putExtra("str", checkedcontacts.toString());
// Setting resultCode to 100 to identify on old activity
setResult(100,i);
and close your AddMember activity
finish()
so your click event should look like this;
#Override
public void onClick(View v) {
StringBuilder checkedcontacts= new StringBuilder();
System.out.println("............"+ma.mCheckStates.size());
for(int i = 0; i < name1.size(); i++)
{
if(ma.mCheckStates.get(i)==true)
{
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");
}
else
{
System.out.println("..Not Checked......"+name1.get(i).toString());
}
}
Intent i = new Intent();
i.putExtra("str", checkedcontacts.toString());
// Setting resultCode to 100 to identify on old activity
setResult(100,i);
finish();
}
});
http://developer.android.com/training/basics/intents/result.html
Don't start previous activity again, just update selector Activity's result, and call finish().
Intent resultIntent = new Intent(this, PreviousActivity.class);
resultIntent.putExtra("selection",checkedcontacts.toString());
setResult(RESULT_OK,resultIntent);
finish();
I have a fragment that uses an intent to uninstall an app when they click uninstall.
View.OnClickListener removeButtonClick = new View.OnClickListener() {
#Override
public void onClick(View paramView) {
PackageManager pm = ContextProvider.getContext().getPackageManager();
Intent intent = new Intent(Intent.ACTION_DELETE, Uri.fromParts("package",
app.packageName, null));
int result = 0;
startActivityForResult(intent, result);
}
};
When the activity finishes it successfully calls:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
new MainActivity.UpdateDatabase().execute(); // update database
ContextProvider.getContext().getFragmentManager().popBackStack(); // go back
}
But requestCode & resultCode are 0 and data is null regardless of whether the user pressed uninstall or cancel. How can I find out what they chose?
This is what I ended up doing:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Boolean found = false;
PackageManager pm = ContextProvider.getContext().getPackageManager();
List<PackageInfo> packages = pm.getInstalledPackages(0);
for (PackageInfo pi : packages) {
if (pi.packageName.equals(app.packageName)) {
found = true;
break;
}
}
if (!found) { // User uninstalled app so update database and go back
new MainActivity.UpdateDatabase().execute();
goBack();
}
}
Don't know how to do that, but could you just use the package manager to see it package is still there or not?