0

First of all i have seen two problems first second

but they are different , i use Async task to communicate with server side and it works fine except two situations first one if the server stopped for any reason that caused crashes in my application second situation is when i am connected to network but there is no internet on this access point My Question is how can i handle this error to avoid crashes ? this is my code

    public class news_tab extends Fragment{
    ListView newsLIST;
    String result_news,result_fav;
    String [] Hot_news,newsName1,newsText1 ,agentName;
    int [] Hot_news_id,agent_id;
    int []  fav_id;
    private Context context;
    ArrayList<String> newsName,newsText,agentNamelist;
    public news_tab()
    {

    }
    public news_tab (Context context)
    {

        this.context=context;
        newsName=new ArrayList<String>();
        newsText=new ArrayList<String>();
        agentNamelist=new ArrayList<String>();
    }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.news, container, false);
            rootView.setBackground(Drawable.createFromPath("@drawable/back"));
            newsLIST=(ListView)rootView.findViewById(R.id.newsLV);
            getFavouriteNews();
            news();


            return rootView;
        }
public void getFavouriteNews() {
        new AsyncTask<Void, Void, Void>() {


            @Override
            protected Void doInBackground(Void... voids) {
                try {
                    if(isNetworkAvailable()) {
                        HttpRequestSender http = new HttpRequestSender((Activity) context);
                        result_fav = http.SEND_POST_get_news_fav("**********/dal/login.asmx/getdata_newsfav");
                    }
                    else
                    {
                        result_fav="";
                        Toast.makeText(context,"Check the internet Connection",Toast.LENGTH_SHORT).show();
                    }
                    //  result = http.SEND_Check("******/Login?email="
                    //      +username.getText().toString()+"&password="+password1.getText().toString());

                    Log.d("String", result_fav);


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

            @Override
            protected void onPreExecute() {



                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(Void aVoid) {

                if(result_fav.contains("text_news")) {

                    //   x.cancel();
                   // Toast.makeText(context, "Welcome Favourite", Toast.LENGTH_SHORT).show();
                    // JSONObject jb = null;
                    try {
                        JSONArray JA = new JSONArray(result_fav);
                        ArrayList <String> newsName , newsText,agentNamelist,urlList;

                        fav_id= new int [JA.length()];


                        for (int i = 0; i < JA.length(); i++) {
                            JSONObject JO = (JSONObject) JA.get(i);

                            fav_id[i]= (int)   JO.get("news_id");


                        }

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

                }
                else
                {
                   // Toast.makeText(context,"No News",Toast.LENGTH_SHORT).show();

                }
                super.onPostExecute(aVoid);

            }
        }.execute();

    }
    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager
                = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null;
    }

and finally i got this error

03-29 10:15:45.500 24585-24585/com.Offferly.ahmad.hakimi E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.Offferly.ahmad.hakimi, PID: 24585
java.lang.NullPointerException
   at com.Offferly.ahmad.hakimi.tab.news_tab$2.onPostExecute(news_tab.java:217)
   at com.Offferly.ahmad.hakimi.tab.news_tab$2.onPostExecute(news_tab.java:179)
   at android.os.AsyncTask.finish(AsyncTask.java:632)
   at android.os.AsyncTask.access$600(AsyncTask.java:177)
   at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:146)
   at android.app.ActivityThread.main(ActivityThread.java:5692)
   at java.lang.reflect.Method.invokeNative(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:515)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
   at dalvik.system.NativeStart.main(Native Method)
03-29 10:15:45.540 2952-20003/? E/WakeLock: release without a matched acquire!
Lucifer
  • 29,392
  • 25
  • 90
  • 143
  • 2
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Santanu Sur Mar 29 '18 at 08:46
  • As I see your code You have written a toast inside doInBackground().Remove Toast as doInBackground() runs on different Thread. – Sabyasachi Mar 29 '18 at 11:08

5 Answers5

3

You cannot show Toast inside doInBackground() Method. If you want to do this use below code.

runOnUiThread(new Runnable() {
    public void run() {
       Toast.makeText(<your class name>.this, "Cool Ha?", Toast.LENGTH_SHORT).show();
}});

Try this.

Sanwal Singh
  • 1,765
  • 3
  • 17
  • 35
1
  1. if the server stopped for any reason that caused you are getting null response in your result_fav variable.. You need to handle null in onPostExecute() method like this

    if(!TextUtils.isEmpty(result_fav)){

    // your code

    }else{

    // Show toast Null Response

    }

  2. In second situation :

Remove Toast message in doInBackground() method .can not show toast msg in doInBackground() method

You can try this in your getFavouriteNews() method :

if(isNetworkAvailable()) {
  //then call your async task                      
}

else
{
  //Show Toast no internet                      
}
Rohit
  • 26
  • 5
0

Change your if condition from

if(result_fav.contains("text_news"))

to

 if(!TextUtil(result_fav) && result_fav.contains("text_news"))
Shubham
  • 521
  • 4
  • 11
0

remove toast from doinbackground. you should run it on ui thread.code like below

     @Override
   protected Void doInBackground(Void... voids) {
          try {
          if(isNetworkAvailable()) {
       HttpRequestSender http = new HttpRequestSender((Activity) context);
result_fav = http.SEND_POST_get_news_fav("**********/dal/login.asmx/getdata_newsfav");
                        }
                        else
                        {
                            result_fav="";


      runOnUiThread(new Runnable() {
            public void run() {
              Toast.makeText(context,"Check the internet Connection",Toast.LENGTH_SHORT).show();
        }});
                        }
                        //  result = http.SEND_Check("******/Login?email="
                        //      +username.getText().toString()+"&password="+password1.getText().toString());

                        Log.d("String", result_fav);


                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return null;
                }
Lahiru Prasanna
  • 1,012
  • 2
  • 15
  • 32
0

Run the AsyncTask in onViewCreated, not in onCreateView.

  • can you explain ? – Ahmad Sabbagh Mar 30 '18 at 16:45
  • It is possible that your AsyncTask requires a view that is in your `news.xml` layout file. When you put AsyncTask execution in `onViewCreated`, it might require the view that is not yet created, throwing NullPointerException. Therefore you can try to run the AsyncTask in `onViewCreated` –  Mar 30 '18 at 16:53