Null pointer exception probably due to synchronisation issues; problem in starting activity
I have a small app which is the client running on Android emulator. Server (small Java app in Eclipse) keeps sending strings. Client will receive these strings and display an image if a string in the correct format and right contents is received.
I send two strings-one with wrong content and the other with correct content. Both strings are received. For the string with wrong content, the appropriate message is shown. But when the string with correct content is received, an image is supposed to be shown. But this doesn't happen. I get a warning "Activity pause timeout for HistoryRecord" and then error.
Code and LogCat below.
Please help me with this.
Thank you for time spent and efforts put on this.
Cheers, Madhu
Main activity
public class TCPListen extends Activity implements TCPListener {
private TextView mTitle;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
// Set up the window layout
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
// Set up the custom title
mTitle = (TextView) findViewById(R.id.title_left_text);
mTitle.setText(R.string.app_name);
mTitle = (TextView) findViewById(R.id.title_right_text);
TcpServiceHandler handler=new TcpServiceHandler(this);
handler.execute("192.168.62.23");
}
public void callCompleted(String tempStr){
String source = tempStr;
//Log.d("TCP", "C: In the main" + " " + source);
mTitle.setText(source);
if(source.matches("<MSG><N>.*<!N><V>.*<!V><!MSG>")) {
//mTitle.setText(source1);
//tempStr = "";
//String source = "<MSG><N>shiftDirection<!N><V>1<!V><!MSG>";
// Match characters lying before message name
String find1 = "<MSG><N>";
// Match characters lying before message value
String find2 = ".*<!N><V>";
// Mask the characters by replacing them with blank space
String replace = "";
// Mask the characters lying before message name
Pattern pattern = Pattern.compile(find1);
Matcher matcher = pattern.matcher(source);
String output = matcher.replaceAll(replace);
// Split the message and extract message name
String name1[] = output.split("<!N>");
String msgName = name1[0];
//Log.i(TAG, "Message name is" + msgName);
//Mask the characters lying before message value
Pattern pattern1 = Pattern.compile(find2);
Matcher matcher1 = pattern1.matcher(output);
String output1 = matcher1.replaceAll(replace);
//Split the remaining message and extract message value
String val1[] = output1.split("<!V>");
String actVal = val1[0];
//Log.d("TCP", msgName);
//Pass the message name and value for further action
double msgValue = Integer.parseInt(actVal);
actionOnData(msgName, msgValue);
} else Log.i("TCP", "Wrong message" + source);
}
//Function to display driver messages/images based on individual messages
public void actionOnData(String name, double value) {
String tempName = name;
double tempVal = value;
//while (true) {
if(tempName.equals("shiftDirection") && tempVal == 1) {
Log.d("TCP","C: " + tempName + " " + tempVal);
Intent myIntent = new Intent();
myIntent.setClassName("com.example.android.TCPListen", "com.example.android.TCPListen.Images");
//myIntent.putExtra("Change gear", "Shift to next gear!"); // key/value pair, where key needs current package prefix.
startActivity(myIntent);
} else Log.d("TCP", "Just show an image");
//}
}
}
Interface
package com.example.android.TCPListen;
public interface TCPListener {
public void callCompleted(String msg);
}
Async Task
public class TcpServiceHandler extends AsyncTask<String, Integer, ArrayList<String>>{
TCPListener _listener;
public TcpServiceHandler(TCPListener listener){
_listener=listener;
}
//@Override
//protected void onPreExecute() {
//you may wish to show a wait screen here
//}
@Override
protected ArrayList<String> doInBackground(String... params) {
//you should do the desktop app connectivity part here
ArrayList<String> StrArr = new ArrayList<String>();
String str = "";
//String str = "";
//while (true) {
try{
//response=//stream received from desktop app
InetAddress serverAddr = InetAddress.getByName("192.168.62.23");
Log.d("TCP", "C: Connecting...");
Socket socket = new Socket(serverAddr, 1200);
Log.d("TCP", "C: Receiving...");
//char[] buffer = new char[1024];
//int bytes;
//String end = "<!MSG>";
//StringBuilder curMsg = new StringBuilder();
try {
for(int i = 0; i < 100; i++) {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
StrArr.add(in.readLine());
//while(str != null) {
// StrArr.add(str);
//}
//StrArr.add(str);
//return str;
}
//return str;
//Pass str to main activity for parsing
//mHandler.obtainMessage(TCPIPCommn.INCOMING_MESSAGE, str).sendToTarget();
} catch(Exception e) {
Log.d("TCP","C: Error", e);
e.printStackTrace();
} finally {
socket.close();
Log.d("TCP","C: Done danaadan.");
}
}
catch(Exception e){}
return StrArr;
//return str;
//}
}
@Override
protected void onPostExecute(ArrayList<String> responseMessage) {
//notify your activity that you have received message from desktop app
for (int i = 0; i < responseMessage.size(); i++) {
String RetStr = responseMessage.get(i);
_listener.callCompleted(RetStr);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
Log.d("TCP","C:Wait error", e);
e.printStackTrace();
}
}
}
}
![alt text][1]
01-10 14:06:30.258: DEBUG/AndroidRuntime(340): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
01-10 14:06:30.258: DEBUG/AndroidRuntime(340): CheckJNI is ON
01-10 14:06:30.457: DEBUG/AndroidRuntime(340): --- registering native functions ---
01-10 14:06:31.728: DEBUG/dalvikvm(236): GC_EXPLICIT freed 85 objects / 4160 bytes in 137ms
01-10 14:06:31.796: DEBUG/PackageParser(58): Scanning package: /data/app/vmdl72299.tmp
01-10 14:06:31.966: INFO/PackageManager(58): Removing non-system package:com.example.android.TCPListen
01-10 14:06:31.966: INFO/ActivityManager(58): Force stopping package com.example.android.TCPListen uid=10037
01-10 14:06:32.197: DEBUG/PackageManager(58): Scanning package com.example.android.TCPListen
01-10 14:06:32.207: INFO/PackageManager(58): Package com.example.android.TCPListen codePath changed from /data/app/com.example.android.TCPListen-2.apk to /data/app/com.example.android.TCPListen-1.apk; Retaining data and using new
01-10 14:06:32.216: INFO/PackageManager(58): /data/app/com.example.android.TCPListen-1.apk changed; unpacking
01-10 14:06:32.238: DEBUG/installd(34): DexInv: --- BEGIN '/data/app/com.example.android.TCPListen-1.apk' ---
01-10 14:06:32.537: DEBUG/dalvikvm(347): DexOpt: load 40ms, verify 99ms, opt 2ms
01-10 14:06:32.556: DEBUG/installd(34): DexInv: --- END '/data/app/com.example.android.TCPListen-1.apk' (success) ---
01-10 14:06:32.568: WARN/PackageManager(58): Code path for pkg : com.example.android.TCPListen changing from /data/app/com.example.android.TCPListen-2.apk to /data/app/com.example.android.TCPListen-1.apk
01-10 14:06:32.568: WARN/PackageManager(58): Resource path for pkg : com.example.android.TCPListen changing from /data/app/com.example.android.TCPListen-2.apk to /data/app/com.example.android.TCPListen-1.apk
01-10 14:06:32.568: DEBUG/PackageManager(58): Activities: com.example.android.TCPListen.TCPListen com.example.android.TCPListen.Images
01-10 14:06:32.587: INFO/ActivityManager(58): Force stopping package com.example.android.TCPListen uid=10037
01-10 14:06:32.847: DEBUG/dalvikvm(58): GC_FOR_MALLOC freed 6453 objects / 401352 bytes in 116ms
01-10 14:06:32.918: INFO/installd(34): move /data/dalvik-cache/data@app@com.example.android.TCPListen-1.apk@classes.dex -> /data/dalvik-cache/data@app@com.example.android.TCPListen-1.apk@classes.dex
01-10 14:06:32.918: DEBUG/PackageManager(58): New package installed in /data/app/com.example.android.TCPListen-1.apk
01-10 14:06:33.078: INFO/ActivityManager(58): Force stopping package com.example.android.TCPListen uid=10037
01-10 14:06:33.177: DEBUG/dalvikvm(123): GC_EXPLICIT freed 265 objects / 12104 bytes in 96ms
01-10 14:06:33.287: DEBUG/dalvikvm(121): GC_EXPLICIT freed 762 objects / 42224 bytes in 140ms
01-10 14:06:33.507: WARN/RecognitionManagerService(58): no available voice recognition services found
01-10 14:06:33.648: DEBUG/dalvikvm(156): GC_EXPLICIT freed 251 objects / 11976 bytes in 393ms
01-10 14:06:33.797: DEBUG/dalvikvm(58): GC_EXPLICIT freed 4743 objects / 307528 bytes in 146ms
01-10 14:06:33.897: INFO/installd(34): unlink /data/dalvik-cache/data@app@com.example.android.TCPListen-2.apk@classes.dex
01-10 14:06:33.917: DEBUG/AndroidRuntime(340): Shutting down VM
01-10 14:06:33.926: DEBUG/dalvikvm(340): Debugger has detached; object registry had 1 entries
01-10 14:06:33.967: INFO/AndroidRuntime(340): NOTE: attach of thread 'Binder Thread #3' failed
01-10 14:06:34.697: DEBUG/AndroidRuntime(352): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
01-10 14:06:34.697: DEBUG/AndroidRuntime(352): CheckJNI is ON
01-10 14:06:34.988: DEBUG/AndroidRuntime(352): --- registering native functions ---
01-10 14:06:35.867: INFO/ActivityManager(58): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.example.android.TCPListen/.TCPListen }
01-10 14:06:35.927: DEBUG/AndroidRuntime(352): Shutting down VM
01-10 14:06:35.957: DEBUG/dalvikvm(352): Debugger has detached; object registry had 1 entries
01-10 14:06:35.988: INFO/ActivityManager(58): Start proc com.example.android.TCPListen for activity com.example.android.TCPListen/.TCPListen: pid=359 uid=10037 gids={3003}
01-10 14:06:36.017: INFO/AndroidRuntime(352): NOTE: attach of thread 'Binder Thread #3' failed
01-10 14:06:36.837: INFO/ActivityManager(58): Displayed activity com.example.android.TCPListen/.TCPListen: 904 ms (total 57691 ms)
01-10 14:06:36.926: DEBUG/TCP(359): C: Connecting...
01-10 14:06:37.117: DEBUG/TCP(359): C: Receiving...
01-10 14:06:37.117: INFO/global(359): Default buffer size used in BufferedReader constructor. It would be better to be explicit if an 8k-char buffer is required.
01-10 14:06:42.057: DEBUG/dalvikvm(123): GC_EXPLICIT freed 103 objects / 5744 bytes in 150ms
01-10 14:06:43.169: DEBUG/TCP(359): C: Done danaadan.
01-10 14:06:43.186: DEBUG/TCP(359): C: In the parser <MSG><N>shiftDirection<!N><V>0<!V><!MSG>
01-10 14:06:43.208: DEBUG/TCP(359): C:Wrong value message shiftDirection
01-10 14:06:48.219: DEBUG/TCP(359): C:Wrong format message SD<!N><V>0<!V><!MSG>
01-10 14:06:53.228: DEBUG/TCP(359): C: In the parser <MSG><N>shiftDirection<!N><V>1<!V><!MSG>
01-10 14:06:53.248: DEBUG/TCP(359): C:Correct message shiftDirection 1.0
01-10 14:06:53.287: INFO/ActivityManager(58): Starting activity: Intent { cmp=com.example.android.TCPListen/.Images }
01-10 14:06:53.879: WARN/ActivityManager(58): Activity pause timeout for HistoryRecord{43e45238 com.example.android.TCPListen/.TCPListen}
01-10 14:06:58.384: DEBUG/AndroidRuntime(359): Shutting down VM
01-10 14:06:58.388: WARN/dalvikvm(359): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
01-10 14:06:58.458: ERROR/AndroidRuntime(359): FATAL EXCEPTION: main
01-10 14:06:58.458: ERROR/AndroidRuntime(359): java.lang.NullPointerException
01-10 14:06:58.458: ERROR/AndroidRuntime(359): at com.example.android.TCPListen.TCPListen.callCompleted(TCPListen.java:40)
01-10 14:06:58.458: ERROR/AndroidRuntime(359): at com.example.android.TCPListen.TcpServiceHandler.onPostExecute(TcpServiceHandler.java:75)
01-10 14:06:58.458: ERROR/AndroidRuntime(359): at com.example.android.TCPListen.TcpServiceHandler.onPostExecute(TcpServiceHandler.java:1)
01-10 14:06:58.458: ERROR/AndroidRuntime(359): at android.os.AsyncTask.finish(AsyncTask.java:417)
01-10 14:06:58.458: ERROR/AndroidRuntime(359): at android.os.AsyncTask.access$300(AsyncTask.java:127)
01-10 14:06:58.458: ERROR/AndroidRuntime(359): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
01-10 14:06:58.458: ERROR/AndroidRuntime(359): at android.os.Handler.dispatchMessage(Handler.java:99)
01-10 14:06:58.458: ERROR/AndroidRuntime(359): at android.os.Looper.loop(Looper.java:123)
01-10 14:06:58.458: ERROR/AndroidRuntime(359): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-10 14:06:58.458: ERROR/AndroidRuntime(359): at java.lang.reflect.Method.invokeNative(Native Method)
01-10 14:06:58.458: ERROR/AndroidRuntime(359): at java.lang.reflect.Method.invoke(Method.java:521)
01-10 14:06:58.458: ERROR/AndroidRuntime(359): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-10 14:06:58.458: ERROR/AndroidRuntime(359): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-10 14:06:58.458: ERROR/AndroidRuntime(359): at dalvik.system.NativeStart.main(Native Method)
01-10 14:06:58.487: WARN/ActivityManager(58): Force finishing activity com.example.android.TCPListen/.Images
01-10 14:06:58.538: WARN/ActivityManager(58): Force finishing activity com.example.android.TCPListen/.TCPListen
01-10 14:06:59.026: WARN/ActivityManager(58): Activity pause timeout for HistoryRecord{43fc82d8 com.example.android.TCPListen/.Images}
01-10 14:06:59.087: DEBUG/dalvikvm(58): GREF has increased to 301
01-10 14:07:01.427: INFO/Process(359): Sending signal. PID: 359 SIG: 9
01-10 14:07:01.457: INFO/ActivityManager(58): Process com.example.android.TCPListen (pid 359) has died.
01-10 14:07:01.457: INFO/WindowManager(58): WIN DEATH: Window{43f5d848 com.example.android.TCPListen/com.example.android.TCPListen.TCPListen paused=true}
01-10 14:07:01.556: WARN/InputManagerService(58): Got RemoteException sending setActive(false) notification to pid 359 uid 10037
01-10 14:07:05.458: DEBUG/dalvikvm(156): GC_EXPLICIT freed 1575 objects / 81008 bytes in 219ms
01-10 14:07:09.860: WARN/ActivityManager(58): Activity destroy timeout for HistoryRecord{43e45238 com.example.android.TCPListen/.TCPListen}
01-10 14:07:09.860: WARN/ActivityManager(58): Activity destroy timeout for HistoryRecord{43fc82d8 com.example.android.TCPListen/.Images}
01-10 14:07:26.170: DEBUG/SntpClient(58): request time failed: java.net.SocketException: Address family not supported by protocol
Update
Instead of AsyncTask in TcpServiceHandler, I used just thread.
public class TcpServiceHandler implements Runnable {
TCPListener _listener;
private Activity _act;
public TcpServiceHandler(TCPListener listener, Activity act){
_listener = listener;
_act = act;
}
public synchronized void run() {
// TODO Auto-generated method stub
//if(socket==null){
try {
InetAddress serverAddr = InetAddress.getByName("192.168.178.24");
Socket socket = new Socket(serverAddr, 1200);
//
while(true){
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
final String str = in.readLine();
this._act.runOnUiThread(new Runnable(){
public void run() {
_listener.callCompleted(str);
} 开发者_Python百科
});
}
catch(Exception e){
e.printStackTrace();
}
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This client (based on TCP sockets) will receive messages (strings) in the format <MSG><N>shiftDirection</N><V>1</V></MSG>
and has to display an image or show some driver assistance info. Such messages keep coming every 100 ms.
Is this a good way of doing this task? If this is not the right way or if there is a better alternate way, I would be grateful for any such suggestion.
I don't think you should be writing your own constructor for an AsyncTask
. Remove the public constructor and perform any initialisation within your onPreExecute
method. Read the documentation for examples.
精彩评论