尝试在空对象引用(android片段)上写入字段“ android.view.View android.support.v4.app.Fragment.mView”

时间:2018-06-23 13:16:37

标签: android android-fragments fragment

我正在尝试更新以下app version 它因未定义的问题而崩溃。 这是我的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) 

在MainActivity中,除了另一个Activity外,我还使用NavigationView打开2个片段。在调试模式下,默认片段的调试器getItem()进入onCreateView()时,它将首先通过正常放大布局开始,但是一旦返回其视图,它将崩溃并返回最后一个异常。

异常不涉及崩溃行。因此,我尝试搜索此问题。我发现了许多类似的问题,例如:prob1prob2prob3prob4prob5。但是,没有url /引用解决了我的问题。

您可以按以下方式查看我的代码块,以获取更多详细信息:

   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);
                   }
               }
           }
       }
   }

注意:要启动的Activity与要提交的片段事务之间没有问题,该问题发生在onCreateView()方法中的布局膨胀之后。 响应将不胜感激。感谢您的任何帮助。 如果审阅者想发布xml布局,只需提及,但我确定问题不在xml布局文件中,这会导致应用程序正常工作并在Google Play上载,但我想减少崩溃的发生。

1 个答案:

答案 0 :(得分:0)

我使用getSupportFragmentManager()来提交活动中的片段事务,并从android.support.v4.app.Fragment扩展了我的Fragment Java类。 因此,我认为兼容性没有问题。如果有其他意见与我的不同,让我们讨论一下。