java.lang.NullPointerException:Android 尝试调用虚拟方法错误
Posted
技术标签:
【中文标题】java.lang.NullPointerException:Android 尝试调用虚拟方法错误【英文标题】:java.lang.NullPointerException: Android Attempt to invoke virtual method error 【发布时间】:2018-10-23 01:52:51 【问题描述】:我的 android webview 片段应用程序崩溃了,在我添加了一个从一个片段转到另一个片段的按钮后,控制台上的错误是:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ahmed.stories, PID: 11846
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.ahmed.stories.MainActivity.setUrl(java.lang.String)' on a null object reference at com.ahmed.stories.Saying$3.onPageStarted(Saying.java:127)
at com.android.webview.chromium.WebViewContentsClientAdapter.onPageStarted(WebViewContentsClientAdapter.java:517)
at org.chromium.android_webview.AwContentsClientCallbackHelper$MyHandler.handleMessage(AwContentsClientCallbackHelper.java:144)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
它说问题出在((MainActivity) getActivity()).setUrl(url);
的第 127 行,但我找不到任何问题,我是 android 并正在努力学习,也许你们可以帮忙。
MainActivity
package com.ahmed.stories;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.customtabs.CustomTabsIntent;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.NavigationView;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
TextView home_tv, stories, bookmarks, drafts, fakecheck, lost, leaving;
CardView lyt_top_bar;
View toolbar_line;
BottomNavigationView navigation;
BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener()
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item)
switch (item.getItemId())
case R.id.navigation_home:
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
Home home = new Home();
fragmentTransaction.replace(R.id.fragmentContainer, home, "Home");
fragmentTransaction.commit();
return true;
case R.id.navigation_search:
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
Search search = new Search();
fragmentTransaction.replace(R.id.fragmentContainer, search, "Home");
fragmentTransaction.commit();
return true;
case R.id.navigation_edit:
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
Edit edit = new Edit();
fragmentTransaction.replace(R.id.fragmentContainer, edit, "Home");
fragmentTransaction.commit();
return true;
case R.id.navigation_message:
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
Notification notification = new Notification();
fragmentTransaction.replace(R.id.fragmentContainer, notification, "Home");
fragmentTransaction.commit();
return true;
case R.id.navigation_profile:
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
Profile profile = new Profile();
fragmentTransaction.replace(R.id.fragmentContainer, profile, "Home");
fragmentTransaction.commit();
return true;
return false;
;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigation = (BottomNavigationView) findViewById(R.id.navigation);
BottomNavigationViewHelper.disableShiftMode(navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.navigation));
bookmarks = findViewById(R.id.bookmarks);
stories = findViewById(R.id.stories);
home_tv = findViewById(R.id.home_tv);
lyt_top_bar = findViewById(R.id.lyt_top_bar);
toolbar_line = findViewById(R.id.toolbar_line);
stories.setOnClickListener(this);
home_tv.setOnClickListener(this);
bookmarks.setOnClickListener(this);
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
Home home = new Home();
fragmentTransaction.replace(R.id.fragmentContainer, home, "Home");
fragmentTransaction.commit();
@Override
public void onBackPressed()
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START))
drawer.closeDrawer(GravityCompat.START);
else
super.onBackPressed();
@Override
public boolean onCreateOptionsMenu(Menu menu)
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main3, menu);
return true;
@Override
public boolean onOptionsItemSelected(MenuItem item)
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings)
shareTextUrl();
return true;
return super.onOptionsItemSelected(item);
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item)
// Handle navigation view item clicks here.
int id = item.getItemId();
showSystemUI();
if (id == R.id.nav_camera)
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
Profile profile = new Profile();
fragmentTransaction.replace(R.id.fragmentContainer, profile, "Home");
fragmentTransaction.commit();
// Handle the camera action
else if (id == R.id.nav_gallery)
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
Edit edit = new Edit();
fragmentTransaction.replace(R.id.fragmentContainer, edit, "Home");
fragmentTransaction.commit();
else if (id == R.id.nav_slideshow)
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
Drafts drafts = new Drafts();
fragmentTransaction.replace(R.id.fragmentContainer, drafts, "Home");
fragmentTransaction.commit();
else if (id == R.id.nav_manage)
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
Fakecheck fakecheck = new Fakecheck();
fragmentTransaction.replace(R.id.fragmentContainer, fakecheck, "Home");
fragmentTransaction.commit();
else if (id == R.id.nav_lost)
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
Lost lost = new Lost();
fragmentTransaction.replace(R.id.fragmentContainer, lost, "Home");
fragmentTransaction.commit();
else if (id == R.id.nav_send)
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
Leaving leaving = new Leaving();
fragmentTransaction.replace(R.id.fragmentContainer, leaving, "Home");
fragmentTransaction.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
private void hideSystemUI()
lyt_top_bar.setVisibility(View.GONE);
navigation.setVisibility(View.GONE);
toolbar_line.setVisibility(View.GONE);
public void showSystemUI()
lyt_top_bar.setVisibility(View.VISIBLE);
navigation.setVisibility(View.VISIBLE);
toolbar_line.setVisibility(View.VISIBLE);
// View decorView = getWindow().getDecorView();
// decorView.setSystemUiVisibility(
// View.SYSTEM_UI_FLAG_LAYOUT_STABLE
// );
@Override
public void onClick(View v)
showSystemUI();
if (v == home_tv)
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
Saying saying = new Saying();
fragmentTransaction.replace(R.id.fragmentContainer, saying, "Home");
fragmentTransaction.commit();
saying.hideProgress();
hideSystemUI();
if (v == bookmarks)
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
Bookmarks bookmarks = new Bookmarks();
fragmentTransaction.replace(R.id.fragmentContainer, bookmarks, "Home");
fragmentTransaction.commit();
if (v == drafts)
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
Drafts drafts = new Drafts();
fragmentTransaction.replace(R.id.fragmentContainer, drafts, "Home");
fragmentTransaction.commit();
if (v == fakecheck)
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
Fakecheck fakecheck = new Fakecheck();
fragmentTransaction.replace(R.id.fragmentContainer, fakecheck, "Home");
fragmentTransaction.commit();
if (v == lost)
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
Lost lost = new Lost();
fragmentTransaction.replace(R.id.fragmentContainer, lost, "Home");
fragmentTransaction.commit();
if (v == leaving)
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
Leaving leaving = new Leaving();
fragmentTransaction.replace(R.id.fragmentContainer, leaving, "Home");
fragmentTransaction.commit();
if (v == stories)
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
Trending trending = new Trending();
fragmentTransaction.replace(R.id.fragmentContainer, trending, "Home");
fragmentTransaction.commit();
String urlOpen="";
public void setUrl(String url)
this.urlOpen = url;
public void shareTextUrl()
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("text/plain");
share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
// Add data to the intent, the receiving app will decide
// what to do with it.
share.putExtra(Intent.EXTRA_SUBJECT, "Title Of The Post");
share.putExtra(Intent.EXTRA_TEXT, urlOpen);
startActivity(Intent.createChooser(share, "We Only share with the people we care!"));
public void goToHome()
showSystemUI();
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
Home home = new Home();
fragmentTransaction.replace(R.id.fragmentContainer, home, "Home");
fragmentTransaction.commit();
说片段
package com.ahmed.stories;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import java.io.File;
/**
* Created by ahmed on 21/4/18.
*/
public class Saying extends BaseFragment
private String postUrl = "https://wewritesay.herokuapp.com";
private ProgressBar progressBar;
WebView home_web;
ImageButton btn_home;
private float m_downX;
//
public Saying()
// Required empty public constructor
@Override
public void hideProgress()
if (progressBar != null)
progressBar.setVisibility(View.GONE);
// https://my-medium-clone.herokuapp.com/top-stories
@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
@Override
public void onResume()
super.onResume();
((AppCompatActivity) getActivity()).getSupportActionBar().hide();
@Override
public void onStop()
super.onStop();
((AppCompatActivity) getActivity()).getSupportActionBar().show();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_saying, container, false);
home_web = (WebView) view.findViewById(R.id.home_web);
btn_home = view.findViewById(R.id.btn_home);
btn_home.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
((MainActivity) getActivity()).goToHome();
);
WebSettings settings = home_web.getSettings();
settings.setjavascriptEnabled(true);
home_web.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
home_web.getSettings().setAppCacheEnabled(true);
settings.setDomStorageEnabled(true);
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
settings.setUseWideViewPort(true);
settings.setSavePassword(true);
settings.setSaveFormData(true);
settings.setEnableSmoothTransition(true);
progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
// home_web.getSettings().setJavaScriptEnabled(true);
home_web.loadUrl(postUrl);
home_web.setOnKeyListener(new View.OnKeyListener()
public boolean onKey(View v, int keyCode, KeyEvent event)
if ((keyCode == KeyEvent.KEYCODE_BACK) && home_web.canGoBack())
home_web.goBack();
return true;
return false;
);
initWebView();
// home_web.setHorizontalScrollBarEnabled(false);
return view;
private class MyWebChromeClient extends WebChromeClient
Context context;
public MyWebChromeClient(Context context)
super();
this.context = context;
private void initWebView()
home_web.setWebChromeClient(new Saying.MyWebChromeClient(getActivity()));
home_web.setWebViewClient(new WebViewClient()
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
super.onPageStarted(view, url, favicon);
((MainActivity) getActivity()).setUrl(url);
progressBar.setVisibility(View.VISIBLE);
// invalidateOptionsMenu();
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
home_web.loadUrl(url);
return true;
@Override
public void onPageFinished(WebView view, String url)
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
// invalidateOptionsMenu();
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error)
super.onReceivedError(view, request, error);
progressBar.setVisibility(View.GONE);
// invalidateOptionsMenu();
);
home_web.clearCache(true);
home_web.clearHistory();
home_web.getSettings().setJavaScriptEnabled(true);
home_web.setHorizontalScrollBarEnabled(false);
home_web.setOnTouchListener(new View.OnTouchListener()
public boolean onTouch(View v, MotionEvent event)
if (event.getPointerCount() > 1)
//Multi touch detected
return true;
switch (event.getAction())
case MotionEvent.ACTION_DOWN:
// save the x
m_downX = event.getX();
break;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
// set x so that it doesn't move
event.setLocation(m_downX, event.getY());
break;
return false;
);
【问题讨论】:
What is a NullPointerException, and how do I fix it?的可能重复 getActivity()==null. 【参考方案1】:试试下面:
@Override
public void onAttach(Activity activity)
super.onAttach(activity);
mActivity = activity;
然后为了防止泄漏:
@Override
public void onDetach()
super.onDetach();
mContext = null;
现在使用 MainActivity 做:
((MainActivity)mContext).setUrl(url);
【讨论】:
嘿@HaroldSer 我对android 真的很陌生,并试图自学,我不明白你做了什么,请你详细说明。这将是一个很大的帮助谢谢。 onAttach() 我们只是获取对片段附加到的活动的引用(稍后我们使用它来调用方法 setUrl(url)。现在,因为我们要确保没有内存泄漏(片段附加到的活动的引用在分离后仍然存在)我们必须在 onDetach() 上设置活动的引用 null。请参阅片段生命周期。以上是关于java.lang.NullPointerException:Android 尝试调用虚拟方法错误的主要内容,如果未能解决你的问题,请参考以下文章
亲測,Eclipse报"An error has occurred,See error log for more details. java.lang.NullPointerExce