Android application unable to run on emulator - java

I'm quite new to android development, I'm trying to develop a server-client application where the server is a simple java application that reads some text from a file and sends it using output stream. the client is an android application that reads this stream when clicking a button and displays it on a text view.
I'm using eclipse with ADK, and testing on an emulator here's how both codes look like:
Server:
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class Server {
/**
* #param args
* #throws IOException
* #throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException
{
System.out.println("***********Starting ***********");
ServerSocket servsock = new ServerSocket(12344);
System.out.println("Waiting...");
Socket sock = servsock.accept();
while (true)
{
System.out.println("Accepted connection : " + sock);
File myFile = new File ("source.txt");
while (true){
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
}
}
}
}
Client:
-MainActivity
package com.example.streamerclient;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
Button ConnectBtn ;
#Override
public void onResume() {
super.onResume();
//setContentView(R.layout.activity_main);
System.out.println(" on resume ");
ConnectBtn = (Button)findViewById(R.id.ConnectButton);
ConnectBtn.setOnClickListener(this);
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Connecting c = new Connecting();
}
}
-Connecting class
package com.example.streamerclient;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import android.app.Activity;
import android.widget.TextView;
public class Connecting extends Activity implements Runnable
{
private Socket sock;
private BufferedReader r;
private BufferedWriter out;
TextView Data;
public Connecting ()
{
Data = (TextView) findViewById(R.id.DataTextView);
Thread th = new Thread(this);
th.start();
}
#Override
public void run() {
try
{
System.out.println("trying to initiated ");
Data.setText("trying to initiated ");
sock = new Socket("10.0.2.2",12344);
System.out.println(" socket initiated ");
Data.setText(" socket initiated ");
r = new BufferedReader(new InputStreamReader(sock.getInputStream()));
Data.setText(" buffer reader initiated ");
System.out.println(" buffer reader initiated ");
out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
Data.setText(" buffer writer initiated ");
System.out.println(" buffer writer initiated ");
final String data = r.readLine();
Data.setText(" Data read is: \n"+data);
System.out.println(" Data read is: \n"+data);
}
catch (IOException ioe) { }
}
public void OnPause()
{
System.out.println(" paused");
try {
if (sock != null) {
sock.getOutputStream().close();
sock.getInputStream().close();
sock.close();
System.out.println(" everything is closed ");
}
} catch (IOException e) {}
}
}
I know I know, there are some parts of the code that are not used .. my next task is to have this application send commands to the server ... so I'm still experimenting.
when running the application on the emulator it stops before even displaying any of the GUI components. Any idea why ? Here's what the log file says
03-17 08:16:30.886: W/Trace(846): Unexpected value from nativeGetEnabledTags: 0
03-17 08:16:30.886: W/Trace(846): Unexpected value from nativeGetEnabledTags: 0
03-17 08:16:30.886: W/Trace(846): Unexpected value from nativeGetEnabledTags: 0
03-17 08:16:31.016: W/Trace(846): Unexpected value from nativeGetEnabledTags: 0
03-17 08:16:31.016: W/Trace(846): Unexpected value from nativeGetEnabledTags: 0
03-17 08:16:31.126: I/System.out(846): on resume
03-17 08:16:31.447: D/AndroidRuntime(846): Shutting down VM
03-17 08:16:31.447: W/dalvikvm(846): threadid=1: thread exiting with uncaught exception (group=0x40a70930)
03-17 08:16:31.457: E/AndroidRuntime(846): FATAL EXCEPTION: main
03-17 08:16:31.457: E/AndroidRuntime(846): java.lang.RuntimeException: Unable to resume activity {com.example.streamerclient/com.example.streamerclient.MainActivity}: java.lang.NullPointerException
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2742)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2771)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2235)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.os.Handler.dispatchMessage(Handler.java:99)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.os.Looper.loop(Looper.java:137)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread.main(ActivityThread.java:5039)
03-17 08:16:31.457: E/AndroidRuntime(846): at java.lang.reflect.Method.invokeNative(Native Method)
03-17 08:16:31.457: E/AndroidRuntime(846): at java.lang.reflect.Method.invoke(Method.java:511)
03-17 08:16:31.457: E/AndroidRuntime(846): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-17 08:16:31.457: E/AndroidRuntime(846): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-17 08:16:31.457: E/AndroidRuntime(846): at dalvik.system.NativeStart.main(Native Method)
03-17 08:16:31.457: E/AndroidRuntime(846): Caused by: java.lang.NullPointerException
03-17 08:16:31.457: E/AndroidRuntime(846): at com.example.streamerclient.MainActivity.onResume(MainActivity.java:20)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1185)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.Activity.performResume(Activity.java:5182)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2732)
03-17 08:16:31.457: E/AndroidRuntime(846): ... 12 more
thanks!

Try moving the contents of your entire onResume() to an onCreate() method. Always do the UI setup in onCreate(). Read this: Activity Lifecycle Management.
And take any further queries to stackoverflow :)
Cheers!

You are getting a NullPointerException on line 20 in MainActivity, check that line.
I think this question is better suited for stackoverflow

Related

Whenever Iam not entering anything in EditText the app is crashes [duplicate]

This question already has answers here:
Can't create handler inside thread that has not called Looper.prepare()
(30 answers)
Closed 2 years ago.
Iam making a weather app but whenever Iam not entering or entering wrong city name in EditText the app crashes even though I have used try and catch blocks for error handling.The below is the java,xml code and the logs where it is showing a runtime error.
Java
package com.atul.whatstheweather;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
EditText cityName;
TextView weatherInfo;
public class Content extends AsyncTask<String, Void ,String>
{
#Override
protected String doInBackground(String... urls) {
URL url;
HttpURLConnection urlConnection = null;
String result = "";
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while(data != -1)
{
char current = (char)data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
Toast.makeText(MainActivity.this, "URL malfunctioned", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
String weatherData = jsonObject.getString("weather");
JSONArray array = new JSONArray(weatherData);
for(int i=0;i<array.length();i++)
{
JSONObject jsonPart = array.getJSONObject(i);
String main = jsonPart.getString("main");
String description = jsonPart.getString("description");
weatherInfo.setText("Weather: "+main+"\n\n"+"Description: "+description);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityName = (EditText)findViewById(R.id.cityName);
weatherInfo = (TextView)findViewById(R.id.textView);
}
public void clicked(View view)
{
Content content = new Content();
content.execute("https://api.openweathermap.org/data/2.5/weather?q=" + cityName.getText().toString() + "&appid=c20cea76c84b519d67d4e6582064db92");
Log.i("clicked","is working");
}
}
In the Logs given below it is showing Runtime error
Run Logs
05/03 17:35:25: Launching app
Cold swapped changes.
$ adb shell am start -n "com.atul.whatstheweather/com.atul.whatstheweather.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 18757 on device xiaomi-redmi_note_3-9b51ac51
I/art: Late-enabling -Xcheck:jni
D/TidaProvider: TidaProvider()
W/ReflectionUtils: java.lang.NoSuchMethodException: android.os.MessageQueue#enableMonitor()#bestmatch
at miui.util.ReflectionUtils.findMethodBestMatch(ReflectionUtils.java:338)
at miui.util.ReflectionUtils.findMethodBestMatch(ReflectionUtils.java:375)
at miui.util.ReflectionUtils.callMethod(ReflectionUtils.java:800)
at miui.util.ReflectionUtils.tryCallMethod(ReflectionUtils.java:818)
at android.os.BaseLooper.enableMonitor(BaseLooper.java:47)
at android.os.Looper.prepareMainLooper(Looper.java:111)
at android.app.ActivityThread.main(ActivityThread.java:5586)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
W/ResourceType: No package identifier when getting name for resource number 0x00000000
W/System: ClassLoader referenced unknown path: /data/app/com.atul.whatstheweather-1/lib/arm64
I/InstantRun: Instant Run Runtime started. Android package is com.atul.whatstheweather, real application class is null.
W/System: ClassLoader referenced unknown path: /data/app/com.atul.whatstheweather-1/lib/arm64
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
D/AccessibilityManager: current package=com.atul.whatstheweather, accessibility manager mIsFinalEnabled=false, mOptimizeEnabled=false, mIsUiAutomationEnabled=false, mIsInterestedPackage=false
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#9df51ef
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#ce6e4fc
D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
I/Adreno: QUALCOMM build : a7823f5, I59a6815413
Build Date : 09/23/16
OpenGL ES Shader Compiler Version: XE031.07.00.00
Local Branch : mybranch22028469
Remote Branch : quic/LA.BR.1.3.3_rb2.26
Remote Branch : NONE
Reconstruct Branch : NOTHING
I/OpenGLRenderer: Initialized EGL, version 1.4
E/HAL: hw_get_module_by_class: module name gralloc
E/HAL: hw_get_module_by_class: module name gralloc
I/clicked: is working
I/DpmTcmClient: RegisterTcmMonitor from: com.android.okhttp.TcmIdleTimerMonitor
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.atul.whatstheweather, PID: 18757
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:356)
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:266)
at com.atul.whatstheweather.MainActivity$Content.doInBackground(MainActivity.java:60)
at com.atul.whatstheweather.MainActivity$Content.doInBackground(MainActivity.java:31)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
at java.lang.Thread.run(Thread.java:818) 
I/Process: Sending signal. PID: 18757 SIG: 9
Application terminated.
App crashes because you are calling Toast in background thread.
Replace your Toast line in catch block Toast.makeText(MainActivity.this, "URL malfunctioned", Toast.LENGTH_SHORT).show(); with :
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "URL malfunctioned", Toast.LENGTH_SHORT).show();
}
});
Just delete the Toast.makeText

AndroidRuntime: Shutting down VM

I'm building an android game. It's a Unity3D project exported to Android Studio. I'm trying to manage all the Google Play Services (GPS) interaction in Android Studio. This is the class responsible to interact with GPS (I know I'm not following standard programming patterns):
package com.lemondo.eyescube;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.games.Games;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;
public class GPSBinding implements ConnectionCallbacks, OnConnectionFailedListener {
public GoogleApiClient googleApiClient;
private static GPSBinding _gpsBindingInstance;
public static GPSBinding instance(){
if(_gpsBindingInstance == null){
_gpsBindingInstance = new GPSBinding();
}
return _gpsBindingInstance;
}
public static void Initialize(){
if(instance().googleApiClient == null) {
instance().googleApiClient = new GoogleApiClient.Builder(UnityPlayer.currentActivity)
.addConnectionCallbacks(instance())
.addOnConnectionFailedListener(instance())
.addApi(Games.API)
.addScope(Games.SCOPE_GAMES)
.build();
}
}
public static void AuthenticatePlayer() {
Log.d("GPSBinding", "AuthenticatePlayer");
try {
if (instance().googleApiClient != null)
instance().googleApiClient.connect();
else
Log.d("GPSBinding", "AuthenticatePlayer: googleApiClient is null");
} catch (Exception e){
e.printStackTrace();
}
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult result) {
}
}
This is what happens: the app starts, Unity calls Initialize() method upon startup, it waits for 1 second and calls for AuthenticatePlayer() method.
The app crashes on this line in Authenticatelayer():
instance().googleApiClient.connect();
I do not get the cause though, this is the stack trace:
01-12 12:46:02.602 30609-30609/com.lemondo.eyescube D/AndroidRuntime: Shutting down VM
01-12 12:46:02.605 30609-30609/com.lemondo.eyescube E/AndroidRuntime: FATAL EXCEPTION: main
01-12 12:46:02.605 30609-30609/com.lemondo.eyescube E/AndroidRuntime: Process: com.lemondo.eyescube, PID: 30609
01-12 12:46:02.605 30609-30609/com.lemondo.eyescube E/AndroidRuntime: java.lang.Error: FATAL EXCEPTION [main]
01-12 12:46:02.605 30609-30609/com.lemondo.eyescube E/AndroidRuntime: Unity version : 5.2.1f1
01-12 12:46:02.605 30609-30609/com.lemondo.eyescube E/AndroidRuntime: Device model : samsung GT-I9500
01-12 12:46:02.605 30609-30609/com.lemondo.eyescube E/AndroidRuntime: Device fingerprint: ...
01-12 12:46:25.139 30609-30609/com.lemondo.eyescube I/Process: Sending signal. PID: 30609 SIG: 9
Similar questions on SO just say to tweak Google Analytics, which I don't use at all. Weird thing is it does not even catch an exception - just Boom! Crash! Does anyone have an idea what could be wrong? Thanks in advance!
So fudging stupid - I forgot to add app id to my manifest:
<meta-data android:name="com.google.android.gms.games.APP_ID" android:value="#string/app_id" />

Android Socket Client Receiving data

I am creating a basic test application for android that can connect to a socket server and send and receive data. i have been able to get the sending of data from the client to the server working but seem to have a problem getting the android to receive data. the server works as i have been able to test that using a external application.
here is my code
package com.socket_sending_and_receving_test;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Looper;
import android.os.Message;
import android.widget.Button;
import android.widget.TextView;
import android.os.Handler;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class Sending_And_Receiving extends Activity {
private Socket socket;
String message = "";
String mClientMsg;
TextView text;
final Handler myHandler = new Handler();
int count = 0;
public static String SERVERPORT;
public static int SERVERPORT2;
public static String SERVER_IP;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sending_and_receaving);
text = (TextView) findViewById(R.id.textView);
text.setText("0");
}
Handler myUpdateHandler = new Handler() {
public void handleMessage(Message msg) {
TextView tv = (TextView) findViewById(R.id.textView);
tv.setText(mClientMsg);
super.handleMessage(msg);
}
};
class CommsThread implements Runnable {
String st = null;
public void run() {
while (!Thread.currentThread().isInterrupted()) {
Message m = new Message();
{
BufferedReader input = null;
try {
InputStreamReader streamReader = new InputStreamReader(socket.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
st = reader.readLine();
mClientMsg = st;
myUpdateHandler.sendMessage(m);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public void connect(View view) {
EditText ip = (EditText) findViewById(R.id.ip);
EditText port = (EditText) findViewById(R.id.port);
SERVER_IP = ip.getText().toString();
SERVERPORT = port.getText().toString();
new Thread(new ClientThread()).start();
new Thread(new CommsThread()).start();
}
public void Disconnect(View view) {
try {
socket.shutdownInput();
socket.shutdownOutput();
} catch (IOException e) {
e.printStackTrace();
}
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.ko);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true
);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
SERVERPORT2 = Integer.parseInt(SERVERPORT);
socket = new Socket(serverAddr, SERVERPORT2);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
after the connection is made the application crashes. I don't think it is due to the UI updating but i think its due to the receiving of data.
here is the logcat
07-08 21:59:57.915 7041-7041/com.socket_sending_and_receving_test D/libEGL﹕ loaded /system/lib/egl/libEGL_mali.so
07-08 21:59:57.920 7041-7041/com.socket_sending_and_receving_test D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_mali.so
07-08 21:59:57.925 7041-7041/com.socket_sending_and_receving_test D/libEGL﹕ loaded /system/lib/egl/libGLESv2_mali.so
07-08 21:59:57.930 7041-7041/com.socket_sending_and_receving_test D/﹕ Device driver API match
Device driver API version: 10
User space API version: 10
07-08 21:59:57.930 7041-7041/com.socket_sending_and_receving_test D/﹕ mali: REVISION=Linux-r2p4-02rel0 BUILD_DATE=Tue Oct 16 15:37:13 KST 2012
07-08 21:59:57.965 7041-7041/com.socket_sending_and_receving_test D/OpenGLRenderer﹕ Enabling debug mode 0
07-08 21:59:57.965 7041-7041/com.socket_sending_and_receving_test E/SensorManager﹕ thread start
07-08 21:59:57.970 7041-7041/com.socket_sending_and_receving_test D/SensorManager﹕ registerListener :: handle = 0 name= LSM330DLC 3-axis Accelerometer delay= 200000 Listener= android.view.OrientationEventListener$SensorEventListenerImpl#42b1cf38
07-08 21:59:58.080 7041-7041/com.socket_sending_and_receving_test E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
07-08 21:59:58.080 7041-7041/com.socket_sending_and_receving_test E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
07-08 22:00:03.235 7041-7193/com.socket_sending_and_receving_test W/dalvikvm﹕ threadid=13: thread exiting with uncaught exception (group=0x41e792a0)
07-08 22:00:03.240 7041-7193/com.socket_sending_and_receving_test E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-2791
java.lang.NullPointerException
at com.socket_sending_and_receving_test.Sending_And_Receiving$CommsThread.run(Sending_And_Receiving.java:74)
at java.lang.Thread.run(Thread.java:856)
07-08 22:00:03.320 7041-7041/com.socket_sending_and_receving_test D/SensorManager﹕ unregisterListener:: Listener= android.view.OrientationEventListener$SensorEventListenerImpl#42b1cf38
07-08 22:00:03.320 7041-7041/com.socket_sending_and_receving_test D/Sensors﹕ Remain listener = Sending .. normal delay 200ms
07-08 22:00:03.320 7041-7041/com.socket_sending_and_receving_test I/Sensors﹕ sendDelay --- 200000000
07-08 22:00:03.320 7041-7041/com.socket_sending_and_receving_test D/SensorManager﹕ JNI - sendDelay
07-08 22:00:03.320 7041-7041/com.socket_sending_and_receving_test I/SensorManager﹕ Set normal delay = true
07-08 22:00:09.870 7041-7041/com.socket_sending_and_receving_test I/Choreographer﹕ Skipped 392 frames! The application may be doing too much work on its main thread.
07-08 22:00:11.680 7041-7193/com.socket_sending_and_receving_test I/Process﹕ Sending signal. PID: 7041 SIG: 9
Any help on this problem would be greatly appreciated
Cheers :)
Your socket is NULL. This is because of a race condition:
new Thread(new ClientThread()).start();
new Thread(new CommsThread()).start();
Both threads are started here, but ClientThread will initialise the socket while CommsThread tries to use it. But it is not initialised at this point.
You may call CommsThread's run() right after socket=... or if you really need a 2nd thread, start it there.
Your CommsThread is running before your ClientThread has completed the connection. So, 'socket' is still null and you get an NPE.
There is absolutely no reason for these to be two different threads. Combine them, so that the connection is made first and then the I/O starts. Using two threads to perform tasks that must be sequential is basically inane.

Android VerifyError crash using jackson parser

Here is my log cat. Unfortunately I am not a pro in reading errors from logcat so please help me :)
05-30 12:12:16.510: I/System.out(838): We made it this far 1
05-30 12:12:17.230: I/System.out(838): We made it this far 2
05-30 12:12:17.240: W/dalvikvm(838): VFY: unable to resolve exception class 748 (Lcom/fasterxml/jackson/core/JsonParseException;)
05-30 12:12:17.240: W/dalvikvm(838): VFY: unable to find exception handler at addr 0x2a
05-30 12:12:17.240: W/dalvikvm(838): VFY: rejected Lcom/example/bitmapdisplay/MainActivity$URLArray;.doInBackground ([Ljava/lang/Void;)Ljava/lang/Void;
05-30 12:12:17.240: W/dalvikvm(838): VFY: rejecting opcode 0x0d at 0x002a
05-30 12:12:17.250: W/dalvikvm(838): VFY: rejected Lcom/example/bitmapdisplay/MainActivity$URLArray;.doInBackground ([Ljava/lang/Void;)Ljava/lang/Void;
05-30 12:12:17.250: W/dalvikvm(838): Verifier rejected class Lcom/example/bitmapdisplay/MainActivity$URLArray;
05-30 12:12:17.250: D/AndroidRuntime(838): Shutting down VM
05-30 12:12:17.250: W/dalvikvm(838): threadid=1: thread exiting with uncaught exception (group=0xb1adaba8)
05-30 12:12:17.270: E/AndroidRuntime(838): FATAL EXCEPTION: main
05-30 12:12:17.270: E/AndroidRuntime(838): Process: com.example.bitmapdisplay, PID: 838
05-30 12:12:17.270: E/AndroidRuntime(838): java.lang.VerifyError: com/example/bitmapdisplay/MainActivity$URLArray
05-30 12:12:17.270: E/AndroidRuntime(838): at com.example.bitmapdisplay.MainActivity.onCreate(MainActivity.java:72)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.Activity.performCreate(Activity.java:5231)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.ActivityThread.access$800(ActivityThread.java:135)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.os.Handler.dispatchMessage(Handler.java:102)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.os.Looper.loop(Looper.java:136)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-30 12:12:17.270: E/AndroidRuntime(838): at java.lang.reflect.Method.invokeNative(Native Method)
05-30 12:12:17.270: E/AndroidRuntime(838): at java.lang.reflect.Method.invoke(Method.java:515)
05-30 12:12:17.270: E/AndroidRuntime(838): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-30 12:12:17.270: E/AndroidRuntime(838): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-30 12:12:17.270: E/AndroidRuntime(838): at dalvik.system.NativeStart.main(Native Method)
05-30 12:12:30.390: I/Process(838): Sending signal. PID: 838 SIG: 9
Here is the logcat code and here is my Java code. It seems like the problems are coming from the thread URLArray because, as seen in the logcat, the system doesn't even print the third "we made it this far":
package com.example.bitmapdisplay;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import com.fasterxml.jackson.core.JsonParseException;
import android.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class MainActivity extends Activity {
/**
* Bitmap items na dimage displaying
*/
Bitmap image;
BitmapDrawable bd;
ImageView temp;
ProgressDialog pd;
/**
* JSON URL
*/
URL url;
/**
* Data from JSON file
*/
ArrayList<String> urls;
ArrayList<ImageView> images;
JsonParsing obj;
String json_link_str = "http://api.tumblr.com/v2/blog/humansofnewyork.com/posts?api_key=7ag2CJXOuxuW3vlVS5wQG6pYA6a2ZQcSCjzZsAp2pDbVwf3xEk&notes_info=true&filter=text";
int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
System.out.println(" We made it this far 1");
super.onCreate(savedInstanceState);
setContentView(com.example.bitmapdisplay.R.layout.image_container);
counter = 0;
images = new ArrayList<ImageView>();
urls = new ArrayList<String>();
System.out.println(" We made it this far 2");
new URLArray().execute();
}
/**
* Fills the ListView
*/
private void fillGridView() {
ArrayAdapter<ImageView> adapter = new ArrayAdapter<ImageView>(this, com.example.bitmapdisplay.R.layout.image_container,images);
GridView grid = (GridView) findViewById(com.example.bitmapdisplay.R.id.gvImages);
grid.setAdapter(adapter);
}
public class URLArray extends AsyncTask<Void, Void, Void > {
public URLArray() {
}
#Override
protected Void doInBackground(Void...params ) {
try {
System.out.println(" We made it this far 3");
URL json_link = new URL(json_link_str);
JsonParsing parse_images = new JsonParsing(json_link);
try {
parse_images.parseFile(3, urls);
System.out.println(" We made it this far 4");
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
obj = parse_images;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void arg) {
super.onPreExecute();
System.out.println(" We made it this far 5");
urls = obj.getURLs();
new TheTask().execute();
}
}
class TheTask extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params) {
System.out.println(" We made it this far 6");
pd = new ProgressDialog(MainActivity .this);
pd.show();
System.out.println(" We made it this far 7");
try
{
int counter = 0;
for (ImageView temp : images) {
image = downloadBitmap(urls.get(counter));
temp.setImageBitmap(image);
images.add(temp);
counter++;
}
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
System.out.println(" We made it this far 8");
super.onPostExecute(result);
pd.dismiss();
if(image!=null)
{
fillGridView();
}
}
}
private Bitmap downloadBitmap(String url) {
// initilize the default HTTP client object
final DefaultHttpClient client = new DefaultHttpClient();
//forming a HttoGet request
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
//check 200 OK for success
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode +
" while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
// getting contents from the stream
inputStream = entity.getContent();
// decoding stream data back into image Bitmap that android understands
image = BitmapFactory.decodeStream(inputStream);
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// You Could provide a more explicit error message for IOException
getRequest.abort();
Log.e("ImageDownloader", "Something went wrong while" +
" retrieving bitmap from " + url + e.toString());
}
return image;
}
}
The key problem is here
05-30 12:12:17.240: W/dalvikvm(838): VFY: unable to resolve exception class 748 (Lcom/fasterxml/jackson/core/JsonParseException;)
05-30 12:12:17.240: W/dalvikvm(838): VFY: unable to find exception handler at addr 0x2a
05-30 12:12:17.240: W/dalvikvm(838): VFY: rejected Lcom/example/bitmapdisplay/MainActivity$URLArray;.doInBackground ([Ljava/lang/Void;)Ljava/lang/Void;
05-30 12:12:17.240: W/dalvikvm(838): VFY: rejecting opcode 0x0d at 0x002a
05-30 12:12:17.250: W/dalvikvm(838): VFY: rejected Lcom/example/bitmapdisplay/MainActivity$URLArray;.doInBackground ([Ljava/lang/Void;)Ljava/lang/Void;
05-30 12:12:17.250: W/dalvikvm(838): Verifier rejected class Lcom/example/bitmapdisplay/MainActivity$URLArray;
and it all goes downhill from there.
Looks like JsonParseException (and possibly other classes from Jackson) are not being included in your APK. This could happen if they're not being exported by Eclipse.
Instead of adding it as an external library, just place jackson-core-x.x.x.jar in the libs folder of your Android project and it should be enough to ensure this.

Reading a text file from res/raw folder

Im trying to read a text file from the raw folder in res using final Scanner input = new Scanner(new File(R.raw.xmlsource)).useDelimiter("[\\;]+"); but it isn't reading because of the resource id being int in R.java file, my code is below
EDIT Made some changes to my code below, still doesn't run but using the debugger i can tell that it actually reads the file, the problem seems to be at String[] RssLinksArray = readLine.split("[\\;]+"); where the code terminates, i can't for the life of me figure out why. i'm attaching the logcat also.
Any help would be tremendously appreciated.
package com.simplerssreader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.URL;
import java.util.List;
import java.util.Scanner;
import org.xmlpull.v1.XmlPullParserException;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;
public class RssService extends IntentService
{
public static final String ITEMS = "items";
public static final String RECEIVER = "receiver";
public RssService()
{
super("RssService");
}
#Override
protected void onHandleIntent(Intent intent)
{
InputStream is = getResources().openRawResource(R.raw.xmlsource);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine = null;
try {
while ((readLine = br.readLine()) != null)
{
}
} catch (IOException e)
{
e.printStackTrace();
}
String[] RssLinksArray = readLine.split("[\\;]+");
final String RSS_LINK = RssLinksArray[0];
Log.d(Constants.TAG, "Service started");
List<RssItem> rssItems = null;
try
{
XMLRssParser parser = new XMLRssParser();
rssItems = parser.parse(getInputStream(RSS_LINK));
}
catch (XmlPullParserException e)
{
Log.w(e.getMessage(), e);
}
catch (IOException e)
{
Log.w(e.getMessage(), e);
}
Bundle bundle = new Bundle();
bundle.putSerializable(ITEMS, (Serializable) rssItems);
ResultReceiver receiver = intent.getParcelableExtra(RECEIVER);
receiver.send(0, bundle);
}
public InputStream getInputStream(String link)
{
try
{
URL url = new URL(link);
return url.openConnection().getInputStream();
} catch (IOException e)
{
Log.w(Constants.TAG, "Exception while retrieving the input stream", e);
return null;
}
}
}
LOGCAT
10-24 23:07:49.908: D/dalvikvm(1189): GC_FOR_ALLOC freed 101K, 9% free 2778K/3040K, paused 68ms, total 72ms
10-24 23:07:49.938: I/dalvikvm-heap(1189): Grow heap (frag case) to 3.939MB for 1127536-byte allocation
10-24 23:07:50.089: D/dalvikvm(1189): GC_FOR_ALLOC freed 2K, 7% free 3877K/4144K, paused 149ms, total 149ms
10-24 23:07:50.461: W/dalvikvm(1189): threadid=11: thread exiting with uncaught exception (group=0x41465700)
10-24 23:07:50.504: E/AndroidRuntime(1189): FATAL EXCEPTION: IntentService[RssService]
10-24 23:07:50.504: E/AndroidRuntime(1189): java.lang.NullPointerException
10-24 23:07:50.504: E/AndroidRuntime(1189): at com.simplerssreader.RssService.onHandleIntent(RssService.java:48)
10-24 23:07:50.504: E/AndroidRuntime(1189): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
10-24 23:07:50.504: E/AndroidRuntime(1189): at android.os.Handler.dispatchMessage(Handler.java:99)
10-24 23:07:50.504: E/AndroidRuntime(1189): at android.os.Looper.loop(Looper.java:137)
10-24 23:07:50.504: E/AndroidRuntime(1189): at android.os.HandlerThread.run(HandlerThread.java:61)
10-24 23:07:50.899: D/libEGL(1189): loaded /system/lib/egl/libEGL_emulation.so
10-24 23:07:50.940: D/(1189): HostConnection::get() New Host Connection established 0x2a1db628, tid 1189
10-24 23:07:51.078: D/libEGL(1189): loaded /system/lib/egl/libGLESv1_CM_emulation.so
10-24 23:07:51.279: D/libEGL(1189): loaded /system/lib/egl/libGLESv2_emulation.so
10-24 23:07:51.699: W/EGL_emulation(1189): eglSurfaceAttrib not implemented
10-24 23:07:51.729: D/OpenGLRenderer(1189): Enabling debug mode 0
10-24 23:07:51.769: I/Choreographer(1189): Skipped 85 frames! The application may be doing too much work on its main thread.
10-24 23:07:56.358: I/Choreographer(1189): Skipped 265 frames! The application may be doing too much work on its main thread.
InputStream inputStream = getResources().openRawResource(R.raw.xmlsource);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

Categories

Resources