0

I am trying to update the following app version It crashes for an undefined issue. Here is my Logcat

java.lang.RuntimeException: Unable to start activity ComponentInfo{prof.mo.ed.worldcuprussia2018/prof.mo.ed.worldcuprussia2018.MainActivity}: java.lang.NullPointerException: Attempt to write to field 'android.view.View android.support.v4.app.Fragment.mView' on a null object reference
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2460)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2522)
                  at android.app.ActivityThread.access$800(ActivityThread.java:167)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1418)
                  at android.os.Handler.dispatchMessage(Handler.java:111)
                  at android.os.Looper.loop(Looper.java:196)
                  at android.app.ActivityThread.main(ActivityThread.java:5539)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:372)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:956)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:751)
               Caused by: java.lang.NullPointerException: Attempt to write to field 'android.view.View android.support.v4.app.Fragment.mView' on a null object reference
                  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1428)
                  at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1761)
                  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1825)
                  at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:799)
                  at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2596)
                  at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2385)
                  at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2339)
                  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2247)
                  at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3249)
                  at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3201)
                  at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:196)
                  at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:600)
                  at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:178)
                  at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1229)
                  at android.app.Activity.performStart(Activity.java:5992)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2424)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2522) 
                  at android.app.ActivityThread.access$800(ActivityThread.java:167) 
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1418) 
                  at android.os.Handler.dispatchMessage(Handler.java:111) 
                  at android.os.Looper.loop(Looper.java:196) 
                  at android.app.ActivityThread.main(ActivityThread.java:5539) 
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at java.lang.reflect.Method.invoke(Method.java:372) 
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:956) 
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:751) 

In my MainActivity, i use NavigationView to open 2 Fragments in addition to another Activity. In the debug mode, once the debugger getItem() of the default fragment and goes to the onCreateView() it start by inflating the layout normally, but once return its view, it crashes with the last Exception.

Exception doesn't refer to the crash line.So, i have tried to search for this problem. i found many similar problems like : prob1, prob2, prob3, prob4, prob5. However, no url/reference has solved my problem.

