First I think I should describe my problem:
I want to do a BluetoothRequest for turning it on, but I don't want to create a new Activity. I want to keep it in the MainActivity and put the code in subclasses. How is this possible? Down is my own idea of how to do it, but it don't works.
I have the MainActivity and a BluetoothActivity. The following code is from BluetoothActivity:
public class Bluetooth extends Fragment{
private Context context;
private TextView textView;
private final int REQUEST_ENABLE_BT = 1;
private String BtName;
private String BtAddress;
private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
public Bluetooth(Context context){
//constructor
this.context=context;
textView = new TextView(this.context);
}
public boolean bluetoothUnterstuetz(){
if(mBluetoothAdapter == null) {
//Device doesn't support Bluetooth
textView.setText("Device doesn't support Bluetooth");
}
return true;
}
public void bluetoothActivate(){
if(mBluetoothAdapter.getState()== BluetoothAdapter.STATE_ON){
textView.setText("Bluetooth already on.");
}
if(!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
((Activity) context).startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
((Activity) context).setContentView(textView);
}
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
textView.setText(resultCode);
Log.i("bluetooth", "called");
((Activity) context).setContentView(textView);
}
With extends Fragment nothing happens, also logcat is empty. With extends Activity, the app crashs after starting.
When I test the App on my Phone, I get the BluetoothRequest and can Choose my answer but afterwards the ContentView shows nothing, also Logcat stays empty
Somebody knows how to get the Result?
Well now it works.
The onActivityResult() has to be in the MainActivity. If I put it into the subclass it won't be called
You have forgotten tag override.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
AndroidStudio tells me the function onActivityResult is never used.
Using the annotation #Override will make this warning to disappear. It is also a good way to check you overrided properly (with the right parameters in the right order) as you will get an error should the override be wrong. Which doesn't look to be the case here if you extended Activity.
When I test the App on my Phone, I get the BluetoothRequest and can Choose my answer but afterwards the ContentView shows nothing.
Are you sure your startActivityForResult() was called and returned a result (ie. didn't call finish() for example)? I'll update my answer according to the details you will provide.
onActivityResult is a protected method of Activity and a public method of Fragment. If ide is warning you that the method is never used is because your class does not extend neither Activity nor Fragment
Related
Fairly new to Android. I've the following scenario:
App starts in Main Activity and here I add a fragment
In that fragment is a listview populated with a custom adapter, I am passing an instance of the FragmentActivity to the adapter.
Call:
ExpandableListAdapter listAdapter new ExpandableListAdapter(mContext, mActivity, listDataHeader, listDataChild);
Implementation:
public ExpandableListAdapter(Context context, FragmentActivity activity, List<String> listDataHeader, HashMap<String, List<String>> listChildData) {
this._context = context;
this._activity = activity;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
When you click an item in the list, it opens a dialog with edittext fields namely: Name, Surname, Cell. I am passing the FragmentActivity to the dialog as the context:
txtListChild.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new SelectContactDialog(_activity);
dialog.show();
}
});
Then when you focus any of the 3 fields a Select contact opens up, I am using the passed FragmentActivity to call startActivityForResult like so:
private class ContactListener extends Activity implements View.OnFocusChangeListener
{
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
_activity.startActivityForResult(intent, CONTACTS_RESULT);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CONTACTS_RESULT && resultCode == RESULT_OK) {
String cell = "?", firstName = "?", lastName = "?";
uriContact = data.getData();
Cursor cursor = null;
mCell.setText(cell);
mLastName.setText(lastName);
mFirstName.setText(firstName);
}
}
}
Everything works fine up until this point. So my problem now is I would like to get the results when a user selects a contact. I tried below but the onActivityResult override method is never called. I've no idea what to do and seems that other people have had a different from mine and their solutions doesn't work for me.
Anyone know what I can do?
I'd recommend to use an interface for this. For example create the interface ContactCallback which you have to implement in your activity. When you create your adapter, pass this (which means the interface). When you click on an item call inside your adapter the passed callback like callback.onContactSelected(). Inside onContactSelected() which is implemented in your activity you can open your dialog.
Update:
To your problem that your onActivityResult() is never called:
Is there a line in your manifest called "android:launchMode="singleTask"? Remove it and it should be called. Following cases can cause an issue with receiving the result:
check you are using startActivityForResult() correctly, do not use startActivity().
if you do something in overriden onBackPressed method, super.onBackPressed(); has to be positioned at the last of the method, not at the first line.
remove android:launchMode="singleInstance" in manifest or equivalent argument to create a intent.
remove noHistory="true" in manifest of the called activity.
check setResult() is missed.
finish() is called to close the activity. use finishActivity() to close called activity.
use requestCode more than zero. negative value does not work.
You need to call this to get your onActivityResult called. on your dialog while your are closing put this code
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();
I am trying to do the following:
Show dialog fragment from an Activity (not Fragment);
Retrieve result in the Activity.
The problem is that onActivityResult in the Activity is not being called.
Here is how I am showing a DialogFragment
DriverRatingDialogFragment dp = new DriverRatingDialogFragment();
// this solution works well in case of showing dialog from a fragment
// but I have to show it from the Activity
// dp.setTargetFragment(getSupportFragmentManager().findFragmentById(R.id.flContent), DriverRatingDialogFragment.REQUEST_CODE);
dp.show(getSupportFragmentManager(), DriverRatingDialogFragment.ARG_RATING);
And here is how I am trying to return result from DialogFragment:
Intent intent = new Intent();
// This solution works well in case of previously setting target Fragment,
// but I have to return result to Activity
// getTargetFragment().onActivityResult(
// getTargetRequestCode(), REQUEST_CODE, intent);
// and with this attempt App crashes
// this.onActivityResult(REQUEST_CODE, Activity.RESULT_OK, intent);
here is where I want to retrieve result in the Activity, but it doesn't get called:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == DriverRatingDialogFragment.REQUEST_CODE) {
// todo
}
super.onActivityResult(requestCode, resultCode, data);
}
What's wrong?
I start the DialogFragment the same way you do.
CreatePostDialog createPostDialog = new CreatePostDialog();
createPostDialog.show(getSupportFragmentManager(), "create_post_dialog");
And I send back data using a public method in the activity rather than with intents.
((MainActivity)mContext).logout(Utils.getLocation(v));
The snippets above are copy pasted examples of my working code. Logout in this case is a public method in MainActivity that takes in a point and does what is needs with it.
you can use callback
1.define a callback in you dialog fragment
public Call mCall;
public interface Call {
void returnData(Data data);
}
2.on dialog fragment life circle
#Override
public void onDetach() {
super.onDetach();
mCall = (Call) getActivity();
mCall.returnData(data);
}
3.activity just implements Call
activity implements DiaFragment.Call
onActivityResult is there to receive informations after startActivityForResult is called, which is not your case.
What kind of datas you need to get from the dialog ?
DialogFragment is usually used in a fragment, not an activity. Look at alert dialog.
My application has and activity with a viewPager and 4 fragments.
In one fragment I added a google SupportPlaceAutocompleteFragment and
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.area_swipe_fragment, container, false);
SupportPlaceAutocompleteFragment autocompleteFragment = (SupportPlaceAutocompleteFragment)
getChildFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
Toast.makeText(ctx, "do something", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(Status status) {
}
});
return view;
}
My problem is the onPlaceSelectedListener is never fired and I can't get the result of the selected place. Instead get fired the onActivityResults() placed in the second fragment.
I tried with a onActivityResults() in the first fragment but it doesn't get fired, always executed the one in the second fragment.
Any ideas?
From the docs:
If your fragment is nested within another fragment, your app must also
forward onActivityResult() calls to the containing fragment, as shown
in the following snippet:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
autocompleteFragment.onActivityResult(requestCode, resultCode, data);
}
Perhaps this is the solution.
The #AndrewR answer took me on the right track, very similar to the comments, I override onActivityResult however it didn't work.
The problem was the host Activity wasn't calling the super:
public class HostActivity extends AppCompatActivity {
//Please don't forget other relevant methods
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//super.onActivityResult... is the important line
//Add other custom behaviours
}
}
Assuming the Google Places API for android services are properly enabled for your api key, even I observed similar issue using SupportPlaceAutocompleteFragment, where the onPlaceSelected is never getting triggered on place selection. However later when i tried with the intent approach, things worked..
I ran into this issue this morning, and after a bunch of reading and random similar issues I got the following to work.
If you look at the source code for SupportPlaceAutocompleteFragment you will see it calls
public class SupportPlaceAutocompleteFragment extends Fragment {
private void zzzG() {
...
try {
Intent var2 = (new IntentBuilder(2)).setBoundsBias(this.zzaRk).setFilter(this.zzaRl).zzeq(this.zzaRj.getText().toString()).zzig(1).build(this.getActivity());
this.startActivityForResult(var2, 1);
}
...
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 1) {
...
}
super.onActivityResult(requestCode, resultCode, data);
}
}
Depending on your integration this can cause the RequestCode to change to something other than 1. By extending it to override the startActivityForResult you can change the behaviour by calling getActivity().startActivityForResult instead of this.startActivityForResult
public class WrappedSupportPlaceAutocompleteFragment extends SupportPlaceAutocompleteFragment {
#Override
public void startActivityForResult(Intent intent, int requestCode) {
this.getActivity().startActivityForResult(intent, requestCode);
}
}
from there you can now follow what AndrewR mentioned and pass the activity result from the activity to the fragment and get the expected result.
So I have a boolean value in Activity A that is set to false. Then, in another activity I want to change that value to true. Then when i press the back button back to activity A, that boolean is now true and it runs that in the onCreate.
here's what I mean, Activity A
private static boolean newCardcheck = false;
#Override
protected void onCreate(Bundle savedInstanceState)
{
}
public static void setNewCardcheck() {
newCardcheck = true;
}
#Override
public void onResume() {
super.onResume();
if(newCardcheck)
{
Toast.makeText(this,"hey everyone",Toast.LENGTH_SHORT).show();
}
else
{
alfunction();
sendCards(storeCards);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == RESULT_LOAD_IMAGE)
{
newCardcheck = true;
}
}
Activity B:
#Override
public void onBackPressed()
{
MyActivity.setNewCardcheck();
super.onBackPressed();
setResult(Activity.RESULT_OK, getIntent());
finish();
}
So when I press back, I want newCardcheck to be true and run the "if" statement not the else statement.
Hope you guys can help.
thanks.
And I also tried putting setNewCard() method in an onClick it didn't work either.
The best way to do this is through SharedPreferences. SharedPreferences will write your data to a private file in a key/value within your app's apk that will persist even you turn your device off.
You can initialize SharedPreferences in onCreate like so: SharedPreferences sharedPreferences = getSharedPreferences(getPackageName(), MODE_PRIVATE).
To store a value simply call: sharedPreferences.edit().putString("myKey", stringValue).commit();
To retrieve that value anywhere from your application, initialize SharedPreferences, and then use the following code: String myData = sharedPreferences.getString("myKey");
Let me know if that helps!
EDIT: You may also want to look into getting a result from your Intent. See Getting a Result from an Activity. Use SharedPreferences if you need the boolean to be persistent (ie: written to storage and available on reboot), otherwise you may want to try onActivityResult.
Edit 2:
Try overriding onActivityResult in Activity A as so:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
myBoolean = true;
}
}
Then in Activity B try
setResult(Activity.RESULT_OK, getIntent());
finish();
This is the standard way of passing data to and from activities. Check out my link above about getting a result from an activity to delve a little deeper.
I'm using a TabActivity that calls an ActivityGroup. Tipical approach that brings problems.
Now I'm facing a problem with onActivityResult
in my Activity I have..
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.place_buttontab_community_media);
Button ButtonClick =(Button) findViewById(R.id.addPicture);
ButtonClick.setOnClickListener(new OnClickListener (){
#Override
public void onClick(View view)
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// request code
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "hi");
super.onActivityResult(requestCode, resultCode, data);
}
}
unfortunately onActivityResult is never invoked.
You should listen for the result in the ActivityGroup's onActivityResult(). When a result is received, you have to decide which Activity should receive it and call it's onActivityResult() method with the received values.
I recently encountered this, to consolidate Andras' and virtual82's answer and discussion above (Sorry I can't add comment due to my low rep):
If your activity is started inside an ActivityGroup, which is used by TabActivity for example, then only the ActivityGroup activity can receive method calls to onActivityResult when you start an activity with startActivityForResult(Intent intent, int requestCode) from an activity inside the ActivityGroup.
In my situation, I have a TabActivity that contains FragmentActivitys. A Fragment inside a FragmentActivity may start an activity for result.
In this case the Fragment needs to start the activity with TabActivity as the calling activity:
Intent doSomethingIntent = new Intent();
//getActivity() returns the FragmentActivity, so we need to get the TabActivity with getParent()
Activity tabActivity = getActivity().getParent();
doSomethingIntent .setClass(tabActivity , PostCommentActivity.class);
tabActivity.startActivityForResult(doSomethingIntent , DO_SOMETHING_REQ_CODE);
Then in onActivityResult of the TabActivity, pass the result back to the Fragment.
Activity currentActivity = getLocalActivityManager().getCurrentActivity();
//get the FragmentActivity in order to get the Fragment instance
if(currentActivity instanceof FragmentActivity){
FragmentActivity currentFragmentActivity = (FragmentActivity)currentActivity ;
//R.id.l_container is the layout/viewgroup that contains the Fragment
Fragment currentFragment = currentFragmentActivity.getSupportFragmentManager().findFragmentById(R.id.l_container);
if(currentFragment != null){
//pass result to the Fragment!
frag.onActivityResult(requestCode, resultCode, data);
}
}
I realize that ActivityGroup, TabActivity and LocalActivityManager are deprecated in favor of Fragment and FragmentManager, but my project time constraint didn't allow me enough time to fully upgrade.
Hopefully this post will help someone in this situation, instead of the usual "don't do it" kind of response you see else where.