编辑文本未将 url 加载到 webview 中,应用程序在按下按钮时崩溃
edit text not loading url into webview and app crashes on button press
我的第一个应用程序有问题。我想要实现的是在操作栏中编辑文本,它会接受用户输入 URL 并将其加载到 webview 中,最好不要使用 go 按钮,只在键盘上输入,但也无法使其工作方法。该应用程序应该像浏览器一样工作。我尝试了很多东西,但似乎没有任何效果,甚至分配了一个按钮和应用程序崩溃。在过去的 62 小时里一直在努力解决这个问题......:( 真的很感谢你的帮助以及我能做的任何事情。
代码如下:
主要活动
package com.example.------------;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.SearchManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.app.Activity;
import android.view.KeyEvent;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.ProgressBar;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.Toast;
public class MainActivity extends Activity
implements NavigationDrawerFragment.NavigationDrawerCallbacks{
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {@link #restoreActionBar()}.
*/
private CharSequence mTitle;
private WebView webView;
private EditText field;
private ProgressBar progress;
private InputMethodManager mIMEMgr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getActionBar();
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM
| ActionBar.DISPLAY_SHOW_HOME);
// add the custom view to the action bar
actionBar.setCustomView(R.layout.actionbar_view);
field = (EditText)findViewById(R.id.urlField);
webView = (WebView)findViewById(R.id.webView1);
webView.setWebChromeClient(new MyWebViewClient());
Button openUrl = (Button) findViewById(R.id.button1);
openUrl.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
String url = field.getText().toString();
String prefix = "https://www.google.com/search?q=";
if(!url.startsWith("http://") && !url.startsWith("https://") && !url.endsWith(".com"))
{
url = prefix + url;
}
if(url.endsWith(".com") || url.endsWith(".as") || url.endsWith(".uk") || url.endsWith(".biz"))
{
if(!url.startsWith("http://") && !url.startsWith("https://"))
{
url = "http://" + url;
}
}
if (validateUrl(url)) {
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
MainActivity.this.progress.setProgress(0);
}
}
private boolean validateUrl(String url) {
return true;
}
});
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
@Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setTitle(mTitle);
}
private class MyWebViewClient extends WebChromeClient {
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView View, String url)
{
webView.loadUrl(url);
return true;
}
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack())
{
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
protected boolean validateUrl(String url) {
// TODO Auto-generated method stub
return false;
}
@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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
activity_main
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.--------------.MainActivity" >
<!--
As the main content view, the view below consumes the entire
space available using match_parent in both dimensions.
-->
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<WebView
android:id="@+id/webView1"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
tools:context=".MainActivity" />
<Button
android:id="@+id/button1"
android:onClick="onClick"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Go" />
</FrameLayout>
<!--
android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead.
-->
<!--
The drawer is given a fixed width in dp and extends the full height of
the container.
-->
<fragment
android:id="@+id/navigation_drawer"
android:name="com.example.minimalbrowserx.NavigationDrawerFragment"
android:layout_width="@dimen/navigation_drawer_width"
android:layout_height="match_parent"
actionbar_view
<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/urlField"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:imeOptions="actionDone"
android:inputType="textFilter"
android:text="no" >
</EditText>
Android 清单
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.------------"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
LogCat
03-25 18:52:13.301: D/AndroidRuntime(10241): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
03-25 18:52:13.311: D/AndroidRuntime(10241): CheckJNI is ON
03-25 18:52:13.411: D/dalvikvm(10241): Trying to load lib libjavacore.so 0x0
03-25 18:52:13.421: D/dalvikvm(10241): Added shared lib libjavacore.so 0x0
03-25 18:52:13.441: D/dalvikvm(10241): Trying to load lib libnativehelper.so 0x0
03-25 18:52:13.441: D/dalvikvm(10241): Added shared lib libnativehelper.so 0x0
03-25 18:52:13.441: D/dalvikvm(10241): No JNI_OnLoad found in libnativehelper.so 0x0, skipping init
03-25 18:52:13.711: D/dalvikvm(10241): Note: class Landroid/app/ActivityManagerNative; has 179 unimplemented (abstract) methods
03-25 18:52:14.381: E/memtrack(10241): Couldn't load memtrack module (No such file or directory)
03-25 18:52:14.381: E/android.os.Debug(10241): failed to load memtrack module: -2
03-25 18:52:14.781: D/AndroidRuntime(10241): Calling main entry com.android.commands.pm.Pm
03-25 18:52:14.831: D/AndroidRuntime(10241): Shutting down VM
03-25 18:52:14.831: D/dalvikvm(10241): Debugger has detached; object registry had 1 entries
03-25 18:52:15.631: D/AndroidRuntime(10252): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
03-25 18:52:15.641: D/AndroidRuntime(10252): CheckJNI is ON
03-25 18:52:15.741: D/dalvikvm(10252): Trying to load lib libjavacore.so 0x0
03-25 18:52:15.751: D/dalvikvm(10252): Added shared lib libjavacore.so 0x0
03-25 18:52:15.771: D/dalvikvm(10252): Trying to load lib libnativehelper.so 0x0
03-25 18:52:15.771: D/dalvikvm(10252): Added shared lib libnativehelper.so 0x0
03-25 18:52:15.781: D/dalvikvm(10252): No JNI_OnLoad found in libnativehelper.so 0x0, skipping init
03-25 18:52:16.031: D/dalvikvm(10252): Note: class Landroid/app/ActivityManagerNative; has 179 unimplemented (abstract) methods
03-25 18:52:16.721: E/memtrack(10252): Couldn't load memtrack module (No such file or directory)
03-25 18:52:16.721: E/android.os.Debug(10252): failed to load memtrack module: -2
03-25 18:52:17.191: D/AndroidRuntime(10252): Calling main entry com.android.commands.am.Am
03-25 18:52:17.271: I/ActivityManager(385): START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.example.minimalbrowserx/.MainActivity} from pid 10252
03-25 18:52:17.281: D/AndroidRuntime(10252): Shutting down VM
03-25 18:52:17.291: D/jdwp(10252): Got wake-up signal, bailing out of select
03-25 18:52:17.291: D/dalvikvm(10252): Debugger has detached; object registry had 1 entries
03-25 18:52:25.101: W/AwContents(10213): nativeOnDraw failed; clearing to background color.
03-25 18:52:25.161: E/SoundPool(385): error loading /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:25.161: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:25.161: E/SoundPool(385): error loading /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:25.161: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:25.171: E/SoundPool(385): error loading /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:25.171: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:25.171: E/SoundPool(385): error loading /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:25.171: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:25.171: E/SoundPool(385): error loading /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:25.171: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:25.171: E/SoundPool(385): error loading /system/media/audio/ui/KeypressStandard.ogg
03-25 18:52:25.171: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/KeypressStandard.ogg
03-25 18:52:25.171: E/SoundPool(385): error loading /system/media/audio/ui/KeypressSpacebar.ogg
03-25 18:52:25.171: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/KeypressSpacebar.ogg
03-25 18:52:25.171: E/SoundPool(385): error loading /system/media/audio/ui/KeypressDelete.ogg
03-25 18:52:25.171: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/KeypressDelete.ogg
03-25 18:52:25.171: E/SoundPool(385): error loading /system/media/audio/ui/KeypressReturn.ogg
03-25 18:52:25.171: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/KeypressReturn.ogg
03-25 18:52:25.171: E/SoundPool(385): error loading /system/media/audio/ui/KeypressInvalid.ogg
03-25 18:52:25.171: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/KeypressInvalid.ogg
03-25 18:52:25.171: W/AudioService(385): onLoadSoundEffects(), Error -1 while loading samples
03-25 18:52:25.361: D/AndroidRuntime(10213): Shutting down VM
03-25 18:52:25.361: W/dalvikvm(10213): threadid=1: thread exiting with uncaught exception (group=0xb3acbba8)
03-25 18:52:25.381: E/AndroidRuntime(10213): FATAL EXCEPTION: main
03-25 18:52:25.381: E/AndroidRuntime(10213): Process: com.example.minimalbrowserx, PID: 10213
03-25 18:52:25.381: E/AndroidRuntime(10213): java.lang.NullPointerException
03-25 18:52:25.381: E/AndroidRuntime(10213): at com.example.minimalbrowserx.MainActivity.onClick(MainActivity.java:105)
03-25 18:52:25.381: E/AndroidRuntime(10213): at android.view.View.performClick(View.java:4438)
03-25 18:52:25.381: E/AndroidRuntime(10213): at android.view.View$PerformClick.run(View.java:18422)
03-25 18:52:25.381: E/AndroidRuntime(10213): at android.os.Handler.handleCallback(Handler.java:733)
03-25 18:52:25.381: E/AndroidRuntime(10213): at android.os.Handler.dispatchMessage(Handler.java:95)
03-25 18:52:25.381: E/AndroidRuntime(10213): at android.os.Looper.loop(Looper.java:136)
03-25 18:52:25.381: E/AndroidRuntime(10213): at android.app.ActivityThread.main(ActivityThread.java:5017)
03-25 18:52:25.381: E/AndroidRuntime(10213): at java.lang.reflect.Method.invokeNative(Native Method)
03-25 18:52:25.381: E/AndroidRuntime(10213): at java.lang.reflect.Method.invoke(Method.java:515)
03-25 18:52:25.381: E/AndroidRuntime(10213): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-25 18:52:25.381: E/AndroidRuntime(10213): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-25 18:52:25.381: E/AndroidRuntime(10213): at dalvik.system.NativeStart.main(Native Method)
03-25 18:52:25.401: W/ActivityManager(385): Force finishing activity com.example.minimalbrowserx/.MainActivity
03-25 18:52:25.421: D/gralloc(54): Registering a buffer in the process that created it. This may cause memory ordering problems.
03-25 18:52:25.421: E/libEGL(54): called unimplemented OpenGL ES API
03-25 18:52:25.421: E/libEGL(54): called unimplemented OpenGL ES API
03-25 18:52:25.431: E/libEGL(54): called unimplemented OpenGL ES API
03-25 18:52:25.431: E/libEGL(54): called unimplemented OpenGL ES API
03-25 18:52:25.431: E/SurfaceFlinger(54): glCheckFramebufferStatusOES error 2139965326
03-25 18:52:25.431: E/SurfaceFlinger(54): got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot
03-25 18:52:25.441: E/libEGL(54): called unimplemented OpenGL ES API
03-25 18:52:25.441: E/libEGL(54): called unimplemented OpenGL ES API
03-25 18:52:25.441: W/WindowManager(385): Screenshot failure taking screenshot for (246x410) to layer 21010
03-25 18:52:25.731: I/Choreographer(385): Skipped 37 frames! The application may be doing too much work on its main thread.
03-25 18:52:26.241: W/ActivityManager(385): Activity pause timeout for ActivityRecord{b3dbeaa0 u0 com.example.minimalbrowserx/.MainActivity t135 f}
03-25 18:52:26.391: I/Choreographer(540): Skipped 32 frames! The application may be doing too much work on its main thread.
03-25 18:52:28.141: E/SoundPool(385): error loading /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:28.141: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:28.141: E/SoundPool(385): error loading /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:28.151: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:28.151: E/SoundPool(385): error loading /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:28.151: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:28.151: E/SoundPool(385): error loading /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:28.151: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:28.151: E/SoundPool(385): error loading /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:28.151: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:28.151: E/SoundPool(385): error loading /system/media/audio/ui/KeypressStandard.ogg
03-25 18:52:28.151: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/KeypressStandard.ogg
03-25 18:52:28.151: E/SoundPool(385): error loading /system/media/audio/ui/KeypressSpacebar.ogg
03-25 18:52:28.151: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/KeypressSpacebar.ogg
03-25 18:52:28.151: E/SoundPool(385): error loading /system/media/audio/ui/KeypressDelete.ogg
03-25 18:52:28.161: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/KeypressDelete.ogg
03-25 18:52:28.161: E/SoundPool(385): error loading /system/media/audio/ui/KeypressReturn.ogg
03-25 18:52:28.161: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/KeypressReturn.ogg
03-25 18:52:28.161: E/SoundPool(385): error loading /system/media/audio/ui/KeypressInvalid.ogg
03-25 18:52:28.161: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/KeypressInvalid.ogg
03-25 18:52:28.161: W/AudioService(385): onLoadSoundEffects(), Error -1 while loading samples
03-25 18:52:28.231: I/Process(10213): Sending signal. PID: 10213 SIG: 9
03-25 18:52:28.311: I/ActivityManager(385): Process com.example.minimalbrowserx (pid 10213) has died.
03-25 18:52:28.371: W/InputDispatcher(385): channel 'b4213d88 com.example.minimalbrowserx/com.example.minimalbrowserx.MainActivity (server)' ~ Consumer closed input channel or an error occurred. events=0x9
03-25 18:52:28.371: E/InputDispatcher(385): channel 'b4213d88 com.example.minimalbrowserx/com.example.minimalbrowserx.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
03-25 18:52:28.411: W/InputDispatcher(385): Attempted to unregister already unregistered input channel 'b4213d88 com.example.minimalbrowserx/com.example.minimalbrowserx.MainActivity (server)'
03-25 18:52:28.411: I/WindowState(385): WIN DEATH: Window{b4213d88 u0 com.example.minimalbrowserx/com.example.minimalbrowserx.MainActivity}
03-25 18:52:28.421: I/Choreographer(385): Skipped 34 frames! The application may be doing too much work on its main thread.
03-25 18:52:28.501: I/Choreographer(385): Skipped 95 frames! The application may be doing too much work on its main thread.
03-25 18:52:28.591: W/InputMethodManagerService(385): Got RemoteException sending setActive(false) notification to pid 10213 uid 10052
03-25 18:52:28.601: W/Binder(503): Caught a RuntimeException from the binder stub implementation.
03-25 18:52:28.601: W/Binder(503): java.lang.NullPointerException
03-25 18:52:28.601: W/Binder(503): at android.inputmethodservice.IInputMethodWrapper.setSessionEnabled(IInputMethodWrapper.java:280)
03-25 18:52:28.601: W/Binder(503): at com.android.internal.view.IInputMethod$Stub.onTransact(IInputMethod.java:129)
03-25 18:52:28.601: W/Binder(503): at android.os.Binder.execTransact(Binder.java:404)
03-25 18:52:28.601: W/Binder(503): at dalvik.system.NativeStart.run(Native Method)
03-25 18:52:28.691: I/Choreographer(385): Skipped 41 frames! The application may be doing too much work on its main thread.
03-25 18:53:21.601: D/LightsService(385): Excessive delay setting light: 155ms
03-25 19:03:19.131: D/ConnectivityService(385): Sampling interval elapsed, updating statistics ..
03-25 19:03:19.181: D/ConnectivityService(385): Done.
03-25 19:03:19.181: D/ConnectivityService(385): Setting timer for 720seconds
03-25 19:04:19.181: I/ProcessStatsService(385): Prepared write state in 5ms
03-25 19:04:19.191: I/ProcessStatsService(385): Prepared write state in 10ms
根据您的 logcat 看来您正在调用 progress.setProgress(0)
(第 105 行)但您尚未实例化 progress
ProgressBar
(因此它的值为null
)。这会导致 java.lang.NullPointerException
。在调用 setProgress(0)
之前实例化 progress
ProgressBar
。
我的第一个应用程序有问题。我想要实现的是在操作栏中编辑文本,它会接受用户输入 URL 并将其加载到 webview 中,最好不要使用 go 按钮,只在键盘上输入,但也无法使其工作方法。该应用程序应该像浏览器一样工作。我尝试了很多东西,但似乎没有任何效果,甚至分配了一个按钮和应用程序崩溃。在过去的 62 小时里一直在努力解决这个问题......:( 真的很感谢你的帮助以及我能做的任何事情。
代码如下:
主要活动
package com.example.------------;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.SearchManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.app.Activity;
import android.view.KeyEvent;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.ProgressBar;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.Toast;
public class MainActivity extends Activity
implements NavigationDrawerFragment.NavigationDrawerCallbacks{
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {@link #restoreActionBar()}.
*/
private CharSequence mTitle;
private WebView webView;
private EditText field;
private ProgressBar progress;
private InputMethodManager mIMEMgr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getActionBar();
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM
| ActionBar.DISPLAY_SHOW_HOME);
// add the custom view to the action bar
actionBar.setCustomView(R.layout.actionbar_view);
field = (EditText)findViewById(R.id.urlField);
webView = (WebView)findViewById(R.id.webView1);
webView.setWebChromeClient(new MyWebViewClient());
Button openUrl = (Button) findViewById(R.id.button1);
openUrl.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
String url = field.getText().toString();
String prefix = "https://www.google.com/search?q=";
if(!url.startsWith("http://") && !url.startsWith("https://") && !url.endsWith(".com"))
{
url = prefix + url;
}
if(url.endsWith(".com") || url.endsWith(".as") || url.endsWith(".uk") || url.endsWith(".biz"))
{
if(!url.startsWith("http://") && !url.startsWith("https://"))
{
url = "http://" + url;
}
}
if (validateUrl(url)) {
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
MainActivity.this.progress.setProgress(0);
}
}
private boolean validateUrl(String url) {
return true;
}
});
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
@Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setTitle(mTitle);
}
private class MyWebViewClient extends WebChromeClient {
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView View, String url)
{
webView.loadUrl(url);
return true;
}
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack())
{
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
protected boolean validateUrl(String url) {
// TODO Auto-generated method stub
return false;
}
@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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
activity_main
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.--------------.MainActivity" >
<!--
As the main content view, the view below consumes the entire
space available using match_parent in both dimensions.
-->
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<WebView
android:id="@+id/webView1"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
tools:context=".MainActivity" />
<Button
android:id="@+id/button1"
android:onClick="onClick"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Go" />
</FrameLayout>
<!--
android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead.
-->
<!--
The drawer is given a fixed width in dp and extends the full height of
the container.
-->
<fragment
android:id="@+id/navigation_drawer"
android:name="com.example.minimalbrowserx.NavigationDrawerFragment"
android:layout_width="@dimen/navigation_drawer_width"
android:layout_height="match_parent"
actionbar_view
<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/urlField"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:imeOptions="actionDone"
android:inputType="textFilter"
android:text="no" >
</EditText>
Android 清单
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.------------"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
LogCat
03-25 18:52:13.301: D/AndroidRuntime(10241): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
03-25 18:52:13.311: D/AndroidRuntime(10241): CheckJNI is ON
03-25 18:52:13.411: D/dalvikvm(10241): Trying to load lib libjavacore.so 0x0
03-25 18:52:13.421: D/dalvikvm(10241): Added shared lib libjavacore.so 0x0
03-25 18:52:13.441: D/dalvikvm(10241): Trying to load lib libnativehelper.so 0x0
03-25 18:52:13.441: D/dalvikvm(10241): Added shared lib libnativehelper.so 0x0
03-25 18:52:13.441: D/dalvikvm(10241): No JNI_OnLoad found in libnativehelper.so 0x0, skipping init
03-25 18:52:13.711: D/dalvikvm(10241): Note: class Landroid/app/ActivityManagerNative; has 179 unimplemented (abstract) methods
03-25 18:52:14.381: E/memtrack(10241): Couldn't load memtrack module (No such file or directory)
03-25 18:52:14.381: E/android.os.Debug(10241): failed to load memtrack module: -2
03-25 18:52:14.781: D/AndroidRuntime(10241): Calling main entry com.android.commands.pm.Pm
03-25 18:52:14.831: D/AndroidRuntime(10241): Shutting down VM
03-25 18:52:14.831: D/dalvikvm(10241): Debugger has detached; object registry had 1 entries
03-25 18:52:15.631: D/AndroidRuntime(10252): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
03-25 18:52:15.641: D/AndroidRuntime(10252): CheckJNI is ON
03-25 18:52:15.741: D/dalvikvm(10252): Trying to load lib libjavacore.so 0x0
03-25 18:52:15.751: D/dalvikvm(10252): Added shared lib libjavacore.so 0x0
03-25 18:52:15.771: D/dalvikvm(10252): Trying to load lib libnativehelper.so 0x0
03-25 18:52:15.771: D/dalvikvm(10252): Added shared lib libnativehelper.so 0x0
03-25 18:52:15.781: D/dalvikvm(10252): No JNI_OnLoad found in libnativehelper.so 0x0, skipping init
03-25 18:52:16.031: D/dalvikvm(10252): Note: class Landroid/app/ActivityManagerNative; has 179 unimplemented (abstract) methods
03-25 18:52:16.721: E/memtrack(10252): Couldn't load memtrack module (No such file or directory)
03-25 18:52:16.721: E/android.os.Debug(10252): failed to load memtrack module: -2
03-25 18:52:17.191: D/AndroidRuntime(10252): Calling main entry com.android.commands.am.Am
03-25 18:52:17.271: I/ActivityManager(385): START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.example.minimalbrowserx/.MainActivity} from pid 10252
03-25 18:52:17.281: D/AndroidRuntime(10252): Shutting down VM
03-25 18:52:17.291: D/jdwp(10252): Got wake-up signal, bailing out of select
03-25 18:52:17.291: D/dalvikvm(10252): Debugger has detached; object registry had 1 entries
03-25 18:52:25.101: W/AwContents(10213): nativeOnDraw failed; clearing to background color.
03-25 18:52:25.161: E/SoundPool(385): error loading /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:25.161: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:25.161: E/SoundPool(385): error loading /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:25.161: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:25.171: E/SoundPool(385): error loading /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:25.171: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:25.171: E/SoundPool(385): error loading /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:25.171: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:25.171: E/SoundPool(385): error loading /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:25.171: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:25.171: E/SoundPool(385): error loading /system/media/audio/ui/KeypressStandard.ogg
03-25 18:52:25.171: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/KeypressStandard.ogg
03-25 18:52:25.171: E/SoundPool(385): error loading /system/media/audio/ui/KeypressSpacebar.ogg
03-25 18:52:25.171: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/KeypressSpacebar.ogg
03-25 18:52:25.171: E/SoundPool(385): error loading /system/media/audio/ui/KeypressDelete.ogg
03-25 18:52:25.171: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/KeypressDelete.ogg
03-25 18:52:25.171: E/SoundPool(385): error loading /system/media/audio/ui/KeypressReturn.ogg
03-25 18:52:25.171: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/KeypressReturn.ogg
03-25 18:52:25.171: E/SoundPool(385): error loading /system/media/audio/ui/KeypressInvalid.ogg
03-25 18:52:25.171: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/KeypressInvalid.ogg
03-25 18:52:25.171: W/AudioService(385): onLoadSoundEffects(), Error -1 while loading samples
03-25 18:52:25.361: D/AndroidRuntime(10213): Shutting down VM
03-25 18:52:25.361: W/dalvikvm(10213): threadid=1: thread exiting with uncaught exception (group=0xb3acbba8)
03-25 18:52:25.381: E/AndroidRuntime(10213): FATAL EXCEPTION: main
03-25 18:52:25.381: E/AndroidRuntime(10213): Process: com.example.minimalbrowserx, PID: 10213
03-25 18:52:25.381: E/AndroidRuntime(10213): java.lang.NullPointerException
03-25 18:52:25.381: E/AndroidRuntime(10213): at com.example.minimalbrowserx.MainActivity.onClick(MainActivity.java:105)
03-25 18:52:25.381: E/AndroidRuntime(10213): at android.view.View.performClick(View.java:4438)
03-25 18:52:25.381: E/AndroidRuntime(10213): at android.view.View$PerformClick.run(View.java:18422)
03-25 18:52:25.381: E/AndroidRuntime(10213): at android.os.Handler.handleCallback(Handler.java:733)
03-25 18:52:25.381: E/AndroidRuntime(10213): at android.os.Handler.dispatchMessage(Handler.java:95)
03-25 18:52:25.381: E/AndroidRuntime(10213): at android.os.Looper.loop(Looper.java:136)
03-25 18:52:25.381: E/AndroidRuntime(10213): at android.app.ActivityThread.main(ActivityThread.java:5017)
03-25 18:52:25.381: E/AndroidRuntime(10213): at java.lang.reflect.Method.invokeNative(Native Method)
03-25 18:52:25.381: E/AndroidRuntime(10213): at java.lang.reflect.Method.invoke(Method.java:515)
03-25 18:52:25.381: E/AndroidRuntime(10213): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-25 18:52:25.381: E/AndroidRuntime(10213): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-25 18:52:25.381: E/AndroidRuntime(10213): at dalvik.system.NativeStart.main(Native Method)
03-25 18:52:25.401: W/ActivityManager(385): Force finishing activity com.example.minimalbrowserx/.MainActivity
03-25 18:52:25.421: D/gralloc(54): Registering a buffer in the process that created it. This may cause memory ordering problems.
03-25 18:52:25.421: E/libEGL(54): called unimplemented OpenGL ES API
03-25 18:52:25.421: E/libEGL(54): called unimplemented OpenGL ES API
03-25 18:52:25.431: E/libEGL(54): called unimplemented OpenGL ES API
03-25 18:52:25.431: E/libEGL(54): called unimplemented OpenGL ES API
03-25 18:52:25.431: E/SurfaceFlinger(54): glCheckFramebufferStatusOES error 2139965326
03-25 18:52:25.431: E/SurfaceFlinger(54): got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot
03-25 18:52:25.441: E/libEGL(54): called unimplemented OpenGL ES API
03-25 18:52:25.441: E/libEGL(54): called unimplemented OpenGL ES API
03-25 18:52:25.441: W/WindowManager(385): Screenshot failure taking screenshot for (246x410) to layer 21010
03-25 18:52:25.731: I/Choreographer(385): Skipped 37 frames! The application may be doing too much work on its main thread.
03-25 18:52:26.241: W/ActivityManager(385): Activity pause timeout for ActivityRecord{b3dbeaa0 u0 com.example.minimalbrowserx/.MainActivity t135 f}
03-25 18:52:26.391: I/Choreographer(540): Skipped 32 frames! The application may be doing too much work on its main thread.
03-25 18:52:28.141: E/SoundPool(385): error loading /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:28.141: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:28.141: E/SoundPool(385): error loading /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:28.151: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:28.151: E/SoundPool(385): error loading /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:28.151: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:28.151: E/SoundPool(385): error loading /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:28.151: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:28.151: E/SoundPool(385): error loading /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:28.151: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
03-25 18:52:28.151: E/SoundPool(385): error loading /system/media/audio/ui/KeypressStandard.ogg
03-25 18:52:28.151: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/KeypressStandard.ogg
03-25 18:52:28.151: E/SoundPool(385): error loading /system/media/audio/ui/KeypressSpacebar.ogg
03-25 18:52:28.151: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/KeypressSpacebar.ogg
03-25 18:52:28.151: E/SoundPool(385): error loading /system/media/audio/ui/KeypressDelete.ogg
03-25 18:52:28.161: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/KeypressDelete.ogg
03-25 18:52:28.161: E/SoundPool(385): error loading /system/media/audio/ui/KeypressReturn.ogg
03-25 18:52:28.161: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/KeypressReturn.ogg
03-25 18:52:28.161: E/SoundPool(385): error loading /system/media/audio/ui/KeypressInvalid.ogg
03-25 18:52:28.161: W/AudioService(385): Soundpool could not load file: /system/media/audio/ui/KeypressInvalid.ogg
03-25 18:52:28.161: W/AudioService(385): onLoadSoundEffects(), Error -1 while loading samples
03-25 18:52:28.231: I/Process(10213): Sending signal. PID: 10213 SIG: 9
03-25 18:52:28.311: I/ActivityManager(385): Process com.example.minimalbrowserx (pid 10213) has died.
03-25 18:52:28.371: W/InputDispatcher(385): channel 'b4213d88 com.example.minimalbrowserx/com.example.minimalbrowserx.MainActivity (server)' ~ Consumer closed input channel or an error occurred. events=0x9
03-25 18:52:28.371: E/InputDispatcher(385): channel 'b4213d88 com.example.minimalbrowserx/com.example.minimalbrowserx.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
03-25 18:52:28.411: W/InputDispatcher(385): Attempted to unregister already unregistered input channel 'b4213d88 com.example.minimalbrowserx/com.example.minimalbrowserx.MainActivity (server)'
03-25 18:52:28.411: I/WindowState(385): WIN DEATH: Window{b4213d88 u0 com.example.minimalbrowserx/com.example.minimalbrowserx.MainActivity}
03-25 18:52:28.421: I/Choreographer(385): Skipped 34 frames! The application may be doing too much work on its main thread.
03-25 18:52:28.501: I/Choreographer(385): Skipped 95 frames! The application may be doing too much work on its main thread.
03-25 18:52:28.591: W/InputMethodManagerService(385): Got RemoteException sending setActive(false) notification to pid 10213 uid 10052
03-25 18:52:28.601: W/Binder(503): Caught a RuntimeException from the binder stub implementation.
03-25 18:52:28.601: W/Binder(503): java.lang.NullPointerException
03-25 18:52:28.601: W/Binder(503): at android.inputmethodservice.IInputMethodWrapper.setSessionEnabled(IInputMethodWrapper.java:280)
03-25 18:52:28.601: W/Binder(503): at com.android.internal.view.IInputMethod$Stub.onTransact(IInputMethod.java:129)
03-25 18:52:28.601: W/Binder(503): at android.os.Binder.execTransact(Binder.java:404)
03-25 18:52:28.601: W/Binder(503): at dalvik.system.NativeStart.run(Native Method)
03-25 18:52:28.691: I/Choreographer(385): Skipped 41 frames! The application may be doing too much work on its main thread.
03-25 18:53:21.601: D/LightsService(385): Excessive delay setting light: 155ms
03-25 19:03:19.131: D/ConnectivityService(385): Sampling interval elapsed, updating statistics ..
03-25 19:03:19.181: D/ConnectivityService(385): Done.
03-25 19:03:19.181: D/ConnectivityService(385): Setting timer for 720seconds
03-25 19:04:19.181: I/ProcessStatsService(385): Prepared write state in 5ms
03-25 19:04:19.191: I/ProcessStatsService(385): Prepared write state in 10ms
根据您的 logcat 看来您正在调用 progress.setProgress(0)
(第 105 行)但您尚未实例化 progress
ProgressBar
(因此它的值为null
)。这会导致 java.lang.NullPointerException
。在调用 setProgress(0)
之前实例化 progress
ProgressBar
。