You can review my blocks of code as follows for more details:

   package prof.mo.ed.worldcuprussia2018.Fragments;
   import android.app.ProgressDialog;
   import android.content.Context;
   import android.content.res.Resources;
   import android.graphics.Rect;
   import android.os.AsyncTask;
   import android.os.Bundle;
      import android.os.Handler;
      import android.support.annotation.Nullable;
      import android.support.v4.app.Fragment;
      import android.util.Log;
      import android.util.TypedValue;
      import android.view.LayoutInflater;
      import android.view.View;
      import android.view.ViewGroup;
      import android.webkit.WebView;
      import android.widget.AdapterView;
      import android.widget.ListView;
      import org.json.JSONArray;
      import org.json.JSONException;
      import org.json.JSONObject;
      import java.io.BufferedInputStream;
      import java.io.BufferedReader;
      import java.io.IOException;
      import java.io.InputStream;
      import java.io.InputStreamReader;
      import java.util.ArrayList;   
      import javax.net.ssl.HttpsURLConnection;
      import prof.mo.ed.worldcuprussia2018.DBHelper;
      import prof.mo.ed.worldcuprussia2018.LazyAdapter;
      import prof.mo.ed.worldcuprussia2018.OptionsEntity;
          import prof.mo.ed.worldcuprussia2018.R;

   /**
    * Created by Prof-Mohamed Atef on 6/10/2018.
    */

   public class NewsFeedFragment extends Fragment {

       private final String LOG_TAG = NewsFeedFragment.class.getSimpleName();
       RecyclerView recyclerView;
       LazyAdapter lazyAdapter;
       ArrayList<OptionsEntity> Articleslist = new ArrayList<OptionsEntity>();
       DBHelper DB;
       OptionsEntity optionsEntity;
       private ListView ArticlesListView;
       private WebView webview;
       private Handler handler;

       @Nullable
       @Override
       public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup        container, Bundle savedInstanceState) {
           View mainView = inflater.inflate(R.layout.article_list, container, false);
           optionsEntity = new OptionsEntity();
           handler = new Handler();
           ArticlesListView= (ListView)mainView.findViewById(R.id.listview);
           webview=(WebView)mainView.findViewById(R.id.webview);
           lazyAdapter = new        LazyAdapter(getActivity(),R.layout.article_list_item,Articleslist);
           lazyAdapter.notifyDataSetChanged();
           ArticlesListView.setAdapter(lazyAdapter);
           ArticlesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
               @Override
               public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                   OptionsEntity optionsEntity= Articleslist.get(position);
                   WebViewMethod(optionsEntity.getArticleURL());
               }
           });
           ArticlesListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
               @Override
               public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                   return true;
               }
           });
           try {
               DB = new DBHelper(getActivity());
           } catch (Exception e) {
               Log.e(LOG_TAG, "Didn't Create Database", e);
           }
           return mainView;
       }


       private void WebViewMethod(String articleURL) {
           webview.getSettings().setJavaScriptEnabled(true);
           String Url =articleURL.toString();
           webview.loadUrl(Url);
           webview.setHorizontalScrollBarEnabled(false);
       }

       @Override
       public void onResume() {
           super.onResume();
           try{
               int initialVal=DB.SpecifyHomegeneralPosts_Initial_max_Value();
               if (checkConnection()) {
                   startFetchingArticles();
               } else if (!checkConnection()) {
                   if (initialVal==0){
                       getActivity().getSupportFragmentManager().beginTransaction()
                               .replace(R.id.container_frame, new        Fragment_NoInternetDialogue(), "posts")
                               .commit();
                   }else if (initialVal>0){
                       Articleslist =DB.selectAllPostsData();
                       if (Articleslist.size()>0) {
                           // add new to last data then update UI
                           lazyAdapter = new LazyAdapter(getActivity(),        R.layout.article_list_item,Articleslist);
                           lazyAdapter.notifyDataSetChanged();
                           ArticlesListView.setAdapter(lazyAdapter);
                       }
                   }
               }
           }catch (Exception e){
         }
       }

       String URL_API;
       private void startFetchingArticles() {
           try {
               FetchArticles fetchArticles = new FetchArticles();
               fetchArticles.execute(URL_API);
           } catch (Exception e) {
               Log.v(LOG_TAG, "didn't Execute Desires");
           }
       }

       public class FetchArticles extends AsyncTask<String, Void, ArrayList<OptionsEntity>> {
           private final String LOG_TAG = FetchArticles.class.getSimpleName();
           public JSONObject ArticlesFormattedJson;
           public JSONArray ArticlesFormattedJsonAray;
           public JSONObject oneFormattedArticleData;
           String main_List="articles",Source="source", Author="author",Title="title",Description="description",ArticleURL="url",
            ImageURL="urlToImage",PublishDate="publishedAt";
    String Source_STR,Author_STR,Title_STR,Description_STR,ArticleURL_STR,ImageURL_STR,PublishDate_STR;
           private ArrayList<OptionsEntity> getUsersDesiresFromJson(String        UsersDesires)
            throws JSONException {
               ArticlesFormattedJson= new JSONObject(UsersDesires);
               ArticlesFormattedJsonAray = ArticlesFormattedJson.getJSONArray(main_List);
               Articleslist.clear();
               for (int i = 0; i < ArticlesFormattedJsonAray.length(); i++) {
                   oneFormattedArticleData = ArticlesFormattedJsonAray.getJSONObject(i);
                   Source_STR = oneFormattedArticleData.getString(Source);
                   Author_STR = oneFormattedArticleData.getString(Author);
                   Title_STR = oneFormattedArticleData.getString(Title);
                   Description_STR = oneFormattedArticleData.getString(Description);
                   ArticleURL_STR = oneFormattedArticleData.getString(ArticleURL);
                   ImageURL_STR = oneFormattedArticleData.getString(ImageURL);
                   PublishDate_STR = oneFormattedArticleData.getString(PublishDate);
                   OptionsEntity entity = new OptionsEntity(Source_STR, Author_STR,        Title_STR, Description_STR, ArticleURL_STR, ImageURL_STR, PublishDate_STR);
                   try{
                       if (Articleslist!=null){
                           Articleslist.add(entity);
                       }
                   }catch (Exception e){
                   }
               }
               return Articleslist;
           }


           @Override
           protected ArrayList<OptionsEntity> doInBackground(String... params) {
          HttpURLConnection urlConnection = null;
               BufferedReader reader = null;

               if (params.length == 0) {
                   return null;
               }
               try {
                   URL url = new URL(params[0]);
                   urlConnection = (HttpURLConnection) url.openConnection();
                   urlConnection.setRequestMethod("GET");
                   urlConnection.connect();
                   InputStream inputStream = urlConnection.getInputStream();
                   StringBuffer buffer = new StringBuffer();
                   if (inputStream == null) {
                       UsersDesires_JsonSTR = null;
                   }
                   reader = new BufferedReader(new InputStreamReader(inputStream));
                   String line;
                   while ((line = reader.readLine()) != null) {
                       buffer.append(line + "\n");
                   }
                   if (buffer.length() == 0) {
                       return null;
                   }
                   UsersDesires_JsonSTR = buffer.toString();
                   Log.v(LOG_TAG, "Users Desires String: " + UsersDesires_JsonSTR);
               } catch (IOException e) {
                   Log.e(LOG_TAG, "Error here Exactly ", e);
                   return null;
               } finally {
                   if (urlConnection != null) {
                       urlConnection.disconnect();
                   }
                   if (reader != null) {
                       try {
                           reader.close();
                       } catch (final IOException e) {
                           Log.e(LOG_TAG, "Error closing stream", e);
                       }
                   }
               }
               try {
                   return getMatchesFromJson(UsersDesires_JsonSTR);
               } catch (JSONException e) {
                   Log.e(LOG_TAG, "didn't got Users Desires from getJsonData method", e);
                   e.printStackTrace();
               }
               return null;
           }

           @Override
           protected void onPostExecute(ArrayList<OptionsEntity> result) {
               if (result!=null&& getActivity()!=null) {
                           Articleslist =DB.selectAllPostsData();
                   if (Articleslist.size()>0) {
                       lazyAdapter = new LazyAdapter(getActivity(),        R.layout.article_list_item,Articleslist);
                       lazyAdapter.notifyDataSetChanged();
                       ArticlesListView.setAdapter(lazyAdapter);
                   }
               }
           }
       }
   }

Note: there are no problems between Activity to be launched and transaction of fragment to be committed, the problem happens after inflating the layout in onCreateView() method. Response will be appreciated. thanks for any help in advance. If reviewers wants to post the xml layout just mention that but i am sure the problem is not in xml layout files cause the app works and uploaded on google play, but i wanna reduce the crashes from it.

Mohamed Atef
  • 69
  • 13

1 Answers1

0

I uses getSupportFragmentManager() while fragment transaction from activity to be committed and extends my Fragment java class from android.support.v4.app.Fragment. So, i think there is no problem in compatibility. if any other opinion differs from mine, let's discuss that.

Mohamed Atef
  • 69
  • 13