无法实例化服务java.lang.NullPointerException

时间:2015-12-06 06:05:20

标签: java android

我试图通过Android项目培训制作迷你yamba.newcircle.com。我在互联网不可用时保存文本消息,如果互联网启动,则保存连接广播接收器。此应用程序会自动启动一个服务,该服务循环将ActiveAndroid中所有已保存的文本行从表中,通过HTTP帖子推送到Web API。

当我关闭Wifi时,使用ActiveAndroid保存一些消息,然后重新打开Wifi;如果我的应用程序连接,它只会与NullPointereException崩溃。

有什么建议吗?

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="pt.flag.miniyamba" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


    <application
        android:name="MiniYamba"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <meta-data
            android:name="AA_DB_NAME"
            android:value="yamba.db" />
        <meta-data
            android:name="AA_DB_VERSION"
            android:value="5" />

        <activity android:name=".Main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".OnlineStatus" >
        </activity>
        <activity android:name=".OfflineStatus" >
        </activity>
        <activity android:name=".SingleStatus" >
        </activity>
        <activity android:name=".NewStatus" >
        </activity>

        <receiver android:name=".NetworkBroadCastReceiver">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE"></action>
            </intent-filter>
        </receiver>
        <service android:name=".PushOfflineSavedService"/>

    </application>

</manifest>

broacast

public class NetworkBroadCastReceiver extends BroadcastReceiver {

    private Context mContext;

    @Override
    public void onReceive(Context context, Intent intent) {

        ConnectivityManager manager =(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = manager.getActiveNetworkInfo();

        if(netInfo != null && netInfo.isConnectedOrConnecting()){
            Toast.makeText(context, "net is up, pushing our previous offline saved posts ", Toast.LENGTH_SHORT).show();

            //inicializar o servico de push de posts, guardados anteriormente

            Intent novointent = new Intent(context, PushOfflineSavedService.class);
            context.startService(novointent);
        }
        //mudou de conectividade, mas nao tem internet
        else{
            Toast.makeText(context, "Connectivity is changed. Internet seens not working.", Toast.LENGTH_SHORT).show();
        }

    }



}

intentservice

public class PushOfflineSavedService extends IntentService {

    private String LOG_TAG;

    public PushOfflineSavedService() {

        super("PushOfflineSavedService");
        ActiveAndroid.initialize(this);
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        //enviar os status guardados, por enviar

        List<OfflinePostToSend> lista = new Select().from(OfflinePostToSend.class).execute();

        //loop para enviar os status
        if (lista.size() > 0) {

            for (int i = 0; i < lista.size(); i++) {

                HttpURLConnection urlConnection = null;
                BufferedReader reader = null;

                try {
                    String path = "http://yamba.newcircle.com/api/statuses/update.json";
                    String status = lista.get(i).getText();

                    URL url = new URL(path);
                    String userPass = "student:password";
                    String token = "Basic " + Base64.encodeToString(userPass.getBytes(), Base64.NO_WRAP);
                    urlConnection = (HttpURLConnection) url.openConnection();
                    urlConnection.setRequestMethod("POST");
                    // Adicionar o token como header do pedido
                    urlConnection.addRequestProperty("Authorization", token);
                    urlConnection.setDoOutput(true);

                    String postParameters = "status="+status;
                    urlConnection.setFixedLengthStreamingMode(postParameters.getBytes().length);
                    urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

                    // Adicionar o status ao método post
                    PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
                    out.print(postParameters);
                    out.close();

                    reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(urlConnection.getInputStream())));
                    StringBuilder buffer = new StringBuilder();

                    String line;
                    while ((line = reader.readLine()) != null) {
                        buffer.append(line);
                        buffer.append("\n");
                    }
                    //se buffer nao for full, temos 1 respota do API
                    if (buffer.length() != 0) {
                        // Stream was NOT empty.
                        //apagar este elemento da lista e da db

                        lista.get(i).delete();

                    }

                    //return buffer.toString();

                } catch (IOException e) {
                    Log.e(LOG_TAG, "Error ", e);
                } finally {
                    if (urlConnection != null) {
                        urlConnection.disconnect();
                    }
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (final IOException e) {
                            Log.e(LOG_TAG, "Error closing stream", e);
                        }
                    }
                }
            }
        }

    }
}

1 个答案:

答案 0 :(得分:0)

ActiveAndroid guideApplication子类中显示对initialize()的调用,如下所示:

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        ActiveAndroid.initialize(this);
    }
}

尝试扩展应用并将initialize()电话放在那里而不是服务中。