I have created an activity which contains a button, a ViewPager and some fragments. When I click on the button a DialogActivity opens and connects to the web service using AsyncHttpClient and returns some strings which are pictures url, name, etc. to MainActivity. I want MainActivity to show the data in fragment specially the picture url (using Glide) but I can’t do this.
I appreciate it if you help me
DialogActivity:
void parsAndShowBiography(String response) {
try {
Gson gson = new Gson();
TheaudiodbBiography theaudiodbBiography = gson.fromJson(response, TheaudiodbBiography.class);
Intent returnIntent = new Intent(DialogActivity.this, MainActivity.class);
returnIntent.putExtra("artistThumb", theaudiodbBiography.getArtists()
.get(0).getStrArtistThumb());
returnIntent.putExtra("strArtist", theaudiodbBiography.getArtists()
.get(0).getStrArtist());
returnIntent.putExtra("artistFanart1", theaudiodbBiography.getArtists()
.get(0).getStrArtistFanart());
setResult(Activity.RESULT_OK, returnIntent);
finish();
MainActivity :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
???????????????????????
}
And this is the Fragment :
public class BiographyFragment extends Fragment {
static BiographyFragment instance;
public static BiographyFragment getInstance() {
if (instance == null) {
instance = new BiographyFragment();
}
return instance;
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.bigraphy_fragment, container, false);
return view;
}
I put some TextViews and ImageViews into Fragment xml file.
and if it helps this is the UX :
Hi guys i solved the question with this code :
MainActivity :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
View test=BiographyFragment.getInstance().getView();
Glide.with(this).load(data.getStringExtra("artistFanart1")).into(
(ImageView)test.findViewById(R.id.artistFanart1));
}
Related
I have a helper class that takes an activity and does stuff with it.
public MyClass(AppCompatActivity activity, Callbacks callbacks) {
this.activity = activity;
this.callbacks = callbacks;
}
What I do in this class is basically call other activies/libraries in a certain order and use the results. I put this in a helper class so that I can easily reuse the code.
This is the problem I have:
With the new ActivityResultLauncher it's easy to "modularize" what I need:
ActivityResultLauncher<Intent> chooseImageLauncher = activity.registerForActivityResult(...);
...
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
chooseImageLauncher.launch(intent);
And in the implementation of chooseImageLauncher I do whatever I want next. In this case, I will call a library.
The problem is that the library I'm calling was last updated 2020 and doesn't provide a method for an ActivityResultLauncher. It only supports the old way with onActivityResult:
MyLibrary.init().start(activity);
And the result can be caught like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == MyLibrary.REQUEST_CODE && resultCode == RESULT_OK) {
...
}
}
But I can only implement that in each activity itself. How can I implement here?
You could add a private class inside your helper class that extends Activity. This way you can still catch the value emitted by your library.
private class MyLibraryActivityWrapper extends AppCompatActivity {
public void init() {
MyLibrary.init().start(activity);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == MyLibrary.REQUEST_CODE && resultCode == RESULT_OK) {
}
}
}
I'am trying to read the barcode via Zxing in fragment
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_caddie, container, false);
etCodigo = v.findViewById(R.id.etCodigo);
btnLeerCodigo = v.findViewById(R.id.btnLeerCodigo);
btnLeerCodigo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
escanear();
}
});
text = "";
return v;
}
public void escanear() {
IntentIntegrator intent = IntentIntegrator.forSupportFragment(FragmentCaddie.this);
//IntentIntegrator intent = new IntentIntegrator(getActivity());
intent.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
intent.setPrompt("ESCANEAR CODIGO");
intent.setCameraId(0);
intent.setBeepEnabled(false);
intent.setBarcodeImageEnabled(false);
intent.initiateScan();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null) {
if(result.getContents() == null) {
Toast.makeText(getContext(), "Cancelaste el escaneo", Toast.LENGTH_SHORT).show();
} else {
text = text + " + " + result.getContents().toString() ;
etCodigo.setText(text);
escanear();
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
The issue is it doesn't access the onActivityResult
The hosting activity overrides onActivityResult(), but it did not make a call to super.onActivityResult() for unhandled result codes. Apparently, even though the fragment is the one making the startActivityForResult() call, the activity gets the first shot at handling the result. This makes sense when you consider the modularity of fragments. Once I implemented super.onActivityResult() for all unhandled results, the fragment got a shot at handling the result.
Check this out:
onActivityResult is not being called in Fragment
I hope to be useful for u :)
The solution was quiet simple the onActivityResult that i implemented was Overrided from the parent activity
The solution is to call the fragment onActivityResult from the parent activity
private static final int BARECODE_REQUEST = 114910;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == BARECODE_REQUEST) {
super.onActivityResult(requestCode,resultCode,data);
}
}
I have a MainActivity with tabhost , tabhost has three tab(Fragment) . SecondTab has a RecyclerView . In MainActivity, use the ActionBar button to go to another activity(NewClass) and add new values(MainActivity is still open) . After adding new values, I want to go back to MainActivity and refresh the RecyclerView to display new values.
I am using reactToPublishedEvent() method to refresh RecyclerView but doesnt work.
I could not solve my problem with using answers .
MainActivity
public class MainActivity extends AppCompatActivity implements Publisher{
private Listener listener;
protected void onCreate(Bundle savedInstanceState) {
//. . .
public void onClick(View view)
{
Intent intent = new Intent();
intent.setClass(this , NewClass.class);
startActivityForResult(intent , 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == RESULT_OK)
{
if(data != null)
{
listener.reactToPublishedEvent();
}
}
}
#Override
public void setListener(SecondTab listener) {
this.listener = listener;
}
interface Listener{
void reactToPublishedEvent();
}}
NewClass
boolean check = database.SaveClass(className, classDay, classTimeStart, classTimeEnd, Integer.parseInt(classNumber), uniName , checkMidTerm , checkEndTerm , checkPractical , checkProject , checkConference);
if(check)
{
Intent intent = new Intent();
setResult(RESULT_OK , intent);
finish();
}
SecondTab :
public class SecondTab extends Fragment implements MainActivity.Listener{
private RecyclerView recyclerView;
private DatabaseHandler database;
private RecyclerViewAdapter recyclerAdapter;
private List<ClassTable> classData;
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_second_tab, container, false);
database = new DatabaseHandler(getContext());
recyclerView = view.findViewById(R.id.recyclerView_SecondTab);
classData = new ArrayList<>();
prepareAdapter();
return view;
}
private void prepareAdapter()
{
classData = database.getClassData();//Receive table data
recyclerAdapter = new RecyclerViewAdapter(this , getContext(), classData);
recyclerView.setAdapter(recyclerAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if(context instanceof Publisher){
((Publisher)context).setListener(this);
}
}
#Override
public void reactToPublishedEvent() {
recyclerAdapter.notifyDataSetChanged();//this line is not correct
}
Publisher
public interface Publisher {
void setListener(SecondTab listener);}
I recommend you to use Publisher/Listener pattern.
Publisher - publish some event. Listener react to this events.
So you need to create two interfaces:
interface Publisher{
void setListener(Listener listener)
}
And
interface Listener{
void reactToPublishedEvent()
}
Your MainActivity is publisher. It emmit some events, so your MainActivity should be updated:
class MainActivity extends AppCompatActivity implements Publisher{
private Listener listener;
... // Some your code here
#Ovveride
public void setListener(Listener listener){
this.listener = listener
}
}
Your SecondTab is Listener and should be updated as:
public class SecondTab extends Fragment implements AlertDialogShowClass.OnItemChange, Listener{
... //Your code here
#Ovveride
public void onAttach(Context context){
//Set this fragment in activity as Listener
if(context instance of Publisher){
((Publisher)context).setListener(this)
}
}
}
Then in onActivityResult method you can write something like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == RESULT_OK)
{
if(data != null && listener!=null)
{
listener.reactToPublishedEvent()
}
}
}
There are two way
1.Local broadcast manager
2.Interface
Few methods to achieve the problem.
Observer Pattern.
Local BroadcastManager.
Directly update from the Fragment.
First and second methods are already described in above answers. So will describe the the third one.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == RESULT_OK)
{
if(data != null)
{
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment);
if (fragment instanceof SecondTab)
{
((SecondTab)fragment).recyclerView.notifyDataSetChanged();
// Any Notify method as the requirement
}
}
}
}
Hope This will help.
Cheers!!
I am trying to make image selector for application.For that i am using multi-image-selector library which is perfeclty works when used in activity ,but here i want to use it in fragment.so in fragment OnActivityResult() method is not getting called.Can anyone help me to solve this?
Here's my code:
MainActivity.java:(My Main Activity)
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_IMAGE = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFragmentManager().beginTransaction().replace(R.id.frame, new Image_Selecter()).commit();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Utilz.printLog("Parentactivity", "onActivityResult");
Log.e("hererererer", "hererererer");
if (requestCode == REQUEST_IMAGE) {
new Image().onActivityResult(requestCode, resultCode, data);
}
}
}
Image:(My Fragment)
public class Image extends Fragment {
private ArrayList<String> mSelectPath;
private static final int REQUEST_IMAGE = 2;
ArrayList<Uri> mMedia = new ArrayList<Uri>();
Uri uri;
ImageView img;
protected static final int REQUEST_STORAGE_READ_ACCESS_PERMISSION = 101;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_image, container, false);
img = (ImageView) view.findViewById(R.id.img);
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pickImage();
}
});
return view;
}
public void pickImage() {
MultiImageSelector selector = new MultiImageSelector(getActivity());
selector.showCamera(true);
selector.multi();
selector.count(1);
selector.origin(mSelectPath);
selector.start(getActivity(), REQUEST_IMAGE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE) {
if (resultCode == getActivity().RESULT_OK) {
mSelectPath = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
mMedia.clear();
for (String p : mSelectPath) {
Uri uri = Uri.parse(p);
mMedia.add(uri);
}
uri = mMedia.get(0);
Log.e("uri", " " + uri);
if (!uri.toString().contains("content://")) {
uri = Uri.fromFile(new File(uri.toString()));
Log.e("in if", " uri = " + uri);
}
try {
Glide.with(this)
.load(uri)
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.into(img);
} catch (Exception e) {
Log.e("Exceptionn", " " + e);
}
}
}
}
Try this in your activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("Parentactivity", "onActivityResult");
if (requestCode == REQUEST_IMAGE) { //use request code as REQUEST_IMAGE while starting intent for camera
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.frame);
fragment.onActivityResult(requestCode, resultCode, data);//calling fragments onActivityResult here
}
}
IIRC onActivityResult doesn't get called on a Fragment, it gets called on your parent Activity. You would need to catch this in the Activity and forward the result on to the fragment.
There are two methods which looks same but behaves little bit different.
If method is called by from activity, its not going to give callback to fragment unless called from fragment.
Activity.startActivityForResult()
Fragment.startActivityForResult()
Check out the library if there is way to calling it from fragment.
I dont know the library, just imaging if you can pass fragment to
MultiImageSelector selector = new MultiImageSelector(getActivity()); or selector.start(getActivity(), REQUEST_IMAGE);
Good luck
Emre
you have to call it with intent
public void pickImage() {
Intent intent = new Intent(getContext(), MultiImageSelectorActivity.class);
intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
intent.putStringArrayListExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, mSelectPath);
startActivityForResult(intent, REQUEST_IMAGE);
}
if you were doing getActivity().startActivityForResult(intent, REQUEST_IMAGE);
the on OnActivityResult() will happen on activity instead of fragment. The way you are using it is like that, so you need to use the intent way.
also that maybe will make your code to work
public void pickImage() {
MultiImageSelector selector = new MultiImageSelector(getContext());
selector.showCamera(true);
selector.multi();
selector.count(1);
selector.origin(mSelectPath);
selector.start(getContext(), REQUEST_IMAGE);
}
There have been many successful answers to this question, but there's still something I'm not understanding or that I'm doing incorrectly. One answer is implementing onActivityResult in the host Activity, but I guess I don't know which one that is or I'm following it wrong.
And no, I'm not calling getActivity.startActivityForResult(), just startActivityForResult().
Depending on a selection made in FirstActivity, one or more other selections are possible, created using Fragments. One Fragment is ButtonFragment, which when selected, starts OptionsActivity, like so:
public class ButtonFragment extends Fragment
{
.....
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(resultCode != Activity.RESULT_CANCELED)
{
if(requestCode == OPTIONS_REQUEST_CODE)
{
Bundle extras = data.getExtras();
if (extras != null) {
String selection = (String) extras.get("optionsSelection");
data.setText(selection);
}
}
}
}
private void openOptionsActivity()
{
Intent intent = new Intent(getActivity(), OptionsActivity.class);
intent.putExtra("optionsArray", options);
startActivityForResult(intent, OPTIONS_REQUEST_CODE);
}
}
This fragment is being added in BaseActivity:
public class BaseActivity extends FragmentActivity
{
.....
fm.beginTransaction().add(
R.id.FragmentContainer, frag).commitAllowingStateLoss();
fm.executePendingTransactions();
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
finish();
}
}
Inside OptionsActivity:
public class OptionsActivity extends BaseSpinnerActivity
{
.....
private class OptionsAdapter extends BaseSpinnerAdapter
{
public OptionsAdapter(Context context, Object[] values)
{
super(context, values);
}
protected void fillRow(ViewHolder holder, int position)
{
String option = options[position];
if(option != null) {
holder.text.setText(option);
}
}
protected void onRowSelect(View v)
{
Intent returnIntent = new Intent();
String optionSelection = (String)v.getTag();
returnIntent.putExtra("optionSelected", optionSelection);
setResult(RESULT_OK, returnIntent);
finish();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
finish();
}
}
The same thing is done inside BaseSpinnerActivity, which extends from ListActivity. (I know, should use FragmentActivity, but I haven't had a chance to convert it yet.)
None of these onActivityResult()'s are being called.
What am I missing or doing wrong? Any help is appreciated!