android - Android 中的 java.lang.NullPointerException

标签 android nullpointerexception broadcastreceiver bootcompleted

我遇到了一个关于 NullPointerException 的问题,我无法在我的代码中找出问题所在。请帮帮我。

java.lang.RuntimeException: Unable to start receiver me.radhakrishna.buddyreader.TextMessageReceiver: java.lang.NullPointerException
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2146)
at android.app.ActivityThread.access$1500(ActivityThread.java:127)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1208)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4441)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at me.radhakrishna.buddyreader.MainActivity.stopReading(MainActivity.java:81)
at me.radhakrishna.buddyreader.TextMessageReceiver.onReceive(TextMessageReceiver.java:59)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2139)
... 10 more

我的 list 文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="me.radhakrishna.buddyreader"
    android:versionCode="14"
    android:versionName="1.2.2" >

    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="me.radhakrishna.buddyreader.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>
        <activity
            android:name="me.radhakrishna.buddyreader.MessageActivity"
            android:label="@string/app_name" >
        </activity>
        <activity
            android:name="me.radhakrishna.buddyreader.PreferActivity"
            android:label="@string/app_name" >
        </activity>
        <receiver android:name="me.radhakrishna.buddyreader.TextMessageReceiver" android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

我的 TextMessageReceiver.java 文件:

package me.radhakrishna.buddyreader;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.PhoneLookup;
import android.telephony.SmsMessage;

public class TextMessageReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent){

        if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
            String val="";
            FileInputStream fileos;
            try {
                fileos = context.getApplicationContext().openFileInput("startup");
                byte[] input = new byte[fileos.available()];
                while(fileos.read(input) != -1){
                    val += new String(input);
                }
                if(val.equals("ON")){
                    Intent myIntent = new Intent(context, MainActivity.class);
                    myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(myIntent);
                }
                fileos.close();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        Bundle bundle=intent.getExtras();
        Object[] messages=(Object[])bundle.get("pdus");
        SmsMessage[] sms=new SmsMessage[messages.length];

        for(int n=0;n<messages.length;n++){
            sms[n]=SmsMessage.createFromPdu((byte[]) messages[n]);
        }

        for(SmsMessage msg:sms){
            final String mobileNum = msg.getOriginatingAddress();
            Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(mobileNum));           
            Cursor cursor= context.getContentResolver().query(uri, new String[]{PhoneLookup.DISPLAY_NAME},null,null,null);

            final MainActivity main = new MainActivity();
            main.stopReading();
            main.setSpeechSpeed();
            String messageFormat = "Message from "+mobileNum+". Message: "+msg.getMessageBody();
            FileOutputStream fos;
            try {
                fos = context.getApplicationContext().openFileOutput("lastmessage",Context.MODE_PRIVATE);
                fos.write(messageFormat.toString().getBytes());
                fos.close();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            if (cursor.getCount()>0){
                cursor.moveToFirst();
                String contactName = cursor.getString(0);
                cursor.close();

                String enteredText = "Excuse me sir, You got a message from "+contactName+". Message, "+msg.getMessageBody();
                String words = enteredText.toString();
                main.speakWords(words);
            }else{
                String enteredText = "Excuse me sir, You got a message from "+mobileNum+". Message, "+msg.getMessageBody();
                String words = enteredText.toString();
                main.speakWords(words);
            }
        }
    }
}

提前致谢。

最佳答案

请不要从 Activity 中读取函数,因为您不知道它何时处于 Activity 状态。我几个月遇到了类似的问题。所以把这个函数写在一个普通的类中然后使用它。

关于android - Android 中的 java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15500422/

相关文章:

android - 从string.xml获取app_name以获取Gradle中的当前产品 flavor

Android uber 错误 No authentication challenges found

java - 视频播放器工作室mp4

java - UUID 返回空指针异常

java - 服务在模拟器上启动但在设备上不启动

android - 与 android.widget.AbsListView.obtainView(AbsListView.java :2275)) 相关的 NullPointerException

java - 什么是NullPointerException,我该如何解决?

android - 从最近的应用程序列表/任务管理器中排除广播接收器

android - 无法在我的 Android 应用程序中接收短信

android - 扩展FragmentStateAdapter时各个构造函数有什么区别?