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

无法启动活动ComponentInfo:java.lang.NullPointerException

丁子石
2023-03-14

我已经搜索了这个错误,并找到了许多解决方案,但我无法解决这个问题,因为我是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;
    }


}
<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>

舱单在下面

<?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>

安装应用程序后,它第一次工作,但当我们关闭并重新打开时,它崩溃了,不幸的是,应用程序已经关闭,你有任何想法,它将非常感谢:)

谢了!

共有1个答案

壤驷德寿
2023-03-14

以下是抛出NPE的罪魁祸首:

if (extras.getString("url").isEmpty()) {

您应该在此处检查URL是否为null:

url = extras.getString("url");
if(url == null){
Log.d("url status","its null");
}
 类似资料:
  • 问题内容: 在添加异步任务之前,我已经对代码进行了一些更改,我的应用程序可以正常运行其远程服务器上的身份验证用户名和密码,但是在登录成功消息消失后​​无法启动其他活动。有人建议我现在添加一个异步任务,但是我输入正确的用户名和密码后它将停止工作。当我输入错误的用户名和密码时,其工作正常将显示错误的用户名密码消息。如果有人能够知道会出现什么错误,请帮助我。 码- 日志猫 QuestionnActivi

  • 错误是: 错误:(50,17)错误:没有为startActivities(Intent)方法Activity找到合适的方法。startActivities(Intent[],Bundle)不适用(实际和正式的参数列表长度不同)方法Activity.startActivities(Intent[])方法上下文twrapper.startactivities(Intent[],Bundle)不适用(实

  • MainFormular.java 在Android.app.activity.performCreate(activity_main_formular 洛克卡特

  • 我在运行android应用程序时遇到这个错误 05-25 23:58:44.251:E/AndroidRuntime(1128):java.lang.RuntimeException:无法启动activity ComponentInfo{info.AndroidHive.TabsSwipe/Info.AndroidHive.TabsSwipe.MainActivity}:Android.View.

  • 我怎样才能解决这类问题?问题在于setOnClickListener,它给了我一个NullPointerException。如果你还需要什么,请告诉我。 这是日志中的错误: