-1

I want to pass data to activity to fragment with use of Reference of Activity :

code as below:In MainActiivty

public Integer i = 0; 

 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 thread = new Thread() {
            @Override
            public void run() {
                try {
                    while (!thread.isInterrupted()) {
                        Thread.sleep(1000);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                i++;
                            }
                        });
                    }
                } catch (InterruptedException e) {
                }
            }
        };
        thread.start();
}

In Fragment:

MainActivity ma=new MainActivity();
mySpeed = String.valueOf(ma.i);

Problem is value of i remain 0 , i can't get updated value of i

if I Store i into another Globe variable (j) and In fragment

  MainActivity ma=new MainActivity();
   mySpeed = String.valueOf(ma.j);

then i got Error

java.lang.NumberFormatException: For input string: "null"
        at java.lang.Integer.parseInt(Integer.java:521)
        at java.lang.Integer.valueOf(Integer.java:611)

whole code of Fragment

 public class SpeedFragment extends Fragment {

        View view;
        TextView SpeedFrgvalue;
        DigitSpeedView DigitrpmFrgView;
        SpeedView speedometer;

        Button DigitalView,Gaugeview;
        LinearLayout linearLayoutspeed;

        String mySpeed;

        private int myInteger;

        Thread thread;

        public SpeedFragment() {
            // Required empty public constructor
        }

        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            Bundle bundle = this.getArguments();
            mySpeed = bundle.getString("speed");
                  Toast.makeText(getContext(),mySpeed,Toast.LENGTH_SHORT).show();

        }

        public void setMyInteger(int i) {
            this.myInteger = i;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {

            // Inflate the layout for this fragment
            view=inflater.inflate(R.layout.fragment_speed, container, false);
            SpeedFrgvalue=(TextView)view.findViewById(R.id.speedfrgvalue);
            speedometer=(SpeedView)view.findViewById(R.id.speedViewfrag);
            Gaugeview=(Button)view.findViewById(R.id.Gaugeviewid);
            DigitalView=(Button)view.findViewById(R.id.digitalviewid);


            SpeedFrgvalue.setText(String.valueOf(myInteger));
            linearLayoutspeed=(LinearLayout)view.findViewById(R.id.digitalspeedlinaear);
            DigitrpmFrgView=(DigitSpeedView)view.findViewById(R.id.digitalSpeedfrgid);
            DigitrpmFrgView.updateSpeed((myInteger));


            speedometer.setMaxSpeed(250);
    //        speedometer.speedTo(Integer.valueOf(mySpeed),4000);

            return view;

        }
    }

Inside Oncreate of MainActiivty I am calling setMyInteger; Same as mention by yusaf.

Harsh ramani
  • 41
  • 1
  • 11
  • https://stackoverflow.com/questions/12739909/send-data-from-activity-to-fragment-in-android – Quick learner Jan 28 '19 at 11:36
  • when i m using Bundle i m facing problem https://stackoverflow.com/questions/54397158/how-to-refresh-or-update-fragment-ui maybe this not because of bundle still i m trying reference of activity – Harsh ramani Jan 28 '19 at 11:47
  • if i use bundle i m facing problem https://stackoverflow.com/questions/54397158/how-to-refresh-or-update-fragment-ui – Harsh ramani Jan 28 '19 at 11:49

3 Answers3

1
MainActivity ma=new MainActivity();

You shouldn't instantiate your activities like this.

If you want to pass an integer value from an activity to fragment, there are multiple ways to do this.

One way to achieve this is as follows

  • Define an integer member variable in fragment

    private int myInteger;
    
  • Define a public setter method for that integer variable in fragment

    public void setMyInteger(int i) {
       this.myInteger = i;
    }
    
  • Inside activity, instantiate that fragment and set the value of the integer variable in fragment via setter method

    MyFragment frag = new MyFragment();
    frag.setMyInteger(10);
    

There are others ways to achieve this, see Send data from activity to fragment in android

Yousaf
  • 27,861
  • 6
  • 44
  • 69
  • i m getting value of private int myInteger; not this.myInteger = i; so just zero as result – Harsh ramani Jan 28 '19 at 12:09
  • @Learnerfrombeginning what value are you passing in your fragment and how are you passing it? can you edit your question to include the code? – Yousaf Jan 28 '19 at 12:11
  • try wrapping `SpeedFrgvalue.setText(String.valueOf(myInteger));` this statement with an `if statment` and check if `myInteger` is not equal to `zero`. If its not, only then set the text – Yousaf Jan 28 '19 at 12:23
  • condition getting false – Harsh ramani Jan 28 '19 at 12:27
  • my real problem is this can u solve this:https://stackoverflow.com/questions/54397158/how-to-refresh-or-update-fragment-ui – Harsh ramani Jan 28 '19 at 12:30
0

You have to send your data in a bundle and then you need to fetch that data in your fragment.

Bundle bundle = new Bundle();
bundle.putString("key", "value");
// make object of your fragment and set arguments to pass
Fragmentclass object = new Fragmentclass();
object.setArguments(bundle);

Then in your fragment class

 String text = getArguments().getString("key");

And you will get the value in text from this.

Ritviz Sharma
  • 306
  • 1
  • 9
0

The first thing I guess we need to take care is that when we are creating the fragment, otherwise we may get a null pointer error. So I attached the fragment inside activity_main in onCreate in MainActivity.

FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    Frag1 fragment = new Frag1();
    fragmentTransaction.replace(R.id.ll, fragment);
    fragmentTransaction.commit();

Next I run the thread after this using a button click method.

public void run(View view){
    t = new Thread(this, "Demo Thread");
    System.out.println("Child thread: " + t);
    t.start(); // Start the thread
}

If I include the above three lines inside onCreate after fragment transaction I get a null pointer error. Next comes the tricky part the thread will generate new values over a time but rest of the code already ran. So that is the reason you are getting zero (initial value). This can be solved technically(to my knowledge) either by creating an Intent or by creating a Listener. I tried to use Intent, unfortunately while Intent goes from Fragment to MainActivity(or any other activity) I could not get it done from Activity to fragment (probably still missing something). So I used Listener. Now there is no ready made listener, we have to create a one. More trickier is how to use that. I created an interface OnFragmentInteractionListener.java to do that.

interface OnFragmentInteractionListener {
    void onFragmentInteraction(int i);}

Now inside Fragment I want to display this in a TextView. For that I would create views inside onStart() method (otherwise I get a null pointer error :-). And I will Instantiate the interface inside it.

Activity context;
TextView tv;
static OnFragmentInteractionListener onFragmentInteractionListener;
@Override
public void onStart() {
    super.onStart();
    context = getActivity();
    tv = context.findViewById(R.id.output)   ;
    onFragmentInteractionListener = new OnFragmentInteractionListener() {
        @Override
        public void onFragmentInteraction(int i) {
        tv.setText(" OUT "+i);
        }
    };
}

Next coming back to MainActivity.

@Override
public void run() {
    try {
        for(int i = 20; i > 0; i--) {
            System.out.println("Child Thread: " + i);
            Frag1.onFragmentInteractionListener.onFragmentInteraction(i);
            Thread.sleep(2000);
        }
    } catch (InterruptedException e) {
        System.out.println("Child interrupted.");
    }
    System.out.println("Exiting child thread.");
}

If you run the code you will get the output as you wanted.

amitava
  • 505
  • 1
  • 5
  • 10