0

我不明白为什么plainText = mService.getPlainText(key, cipherText);crackingProcess课堂上会导致错误。如果我把线放在 中buttonclick,它可以工作。谁能向我解释什么是错的?

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" );
    }
}

}

DES服务类

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

}

日志猫

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
4

3 回答 3

1

bindService()尽管方法返回,但与服务的实际连接尚未建立true

绑定到不同进程 (IPC) 的服务是异步的。onServiceConnected()在被调用之前,您不能使用该服务。onStart()在那个过程中为时过早,这就是mService为什么null

这也解释了为什么将代码放在按钮单击侦听器中有效。当您点击按钮时,连接已建立。

于 2013-10-05T18:42:36.000 回答
0

mService当您在其上调用方法时,您的对象似乎未初始化getPlainText,从而导致空指针异常。

等待调用getPlainText,直到 aftermService被初始化OnServiceConnected

于 2013-10-05T18:43:27.463 回答
0

积极的结果 bindService()意味着您获得服务。这并不意味着它已经发生,因此mService将为空。

您有问题的行plainText = mService.getPlainText(key, cipherText);只能在 after 或 within onServiceConnected()- and before工作onServiceDisconnected()

于 2013-10-05T18:48:45.963 回答