尝试写入字段';android.view.view android.support.v4.app.Fragment.mView';在空对象引用上(android片段)
我正在尝试更新以下内容 它因未定义的问题而崩溃。 这是我的日志尝试写入字段';android.view.view android.support.v4.app.Fragment.mView';在空对象引用上(android片段),android,android-fragments,fragment,Android,Android Fragments,Fragment,我正在尝试更新以下内容 它因未定义的问题而崩溃。 这是我的日志 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
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(),它就会正常地通过扩展布局启动,但一旦返回其视图,它就会崩溃,并出现最后一个异常
异常不涉及碰撞线。因此,我尝试搜索此问题。我发现了许多类似的问题,如:。但是,没有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);
}
}
}
}
}
包prof.mo.ed.worldcuprussiasia2018.Fragments;
导入android.app.ProgressDialog;
导入android.content.Context;
导入android.content.res.Resources;
导入android.graphics.Rect;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.os.Handler;
导入android.support.annotation.Nullable;
导入android.support.v4.app.Fragment;
导入android.util.Log;
导入android.util.TypedValue;
导入android.view.LayoutInflater;
导入android.view.view;
导入android.view.ViewGroup;
导入android.webkit.WebView;
导入android.widget.AdapterView;
导入android.widget.ListView;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入java.io.BufferedInputStream;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.util.ArrayList;
导入javax.net.ssl.HttpsURLConnection;
import prof.mo.ed.worldcuprussia2018.DBHelper;
import prof.mo.ed.worldcuprussia2018.LazyAdapter;
import prof.mo.ed.worldcuprussia2018.OptionsEntity;
进口教授mo.ed.worldcuprussia2018.R;
/**
*由Mohamed Atef教授于2018年6月10日创建。
*/
公共类NewsFeedFragment扩展了片段{
私有最终字符串LOG_TAG=NewsFeedFragment.class.getSimpleName();
回收视图回收视图;
懒散适配器懒散适配器;
ArrayList ArticleList=新的ArrayList();
dbdb;
期权实体期权实体;
私有列表视图ArticlesListView;
私有网络视图;
私人经办人;
@可空
@凌驾
创建视图时的公共视图(LayoutFlater充气机、@Nullable ViewGroup容器、Bundle savedInstanceState){
视图主视图=充气机。充气(R.layout.article_列表,容器,假);
optionsEntity=新的optionsEntity();
handler=新的handler();
ArticlesListView=(ListView)mainView.findViewById(R.id.ListView);
webview=(webview)mainView.findviewbyd(R.id.webview);
lazyAdapter=newLazyAdapter(getActivity(),R.layout.article\u list\u item,Articleslist);
notifyDataSetChanged();
ArticlesListView.setAdapter(lazyAdapter);
ArticlesListView.setOnItemClickListener(新的AdapterView.OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父对象、视图、整型位置、长id){
OptionsEntity OptionsEntity=Articleslist.get(位置);
WebViewMethod(optionsEntity.getArticleURL());
}
});
ArticlesListView.setOnItemLongClickListener(新的AdapterView.OnItemLongClickListener(){
@凌驾
公共布尔值长单击(AdapterView父项、视图、整型位置、长id){
返回true;
}
});
试一试{
DB=新的DBHelper(getActivity());
}捕获(例外e){
Log.e(Log_标签,“未创建数据库”,e);
}
返回主视图;
}
私有void WebViewMethod(字符串articleURL){
webview.getSettings().setJavaScriptEnabled(true);
字符串Url=articleURL.toString();
loadUrl(Url);
webview.setHorizontalScrollBarEnabled(false);
}
@凌驾
恢复时公开作废(){
super.onResume();
试一试{
int initialVal=DB.SpecifyHomegeneralPosts_Initial_max_Value();
if(检查连接()){
startFetchingArticles();
}如果(!checkConnection()),则为else{
if(initialVal==0){
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.container\u frame,新片段\u NoInternetDialogue(),“posts”)
.commit();
}否则如果(initialVal>0){
Articleslist=DB.selectAllPostsData();
如果(Articleslist.size()>0){
//向上一个数据添加新数据,然后更新用户界面
lazyAdapter=newLazyAdapter(getActivity(),R.layout.article\u list\u item,Articleslist);
notifyDataSetChanged();
ArticlesListView.setAdapter(lazyAdapter);
}
}
}
}捕获(例外e){
}
}
字符串URL_-API;
私有void startFetchingArticles(){
试一试{
FetchArticles FetchArticles=新的FetchArticles();
fetchArticles.execute(URL\uAPI);
}捕获(例外e){
Log.v(Log_标签,“未执行愿望”);
}
}
公共类FetchArticles扩展异步任务{
私有最终字符串LOG_TAG=FetchArticles.class.getSimpleName();