我搜索过这个错误并找到了很多解决方案,但我无法解决这个问题,因为我是Android的初学者
这是我的主要活动
package ***.***.greytrix.test;
import android.app.LauncherActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.webkit.CookieManager;
public class MainActivity extends ActionBarActivity {
private WebView mWebView;
private Context context;
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
// please enter your sender id
String SENDER_ID = "11111111";
static final String TAG = "Pocket ";
GoogleCloudMessaging gcm;
TextView mDisplay;
String regid;
String fileurl="https://neel.test.com/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
if(checkPlayServices()){
gcm = GoogleCloudMessaging.getInstance(this);
regid = getRegistrationId(context);
//For Testing Purpose
new RegisterBackground().execute();
}
Bundle extras = getIntent().getExtras();
String url;
if (extras != null) {
url = extras.getString("url");
mWebView = (WebView) findViewById(R.id.activity_main_webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.getSettings().setDatabaseEnabled(true);
if (extras.getString("url").isEmpty()) {
mWebView.loadUrl("https://neel.test.com/");
} else {
mWebView.loadUrl(url);
}
mWebView.setWebViewClient(new MyAppWebViewClient());
} else {
mWebView = (WebView) findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setDatabaseEnabled(true);
fileurl = ReadFile();
if (fileurl == "") {
fileurl="https://neel.test.com/";
mWebView.loadUrl("https://neel.test.com/");
} else {
mWebView.loadUrl(fileurl);
}
mWebView.setWebViewClient(new MyAppWebViewClient());
}
}
private String ReadFile() {
String aBuffer = "";
try {
File myFile = new File(getFilesDir() + "/mysdfile.txt");
if (myFile.exists()) {
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
myReader.close();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
return aBuffer.trim();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, 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.SetURL) {
Intent nextscreen = new Intent(PayrollApplication.getContext(), SecondScreenActivity.class);
startActivity(nextscreen);
//setContentView(R.layout.seturl);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
@Override
protected void onResume(){
super.onResume();
checkPlayServices();
}
//New Code developed by Nilesh Gajare on 10th July 2015
class RegisterBackground extends AsyncTask<String,String,String> {
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regid;
Log.d("111", msg);
sendRegistrationIdToBackend();
// Persist the regID - no need to register again.
storeRegistrationId(context, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
@Override
protected void onPostExecute(String msg) {
//mDisplay.append(msg + "\n");
}
private void sendRegistrationIdToBackend() {
// Set Server URL for Storing Android Device Registration ID.
String CompanyCode= getCookie(fileurl,"CompanyId");
String UserName= getCookie(fileurl,"UserName");
String Password= getCookie(fileurl,"Password");
String url = "https://neel.test.com//api/v1.0/SaveAndroidRegId?RegId="+regid+"&CompanyId="+CompanyCode+"&UserName="+UserName+"&Password="+Password ;
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
Log.i(TAG,httpResponse.getStatusLine().toString());
Log.i(TAG,httpResponse.getEntity().toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGCMPreferences(context);
int appVersion = getAppVersion(context);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
private SharedPreferences getGCMPreferences(Context context) {
return getSharedPreferences(MainActivity.class.getSimpleName(),
Context.MODE_PRIVATE);
}
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
public String getCookie(String siteName,String CookieName){
String CookieValue = null;
CookieManager cookieManager = CookieManager.getInstance();
String cookies = cookieManager.getCookie(siteName);
if(cookies != null) {
String[] temp = cookies.split(";");
for (String ar1 : temp) {
if (ar1.contains(CookieName)) {
String[] temp1 = ar1.split("=");
CookieValue = temp1[1];
}
}
}
return CookieValue;
}
}
在MainActivy.xml中,我得到了以下代码:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity">
<WebView
android:id="@+id/activity_main_webview"
android:layout_width="fill_parent"
android:layout_height= "fill_parent"
android:layout_weight="1.0" />
</RelativeLayout>
堆栈跟踪
处理:com.pockethcm.xxx.test,PID:2347 java.lang.RuntimeException:无法启动活动ComponentInfo {xxx.xxx.xxx.test / xxx.xxx.xxx.test.MainActivity}: java.lang.NullPointerException:尝试调用虚方法 '对象引用上的'boolean java.lang.String.isEmpty()' 在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298) 在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) 在android.app.ActivityThread.access $ 800(ActivityThread.java:144) 在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1278) 在android.os.Handler.dispatchMessage(Handler.java:102) 在android.os.Looper.loop(Looper.java:135) 在android.app.ActivityThread.main(ActivityThread.java:5221) at java.lang.reflect.Method.invoke(Native Method) 在java.lang.reflect.Method.invoke(Method.java:372) 在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:899) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 引发者:java.lang.NullPointerException:尝试在空对象上调用虚方法'boolean java.lang.String.isEmpty()' 参考 at selfservice.pockethcm.greytrix.test.MainActivity.onCreate(MainActivity.java:106) 在android.app.Activity.performCreate(Activity.java:5937) 在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105) 在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251) 在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) 在android.app.ActivityThread.access $ 800(ActivityThread.java:144) 在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1278) 在android.os.Handler.dispatchMessage(Handler.java:102) 在android.os.Looper.loop(Looper.java:135) 在android.app.ActivityThread.main(ActivityThread.java:5221) at java.lang.reflect.Method.invoke(Native Method) 在java.lang.reflect.Method.invoke(Method.java:372) 在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:899) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)设备 离线
清单如下所示
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="selfservice.xxx.xxx.test"
android:versionCode="2"
android:versionName="1.1">
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER"/>
<permission
android:name="selfservice.xxx.xxx.test.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="selfservice.xxx.xxx.test.gcm.permission.C2D_MESSAGE" />
<application
android:name="selfservice.xxx.xxx.test.PayrollApplication"
android:allowBackup="true"
android:icon="@mipmap/icon_pocket"
android:label="Pocket HCM"
android:theme="@style/AppTheme">
<activity
android:name="selfservice.xxx.xxx.test.MainActivity"
android:label="Pocket HCM"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="selfservice.xxx.xxx.test.SecondScreenActivity"
android:screenOrientation="portrait"></activity>
<receiver
android:name="selfservice.xxx.xxx.test.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="selfservice.xxx.xxx.test" />
</intent-filter>
</receiver>
<service android:name="selfservice.xxx.xxx.test.GcmIntentService" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<activity
android:name="selfservice.pockethcm.greytrix.test.ReceiveActivity">
</activity>
</application>
</manifest>
它在安装应用程序后第一次工作但是当我们关闭并重新打开时崩溃不幸的是App已经关闭 你有任何想法吗,我将不胜感激:)
谢谢!
答案 0 :(得分:1)
这是抛出NPE的罪魁祸首:
<div class="col-sm-4 col-md-4 col-lg-4 removeOutline" tabindex="3">
<div class="form-group has-feedback has-clear searchManual">
</div>
</div>
如果if (extras.getString("url").isEmpty()) {
为url
,则应在此处进行检查:
null