0

I am trying to set text color in fragment. It crash slowly when I exit the fragment. I attached my code for reference....

class TickData implements Runnable {

    @Override
    public void run() {

        if (!token.isEmpty()){

            //TODO: Nifty Auto live data
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            okhttp3.Request request = new okhttp3.Request.Builder()
                    .url("https://history.truedata.in/getticks?symbol=NIFTY AUTO&from=" + getToday() + "T09:15:00&to=" + getToday() + "T15:30:00&response=json&bidask=1")
                    .method("GET", null)
                    .addHeader("Authorization", "Bearer " + token)
                    .build();
            try {
                okhttp3.Response response = client.newCall(request).execute();

                String s = response.body().string();

                ObjectMapper mapper = new ObjectMapper();
                try {
                    Map map = mapper.readValue(s, Map.class);
                    List<List> recordsList = (List<List>) map.get("Records");
                    Collections.reverse(recordsList);

                    //Log.e(TAG, "TickData: " + recordsList.get(0).get(1));
                    String bn = String.valueOf(recordsList.get(0).get(1));

                    float val = Float.parseFloat(bn) - NiftyAutoPervClose();
                    float res = val / NiftyAutoPervClose();
                    float persent = res * 100;


                    handler.post(new Runnable() {
                        @Override
                        public void run() {

                            niftyAuto.setText(bn);

                            niftyAutoCalc.setText(df.format(val));
                            niftyAutoPers.setText("( " + df.format(persent) + "% )");

                            if (val > 0) {
                                niftyAutoPers.setBackgroundResource(R.drawable.gain_indices);
                                niftyAutoCalc.setTextColor(getResources().getColor(R.color.green));
                            } else {
                                niftyAutoPers.setBackgroundResource(R.drawable.loss_indices);
                                niftyAutoCalc.setTextColor(getResources().getColor(R.color.red));
                            }
                        }
                    });
                    refresh(1000);
               
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            socketData();
            new Thread(tickData).start();
        }
    }
}

this is the error when I exit the fragment slowly it comes...

2021-12-03 15:37:20.789 5555-5555/com.pro.tra E/AndroidRuntime: FATAL EXCEPTION: main Process: com.pro.tra, PID: 5555 java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources androidx.fragment.app.FragmentActivity.getResources()' on a null object reference at com.pro.tra.Indices.tab.IndianIndices.IndianIndicesFragment$TickData$1.run(IndianIndicesFragment.java:179) at android.os.Handler.handleCallback(Handler.java:938) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:236) at android.app.ActivityThread.main(ActivityThread.java:7861) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:600) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967)

1 Answers1

0

It crashes beacause fragment is not attached to activity in the handler.post

You can verify it with this: https://developer.android.com/reference/androidx/fragment/app/Fragment.html#isAdded()

Supertommino
  • 562
  • 3
  • 13