java - 通知启动时出现 NullPointerException

标签 java android

我想在 onPostExecute 方法之后执行通知。 我将 android-support-v4.jar 添加到 libs 文件夹,然后添加到构建路径。 ConnectivityChangeReceiver 类用于了解设备何时连接到互联网。 我的解析没问题。 但我收到这些错误:

03-13 23:38:57.366: E/TAG(24253): TAGTTTTTTTTTTTT
03-13 23:38:59.231: E/TAG(24253): TAG
03-13 23:38:59.236: E/AndroidRuntime(24253): FATAL EXCEPTION: main
03-13 23:38:59.236: E/AndroidRuntime(24253): java.lang.NullPointerException
03-13 23:38:59.236: E/AndroidRuntime(24253):    at com.example.ex80.ConnectivityChangeReceiver$CheckUpdate.onPostExecute(ConnectivityChangeReceiver.java:158)
03-13 23:38:59.236: E/AndroidRuntime(24253):    at com.example.ex80.ConnectivityChangeReceiver$CheckUpdate.onPostExecute(ConnectivityChangeReceiver.java:1)
03-13 23:38:59.236: E/AndroidRuntime(24253):    at android.os.AsyncTask.finish(AsyncTask.java:631)
03-13 23:38:59.236: E/AndroidRuntime(24253):    at android.os.AsyncTask.access$600(AsyncTask.java:177)
03-13 23:38:59.236: E/AndroidRuntime(24253):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
03-13 23:38:59.236: E/AndroidRuntime(24253):    at android.os.Handler.dispatchMessage(Handler.java:99)
03-13 23:38:59.236: E/AndroidRuntime(24253):    at android.os.Looper.loop(Looper.java:137)
03-13 23:38:59.236: E/AndroidRuntime(24253):    at android.app.ActivityThread.main(ActivityThread.java:5328)
03-13 23:38:59.236: E/AndroidRuntime(24253):    at java.lang.reflect.Method.invokeNative(Native Method)
03-13 23:38:59.236: E/AndroidRuntime(24253):    at java.lang.reflect.Method.invoke(Method.java:511)
03-13 23:38:59.236: E/AndroidRuntime(24253):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
03-13 23:38:59.236: E/AndroidRuntime(24253):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
03-13 23:38:59.236: E/AndroidRuntime(24253):    at dalvik.system.NativeStart.main(Native Method)
<小时/>

我的广播接收器:

public class ConnectivityChangeReceiver extends BroadcastReceiver {

    int version ;
    boolean shoudupdate = false ;
    boolean isconnectd  = false ;
    NotificationManager notificationManager = null ;
    Notification notification = null ;
    @SuppressLint("NewApi")
    @Override
    public void onReceive(Context context, Intent intent) {


        Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Intent myintent = new Intent(context, MainActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(context, 0, myintent, 0);


        Notification.Builder builder = new Notification.Builder(context);

        builder.setContentIntent(pIntent)
            .setSmallIcon(R.drawable.ic_launcher)
            .setTicker("notificationMessage")
            .setWhen(System.currentTimeMillis())
            .setAutoCancel(true)
            .setSound(soundUri)
            .setContentTitle("newNotificationsCount" + " New Notifications")
            .setContentText("notificationMessage");
        notification = builder.getNotification();   



        //
        PackageInfo pInfo = null;
        try {
            pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        version    = pInfo.versionCode;
        isconnectd = isConnected(context);
        Log.e("TAG", "TAGTTTTTTTTTTTT");

        new CheckUpdate().execute((Void)null);
    }

 public  boolean isConnected(Context context) {
           ConnectivityManager connectivityManager = ((ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE));
           NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
           return networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected();
   }



    private void shoudUpdate(){
        URL url ;

        try{
            String feed = "*********************.xml" ;
        url = new URL(feed);
        URLConnection connection ;
        connection = url.openConnection();
        HttpURLConnection httpconnection = (HttpURLConnection)connection;
        int responsecode = httpconnection.getResponseCode();

        if(responsecode == HttpURLConnection.HTTP_OK){

            InputStream in = httpconnection.getInputStream();
            DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder() ;

            Document dom = db.parse(in);
            Element docelm = dom.getDocumentElement();
            NodeList nl = docelm.getElementsByTagName("item");
            if(nl != null && nl.getLength() > 0 ){
                    //get version
                    Element entry = (Element)nl.item(0);
                    Element vs = (Element)entry.getElementsByTagName("version").item(0);
                    String updateversion = vs.getFirstChild().getNodeValue();

                    int currentversion = version ;

                    if(currentversion < Integer.parseInt(updateversion)){
                        shoudupdate = true ;
                    }else
                        shoudupdate = false ;
            }

        }


        } catch (SAXException e) {
            // TODO: handle exception
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    private class CheckUpdate extends AsyncTask<Void, Void, Void>{

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            shoudUpdate();
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            if(isconnectd==true && shoudupdate==true){
                Log.e("TAG", "TAG");
                notificationManager.notify(0, notification);  
            }
            super.onPostExecute(result);
        }

    }

}
<小时/>

我的 list :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.ex80"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.ex80.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>
<receiver android:name=".ConnectivityChangeReceiver" >
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>        
    </application>

</manifest>

最佳答案

您没有初始化 notificationManager 属性:

NotificationManager notificationManager = (NotificationManager) 
                  getSystemService(NOTIFICATION_SERVICE);

请添加以上行并再次检查。

关于java - 通知启动时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22390213/

相关文章:

android - 从字符串中获取布局 ID,将不起作用

android - 你如何解析一个相对的 Uri?

java - Java EE Web 应用程序的架构

Java Android异常,错误内容必须有一个id为android.R.id.list的ListView。机器人 :id="@android:id/list Does Not fix Issue

java - 如何使用 XMLDog 从 xml 文件中检索值

Java - JMF 无法添加捕获或视频设备

java - Wicket 口、身份验证和交易界定

Android GPS定位问题

java - 使用 AIDL 在两个进程之间传输 Parcelable

java - Android 将页脚添加到 ListView addFooterView()?