0

I want to send a string data from activity to a fragment, but it always giving error. I checked the links below and tried them, but still same.

send data from activity to fragment android studio Send data from activity to fragment in Android

My code is like below, myActivity.kt (I didn't delete the comment lines, I also tried them too)

img_foto1.setOnClickListener {

        val bundle = Bundle()
        bundle.putString("imgviewname", "img_foto1")
        val fraginfo = adsCameraOrGallery()
        fraginfo.arguments = bundle

        //val imgviewBundle = Bundle()
        //imgviewBundle.putString("coba", "img_foto1")
        //imgviewBundle.putSerializable("modelassign", "test")
        //val fragmentObj = adsCameraOrGallery()
        //fragmentObj.setArguments(imgviewBundle)

        //val transactionData: FragmentTransaction = supportFragmentManager.beginTransaction()
        //transactionData.add(0, fragmentObj, "viewtaskfragment")
        //transactionData.commit()

        //val transactionData: FragmentTransaction = supportFragmentManager.beginTransaction()
        //transactionData.add(0, fraginfo, "viewtaskfragment")

        //transactionData.commit()


        var dialog = adsCameraOrGallery()
        dialog.show(supportFragmentManager,"Choose photo")

    }

Fragment class is like below;

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {


    var args : Bundle = Bundle()
    var dataFromActivity = args.getBundle("imgviewname")
    var temp = args.getString("imgviewname")

    //comingData = this!!.arguments!!.getString("imgviewname")
             }

So from the fragment, both of the lines' data above is null. There is no data coming from the activity.

If I use the line below, in the fragment, this time I'm receving "KotlinNullPointerException" error.

ComingDataFromActivity = this!!.arguments!!.getString("imgviewname")

How can I do that? Thanks.


Regarding to @Mike's suggestions, these lines belove worked for me, updating the post.

Activity;

img_foto1.setOnClickListener {

        val bundle = Bundle()
        bundle.putString("imgviewname", "img_foto1")
        val fraginfo = adsCameraOrGallery()
        fraginfo.arguments = bundle

        var dialog = adsCameraOrGallery()
        dialog.arguments =bundle

        dialog.show(supportFragmentManager,"Choose foto")
    }

Fragment;

    var comingData = this!!.arguments!!.getString("imgviewname")
sleepy
  • 167
  • 1
  • 2
  • 9
  • 1
    In your first snippet, the `dialog` that you show is not the one you set the arguments on earlier, `fraginfo`. Either `show()` `fraginfo`, or change that to set the arguments on `dialog`. The second block isn't correct, because you're creating a new, empty `Bundle` there, not retrieving the arguments. You've got the right idea in your last block, but just make sure to correct the first one, setting the arguments on the right `Fragment` instance. – Mike M. Nov 29 '19 at 04:13
  • Many thanks @Mike , your suggestions solved the problem. I'm adding the working codes to my original post. – sleepy Nov 29 '19 at 10:29

4 Answers4

0
Bundle bundle = new Bundle();
bundle.putString("key", "test");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);

and in Fragment onCreateView method:

String strtext = getArguments().getString("key");    
  • unfortunately didn't worked, throw "KotlinNullPointerException" error at "String strtext = getArguments().getString("key")" line. – sleepy Nov 28 '19 at 11:26
  • try this arguments?.let { String strtext = it.getString("key", "") } – djibril diop Nov 28 '19 at 11:31
  • Couldn't convert this code to Kotlin, also Android Studio too. I don't get it where should I add this argument? – sleepy Nov 28 '19 at 11:36
  • in your fragment – djibril diop Nov 28 '19 at 11:37
  • I put under onCreateView this code ".let { String strtext = it.getString("key", "") }", but it gives error. "Expecting an element". Sorry I'm beginner at Android programming. – sleepy Nov 28 '19 at 11:40
  • you can also declare a public method in your activity that returns a string type and you can access it directly in your fragment. – djibril diop Nov 28 '19 at 11:42
  • Exemple in your activity var image="url" fun getMyData():String{ return image } and in your fragment @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { var myDataFromActivity = activity.getMyData(); return view; } – djibril diop Nov 28 '19 at 11:43
  • Now I see, but the problem is, if I put this method in root of my activity class, that works, I can call from the fragment. But I need to call this method inside "img_foto1.setOnClickListener", so if I put inside this listener, it isn't working. I mean I can't call this method from the fragment. Or I don't know how to call from the fragment, if it's possible? – sleepy Nov 28 '19 at 11:55
  • gives the value of the string in the imagefo.setOnClickListener{ image="new string"} – djibril diop Nov 28 '19 at 12:53
  • But I can't put any parameter to the onClickListener method like this "img_foto1.setOnClickListener(image:String)" . Also tried with parameter like you wrote. But it throws "none of the following functions can be called with the arguments supplied " error. – sleepy Nov 28 '19 at 14:08
0

Try to use interface for accessing data. In class where you want to use data

class A implement PassDataListener{
String str=null;
//PASS CONTEXT TO OF LISTENER TO CLASS WHERE YOU WANT TO GET DATA
B b=new B(A.this);

@override
public void getString(String text){
this.str=text;
}
}
interface PassDataListener{
void getString(String a);
}
class B{
PassDataListener listener;
public(PassDataListener passDataListener){
this.listener=passDataListener;
}
//PASSING DATA TO CLASS WHERE YOU THIS DATA
String text="abc";
listener.getText(text);
}
Sandhiya
  • 339
  • 2
  • 14
  • I already using an interface for sending data from fragment to activity. For the opposite side, should I create another interface? I'll try, but isn't bundle kinda easy way? – sleepy Nov 28 '19 at 12:14
  • 1
    Using dialog.show it will show in popup where as intent will pass data to another activity/Fragment and it self also means activity to fragment or vise-versa. and there is no connection between dialog and intent. I think instead of using dialog intent will help you to achieve your goal. – Twisha Kotecha Nov 28 '19 at 12:32
  • Thanks for the suggestion, will try intent method too. But if I use intent, I can't popup the fragment like a window in activity, right? I mean if I use intent, it will be completely new full screen fragment, not like dialog? – sleepy Nov 28 '19 at 13:31
0

In your Activity:-

 Intent intent = new Intent(getContext(), SearchContact.class);
 Bundle a = new Bundle();
        a.putString("key", "text");
        intent.putExtra("model1", a);
        startActivity(intent);

In your Fragment:-

Intent intent = getIntent();
Bundle bundle = intent.getString("model1");

Try this may be it will help you.

Twisha Kotecha
  • 1,082
  • 1
  • 4
  • 18
  • I'm already using "dialog.show(supportFragmentManager,"Choose photo")" in my "img_foto1.setOnClickListener" so I'm not sure if I can use another intent method? It throws some ActivityNotFoundException errors. – sleepy Nov 28 '19 at 12:24
0

In your Activity,

Bundle bundle = new Bundle();
 String text = "Here is my text";
 bundle.putString("text", text );
 FragmentClass fragment = new FragmentClass();
 fragment.setArguments(bundle);
 transaction.replace(R.id.fragment, fragment);
 transaction.commit();

In your Fragment

@Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    String myText = this.getArguments().getString("text");

 }
Sandhiya
  • 339
  • 2
  • 14
  • I tried to convert activity code to Kotlin, but Android Studio couldn't convert "transaction" class. It throws "unresolved reference" error. – sleepy Nov 28 '19 at 12:40
  • @sleepy refer dis ``` https://stackoverflow.com/a/53965039/12273964 ``` – Sandhiya Nov 28 '19 at 12:45