当前位置: 首页 > 知识库问答 >
问题:

尝试写入空对象引用(android片段)上的字段android.view.视图android.support.v4.app.片段. mView

尤夕
2023-03-14

我正在尝试更新以下应用程序版本,它因未定义的问题崩溃。这是我的日志

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中,除了另一个活动外,我还使用NavigationView打开了两个片段。在调试模式下,一旦调试器获取默认片段的getItem()并转到onCreateView(),它就会正常地通过扩展布局启动,但一旦返回其视图,它就会崩溃,并出现最后一个异常

例外情况不涉及碰撞线。所以,我试图寻找这个问题。我发现了很多类似的问题,比如:prob1,prob2,prob3,prob4,prob5。但是,没有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);
                   }
               }
           }
       }
   }

注意:要启动的活动和要提交的片段事务之间没有问题,问题发生在onCreateView()方法中膨胀布局之后。回应将不胜感激。提前感谢任何帮助。如果评论者想发布xml布局只是提到,但我敢肯定问题不是在xml布局文件导致应用程序的作品和上传到谷歌播放,但我想减少它的崩溃。

共有1个答案

符俊材
2023-03-14

我使用getBackportFragmentManager(),而片段事务从活动被提交,并从android.support.v4.app.片段扩展我的片段java类。所以,我认为兼容性没有问题。如果有任何其他意见与我不同,让我们讨论一下。

 类似资料:
  • 在我的情况下,我对向后兼容性没有兴趣。最低API级别是14(冰淇淋三明治),构建目标是4.2果冻豆。在最简单的形式下,我的应用程序的性能与我在Android开发网站上链接的第二个演示完全相同--只是在三个选项卡之间滑动,每个选项卡都有内容。 我读过的所有文章/帖子/答案似乎都非常支持v4支持库。现在对于我的问题,尽管冗长: > 构造应用程序的最佳方式是什么?使用,从而使用SupportFragme

  • 我正在写一个使用片段的简单示例。在主体活动中,有两个片段。第一个片段有一些文本视图,第二个片段有一些按钮。当用户点击textview时,文本打开按钮将被更改。 activity_main.xml mainactivity.java contentFrag.java 我没有编写控制按钮的操作,只是生成onclick事件。但是,我弄错了。请帮助我修复错误,并继续完成我的任务。

  • 我有一个活动和两个片段。片断a和片断b。 我需要实现像,最初碎片应该在那里。在之后,单击FragmentB应该在那里。 我的第二段代码:

  • 我有一个ViewPagerContainer片段,在应用程序启动时加载。ViewPagerContainer片段将两个选项卡(选项卡A和选项卡B)添加到操作栏。选项卡B有两个项目的列表视图。 我所做的:我在选项卡B片段中的列表视图项上附加了一个click listener,这样当用户单击一个项时,它会在第一个片段(即选项卡B下)内打开另一个片段(子片段)。 我陷入困境的地方:当用户按下后退按钮时,

  • 问题内容: 我搜索了许多看起来像这样的问题,但没有找到我的答案。 我有一个活动,该活动具有3个可通过操作栏访问的选项卡。我通过添加3个片段来实现这一点,这些片段使我自定义视图扩展了视图类。 在数据库更改的那一刻,我尝试通过调用invalidate()/ postinvalidate()刷新选项卡中的视图,但这不起作用。正如我考虑的其他许多选项一样,调用片段的onCreateView也是如此。 但是

  • 问题内容: 以及Android文档: http://developer.android.com/training/basics/fragments/communicating.html 以及本文: http://manishkpr.webheavens.com/android-passing-data-between- fragments/ 尽管上述所有情况都与我的情况相似,但并不完全相同。我在这