Brian Koey
Brian Koey

Reputation: 203

Android Bind Service Issue

I don't understand why plainText = mService.getPlainText(key, cipherText); in the crackingProcess class causes an error. If I put the line in the buttonclick, it works. Can anyone explain to me what is wrong?

public class CrackingProcess extends Activity {

TextView message;
TextView result;
DesService mService;
boolean mBound = false;
Button btnStop;
String[] stringResult;
String key;
String cipherText;
String plainText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cracking_process);

    message = (TextView) findViewById(R.id.message);
    btnStop = (Button) findViewById(R.id.btnStop);
    result = (TextView) findViewById(R.id.result);
    message.setText("Cracking In Progress...");

    doBindService();
}

@Override
protected void onStart() {
    super.onStart();

    try {       
        AssetManager fileManager = getAssets();
        InputStream fileInput = fileManager.open("json_block56");
        Reader fileRead = new InputStreamReader(fileInput);
        JsonReader reader = new JsonReader(fileRead);

        stringResult = readJson(reader);

        key = stringResult[1];
        Log.d("key", key);
        cipherText = stringResult[2];
        Log.d("text", cipherText);

        plainText = mService.getPlainText(key, cipherText); // This line cause error
        result.setText(plainText);

    } catch (IOException e) {
        e.printStackTrace();
    }


    btnStop.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {    
            if (mBound) {
                unbindService(mConnection);
                mBound = false;
            }
            finish();
        }
    });
}

private String[] readJson(JsonReader reader) throws IOException {
    String[] array = new String[3];
    String type = "";
    String key = "";
    String cipherText = "";
//  ArrayList<String> result = null;

    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        if (name.equals("reply")) {
            reader.beginObject();
            while (reader.hasNext()) {
                String newName = reader.nextName();
                if (newName.equals("type"))
                    type = reader.nextString();
                else if (newName.equals("key"))
                    key = reader.nextString();
                else if (newName.equals("ciphertext"))
                    cipherText = reader.nextString();
                else
                    reader.skipValue();
            }
            reader.endObject();
        } else
            reader.skipValue();
    }
    reader.endObject();

    array[0] = type;
    array[1] = key;
    array[2] = cipherText;

    return array;
}

public ServiceConnection mConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        mService = ((DesService.LocalBinder)service).getService();
        mBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        mService = null;
        //mBound = false;
    }

};

void doBindService() {
    Intent intent = new Intent(this, DesService.class);
    startService(intent);
    boolean bound = bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

    if ( bound ) {
        Log.d( "Sucess", "Successfully bound to service" );
    }
    else {
        Log.d( "Fail", "Failed to bind service" );
    }
}

}

DESService class

public class DesService extends Service {

private final IBinder mBinder = new LocalBinder();

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub
    return super.onStartCommand(intent, flags, startId);
}

public class LocalBinder extends Binder {

    public DesService getService() {
        return DesService.this;
    }

}

public String getPlainText(String key, String cipherText) {
     return "testing";  
}  

}

LogCat

10-05 18:29:13.893: D/AndroidRuntime(8026): Shutting down VM
10-05 18:29:13.893: W/dalvikvm(8026): threadid=1: thread exiting with uncaught exception (group=0xa62c5288)
10-05 18:29:13.897: E/AndroidRuntime(8026): FATAL EXCEPTION: main
10-05 18:29:13.897: E/AndroidRuntime(8026): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.androiddes/com.example.androiddes.CrackingProcess}: java.lang.NullPointerException
10-05 18:29:13.897: E/AndroidRuntime(8026):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at android.app.ActivityThread.access$600(ActivityThread.java:130)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at android.os.Handler.dispatchMessage(Handler.java:99)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at android.os.Looper.loop(Looper.java:137)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at android.app.ActivityThread.main(ActivityThread.java:4745)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at java.lang.reflect.Method.invokeNative(Native Method)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at java.lang.reflect.Method.invoke(Method.java:511)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at dalvik.system.NativeStart.main(Native Method)
10-05 18:29:13.897: E/AndroidRuntime(8026): Caused by: java.lang.NullPointerException
10-05 18:29:13.897: E/AndroidRuntime(8026):     at com.example.androiddes.CrackingProcess.onStart(CrackingProcess.java:63)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1163)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at android.app.Activity.performStart(Activity.java:5018)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2032)
10-05 18:29:13.897: E/AndroidRuntime(8026):     ... 11 more

Upvotes: 0

Views: 161

Answers (3)

jboi
jboi

Reputation: 11912

A positive result from bindService() means, that you will get the service. It does not mean, that it already happened, so mService will be null.

Your line in question plainText = mService.getPlainText(key, cipherText); can only work after or within onServiceConnected() - and before onServiceDisconnected().

Upvotes: 0

Matt Logan
Matt Logan

Reputation: 5926

It looks like your mService object is uninitialized when you call the getPlainText method on it, causing a null pointer exception.

Wait to call getPlainText until after mService is initialized in OnServiceConnected.

Upvotes: 0

dnkoutso
dnkoutso

Reputation: 6061

The actual connection to the service has not yet been established despite the fact the method bindService() returns true.

Binding to a service of a different process (IPC) is asynchronous. You cannot use the service until onServiceConnected() has been invoked. onStart() is too early in that process and thats why mService is null.

This also explains why putting your code in the buttons click listener works. By the time you tap the button the connection has been established.

Upvotes: 1

Related Questions