Application crashes during TCP connection - java

I'm new to Android programming. My application crashes while creating a socket. I added to the Manifest internet permission, and Wifi is on. I have a server on a PC waiting for the Android client; it works well with my other applications. I don't know where the problem with is this application. I'd appreciate any help.
Log errors
01-23 13:10:32.110: E/AndroidRuntime(4493): FATAL EXCEPTION: main
01-23 13:10:32.110: E/AndroidRuntime(4493): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.usapp/com.example.usapp.Settings}: android.os.NetworkOnMainThreadException
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1751)
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1767)
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.app.ActivityThread.access$1500(ActivityThread.java:122)
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1005)
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.os.Handler.dispatchMessage(Handler.java:99)
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.os.Looper.loop(Looper.java:132)
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.app.ActivityThread.main(ActivityThread.java:4028)
01-23 13:10:32.110: E/AndroidRuntime(4493): at java.lang.reflect.Method.invokeNative(Native Method)
01-23 13:10:32.110: E/AndroidRuntime(4493): at java.lang.reflect.Method.invoke(Method.java:491)
01-23 13:10:32.110: E/AndroidRuntime(4493): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:844)
01-23 13:10:32.110: E/AndroidRuntime(4493): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
01-23 13:10:32.110: E/AndroidRuntime(4493): at dalvik.system.NativeStart.main(Native Method)
01-23 13:10:32.110: E/AndroidRuntime(4493): Caused by: android.os.NetworkOnMainThreadException
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077)
01-23 13:10:32.110: E/AndroidRuntime(4493): at dalvik.system.BlockGuard$WrappedNetworkSystem.connect(BlockGuard.java:368)
01-23 13:10:32.110: E/AndroidRuntime(4493): at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:208)
01-23 13:10:32.110: E/AndroidRuntime(4493): at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:431)
01-23 13:10:32.110: E/AndroidRuntime(4493): at java.net.Socket.connect(Socket.java:901)
01-23 13:10:32.110: E/AndroidRuntime(4493): at java.net.Socket.connect(Socket.java:844)
01-23 13:10:32.110: E/AndroidRuntime(4493): at com.example.usapp.Stream.doInBackground(Stream.java:46)
01-23 13:10:32.110: E/AndroidRuntime(4493): at com.example.usapp.Settings.onCreate(Settings.java:37)
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1715)
01-23 13:10:32.110: E/AndroidRuntime(4493): ... 11 more
Java class
package com.example.usapp;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
public class Stream extends AsyncTask<Void, Void, Void>{
Bitmap image;
int frameCounter=0;
int checkCounterFPS=0;
long lastFpsTime=0;
double FPS;
protected Handler handler_bitmap, handlerdata;
boolean firstSetOfFPS=false;
double availableFPS;
double toleranceValue;
boolean firstFalseFPS = false;
byte[] datainput = new byte[1024];
Socket socket;
#Override
protected Void doInBackground(Void... params) {
Log.i("DUPA","po String doInBackground(String... params) ");
try {
Log.i("DUPA","przed socket");
socket = new Socket();
InetSocketAddress adres = new InetSocketAddress("192.168.1.50", 4444);
//adres.
socket.connect(adres);
//socket = new Socket("192.168.1.50", 4444);
Log.i("DUPA","po socket");
BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
Log.i("DUPA","po socketconnected ");
/*
do {
try {
ByteBuffer buffer = ByteBuffer.allocate(9);
in.read(buffer.array());
byte[] bBuffer = new byte[9];
buffer.get(bBuffer, 0, 9);
int len = Integer.parseInt(new String(bBuffer,"US-ASCII"));
int bytesRecieved = 0;
ByteBuffer completeBuf;
completeBuf = ByteBuffer.allocate(len);
while (len > bytesRecieved) {
int inSize = in.available();
if (inSize > len- bytesRecieved) {
buffer = ByteBuffer.allocate(len- bytesRecieved);
bytesRecieved += len- bytesRecieved;
in.read(buffer.array());
completeBuf.put(buffer);
} else {
bytesRecieved += inSize;
buffer = ByteBuffer.allocate(inSize);
in.read(buffer.array());
completeBuf.put(buffer);
}
}
frameCounter++;
long delay = (long) (System.currentTimeMillis() - lastFpsTime);
if (delay > 1000) {
checkCounterFPS++;
FPS = (((double) frameCounter) / delay) * 1000;
handler_bitmap.post(new Runnable() {
public void run() {
///usunieto fps set text
}
});
frameCounter = 0;
lastFpsTime = System.currentTimeMillis();
}
if (checkCounterFPS >= 3 && firstSetOfFPS == true) {
checkCounterFPS = 0;
if (FPS <= ((double) availableFPS - toleranceValue)
|| FPS >= ((double) availableFPS + toleranceValue)) {
firstFalseFPS = true;
}
} else if (firstFalseFPS == true) {
if (FPS <= ((double) availableFPS - toleranceValue)
|| FPS >= ((double) availableFPS + toleranceValue)) {
// setSendText("FPS",(int) FPS);
firstFalseFPS = false;
}
}
//publishProgress(completeBuf);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("DUPA","blad1");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("DUPA","blad2");
}
} while (!socket.isInputShutdown() && !socket.isClosed()); //
// publishProgress("Status: Closed".getBytes());*/
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("DUPA","blad3");
}
Log.i("AsyncTask", "doInBackground: Finished");
return null;
}
protected Bitmap onProgressUpdate(ByteBuffer... values) {
Log.i("DUPA","blad4");
return image = BitmapFactory.decodeByteArray(values[0].array(), 0,values[0].array().length);
}
}

As correctly pointed out by others, android does not allow networking operations on the main UI thread since Honeycomb and higher versions. I can see that you have created a class extending AsyncTask, which is a special class provided by android for doing background operations. You need to create a separate activity and trigger your AsyncTask from it. That way the code within doInBackground() will execute in a separate thread and will not block your main activity.
eg., you can make your Stream class an inner class to another activity add the following code to the onCreate() method of the activity
Stream task = new Stream();
task.execute();

As #pingw33n mentioned in his comement, the Android network connection has to be done in an AsyncTask thread, not in the main thread. This worked in older versions of android but in the newest ones, your network connection can't be done in the main thread.

Related

Debugging AsyncTask - strange behaviour, debug jumping into the code

I'm debugging an Asynctask that simply downloads a file: here the code:
public class AsyncDownloadFilesTask extends AsyncTask<String, Integer, Boolean> {
public AsyncResponse<Boolean> delegate=null;
protected Boolean doInBackground(String... params) {
android.os.Debug.waitForDebugger();
try {
URL url = new URL(params[0]);
int count;
String fileName = new String(params[1]);
URLConnection connessione = url.openConnection();
connessione.connect();
int lenghtOfFile = connessione.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(fileName);
long total = 0;
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
return Boolean.valueOf(true);
} catch (Exception e) {
return null;
}
}
protected void onPostExecute(Boolean result) {
delegate.processFinish(result);
}
}
I obtain a strange behaviour: when execution arrive to return
Boolean.valueOf(true);
it skips to
return null;
into the catch block, but Exception e is null, and then debugger goto line 1 of AsyncTask, that is simply
package com.example.compa.asynctasks;
Then execution goes on (executing onPostExecute method) and, of course, returned result is null
What happens? Why debug jump in this way?
Task download correctly the file.
Here code of the Activity that instantiates and calls Async Task
package com.example.compa.activities;
import android.app.Activity;
import ...
public class CoverActivity extends Activity implements AsyncResponse<Boolean>{
ImageView coverImg;
Drawable d;
CompassesFileManager cfm;
int coverId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cover);
coverId = getIntent().getExtras().getInt("coverId");
cfm = new CompassesFileManager(this);
ImageView coverImg = (ImageView)findViewById(R.id.cover_image);
d = cfm.getCover(coverId);
if (d!=null){
coverImg.setImageDrawable(d);
} else {
AsyncDownloadFilesTask task = new AsyncDownloadFilesTask();
task.delegate = this;
task.execute(cfm.getCoverURL(coverId), cfm.getCoverFileName(coverId));
}
}
#Override
public void processFinish(Boolean output) {
if (output){
Drawable d = cfm.getCover(coverId);
coverImg.setImageDrawable(d);
} else {
finish();
}
}
}
Stacktrace of error:
02-21 19:37:29.520: E/AndroidRuntime(407): FATAL EXCEPTION: main
02-21 19:37:29.520: E/AndroidRuntime(407): java.lang.NullPointerException
02-21 19:37:29.520: E/AndroidRuntime(407): at com.example.compa.asynctasks.AsyncDownloadFilesTask.onPostExecute(AsyncDownloadFilesTask.java:65)
02-21 19:37:29.520: E/AndroidRuntime(407): at com.example.compa.asynctasks.AsyncDownloadFilesTask.onPostExecute(AsyncDownloadFilesTask.java:1)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.AsyncTask.finish(AsyncTask.java:631)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.AsyncTask.access$600(AsyncTask.java:177)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.Handler.dispatchMessage(Handler.java:99)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.Looper.loop(Looper.java:176)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.app.ActivityThread.main(ActivityThread.java:5419)
02-21 19:37:29.520: E/AndroidRuntime(407): at java.lang.reflect.Method.invokeNative(Native Method)
02-21 19:37:29.520: E/AndroidRuntime(407): at java.lang.reflect.Method.invoke(Method.java:525)
02-21 19:37:29.520: E/AndroidRuntime(407): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
02-21 19:37:29.520: E/AndroidRuntime(407): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
02-21 19:37:29.520: E/AndroidRuntime(407): at dalvik.system.NativeStart.main(Native Method)
line:
02-21 19:37:29.520: E/AndroidRuntime(407): at com.example.compa.asynctasks.AsyncDownloadFilesTask.onPostExecute(AsyncDownloadFilesTask.java:65)
is the last one of AsyncDownloadFilesTask class, and is a closing bracket, }
Thank you
I don't have enough points to comment, but it looks like delegate is null in your onPostExecute
delegate.processFinish(result); // delegate is null
if that's not the case, you're code stub above doesn't define it though.
I solved on my own.
1st, I move call to the Async Task in the onStart() method, instead of onCreate()
2nd, I made a mistake, in change line
ImageView coverImg = (ImageView)findViewById(R.id.cover_image);
in
coverImg = (ImageView)findViewById(R.id.cover_image);
to avoid a stupid null pointer (I already declared coverImg)!
Anyway, I still don't understand debug's behaviour, but I solved my problem.
Thank you everybody

Android, how can i update a view element from a private inner class which is an AsyncTask

I am making an android application as part of a school assignment.
I need to be able to display a timer in hh:mm:ssand update the timer every second.
I have managed to come up with the code i think will produce the results i need, but i cannot get the AsyncTask to execute every second. This is my current code:
TimerHand timerHand = new TimerHandling(timerTextView);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
timerHand.execute();
} },1000, 1000); // 1000ms == 1 second
This is the Async task this is a nested class inside the class which holds the above code, and the declaration of the TextView tv:
class TimerHandling extends AsyncTask<Void, Void, Void>{
private long secs, mins, hours, millis;
private String timeString;
private TextView tv;
private long startTime;
private boolean stop;
private Handler handler;
public TimerHandling(TextView tv){
this.tv = tv;
startTime = System.currentTimeMillis();
stop = false;
handler = new Handler();
}
#Override
protected Void doInBackground(Void... params) {
while(stop != true){
millis = System.currentTimeMillis() - startTime;
hours += TimeUnit.MILLISECONDS.toHours(millis);
mins += TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis));
secs += TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MILLISECONDS.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis));
timeString = String.format("%02d:%02d:%02d",hours, mins, secs);
handler.post(new Runnable() {
#Override
public void run() {
tv.setText(timeString);
}
});
}
return null;
}
public void setStopCondition(boolean condition){
this.stop = condition;
}
}
}
It produces the following logCat output:
01-23 18:00:27.865: E/AndroidRuntime(14458): FATAL EXCEPTION: AsyncTask #5
01-23 18:00:27.865: E/AndroidRuntime(14458): Process: dcs.aber.ac.uk.cs211.group02, PID: 14458
01-23 18:00:27.865: E/AndroidRuntime(14458): java.lang.RuntimeException: An error occured while executing doInBackground()
01-23 18:00:27.865: E/AndroidRuntime(14458): at android.os.AsyncTask$3.done(AsyncTask.java:300)
01-23 18:00:27.865: E/AndroidRuntime(14458): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
01-23 18:00:27.865: E/AndroidRuntime(14458): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
01-23 18:00:27.865: E/AndroidRuntime(14458): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
01-23 18:00:27.865: E/AndroidRuntime(14458): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
01-23 18:00:27.865: E/AndroidRuntime(14458): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
01-23 18:00:27.865: E/AndroidRuntime(14458): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
01-23 18:00:27.865: E/AndroidRuntime(14458): at java.lang.Thread.run(Thread.java:841)
01-23 18:00:27.865: E/AndroidRuntime(14458): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
01-23 18:00:27.865: E/AndroidRuntime(14458): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6094)
01-23 18:00:27.865: E/AndroidRuntime(14458): at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:824)
01-23 18:00:27.865: E/AndroidRuntime(14458): at android.view.View.requestLayout(View.java:16431)
01-23 18:00:27.865: E/AndroidRuntime(14458): at android.view.View.requestLayout(View.java:16431)
01-23 18:00:27.865: E/AndroidRuntime(14458): at android.view.View.requestLayout(View.java:16431)
01-23 18:00:27.865: E/AndroidRuntime(14458): at android.view.View.requestLayout(View.java:16431)
01-23 18:00:27.865: E/AndroidRuntime(14458): at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:352)
01-23 18:00:27.865: E/AndroidRuntime(14458): at android.view.View.requestLayout(View.java:16431)
01-23 18:00:27.865: E/AndroidRuntime(14458): at android.widget.TextView.checkForRelayout(TextView.java:6600)
01-23 18:00:27.865: E/AndroidRuntime(14458): at android.widget.TextView.setText(TextView.java:3813)
01-23 18:00:27.865: E/AndroidRuntime(14458): at android.widget.TextView.setText(TextView.java:3671)
01-23 18:00:27.865: E/AndroidRuntime(14458): at android.widget.TextView.setText(TextView.java:3646)
I understand that is is caused because the nested class has a different View so it cannot update the TextView, how can i overcome this?
When i run my code, i can see it executing and after about 2 seconds the app will crash wth the posted error message.
Update:
public void startCountingTimer() {
final Handler handler = new Handler();
final Runnable task = new Runnable()
{
#Override
public void run() {
millis = System.currentTimeMillis() - startTime;
hours += TimeUnit.MILLISECONDS.toHours(millis);
mins += TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis));
secs += TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MILLISECONDS.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis));
timeString = String.format("%02d:%02d:%02d",hours, mins, secs);
handler.postDelayed(task, 1000); //problem on this line
}
};
task.run();
}
I have pointed out the problem with a single line comment, "task" is undeclared.
Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
You are trying to update ui from a non ui thread which is not possible. You should update ui from the ui thread.
Timer runs on a different thread.
Also read threading rules # http://developer.android.com/reference/android/os/AsyncTask.html
I need to be able to display a timer in hh:mm:ss and update the timer every second.
You can use a Handler or a CountDownTimer
Handler is associated with the thread in which it is created.
http://developer.android.com/reference/android/os/Handler.html
Handler m_handler;
Runnable m_handlerTask ;
m_handler = new Handler();
m_handlerTask = new Runnable()
{
#Override
public void run() {
// do something
m_handler.postDelayed(m_handlerTask, 1000);
}
};
m_handlerTask.run();
For the count down timer
Countdowntimer in minutes and seconds
Edit:
public class MainActivity extends Activity {
Handler handler;
Runnable task ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startCountingTimer();
}
public void startCountingTimer() {
handler = new Handler();
task = new Runnable()
{
#Override
public void run() {
// do something
handler.postDelayed(task, 1000);
}
};
task.run();
}
}

my application crashes when i start new thread [duplicate]

This question already has an answer here:
Application crashes while starting the new thread
(1 answer)
Closed 9 years ago.
I have a class where I have implemented runnable and I start the thread in one of the function of this class, and I call this function from the main activity,I create the object of this class and call the method of thread class.My main activity code from where I call this class method is:
broadcast broadcastobject.threadfunc(messages);
My class where I create threads is:
public class broadcast {
private DatagramSocket socket;
String str;
private static final int TIMEOUT_MS = 10;
WifiManager mWifi;
EditText et;
DatagramPacket packet;
Button bt;
private static final int SERVERPORT = 11111;
private static final String SERVER_IP = "192.168.1.255";
public void threadfunc(String message){
str=message;
new Thread(new ClientThread()).start();
}
/*
private InetAddress getBroadcastAddress() throws IOException {
DhcpInfo dhcp = mWifi.getDhcpInfo();
if (dhcp == null) {
//Log.d(TAG, "Could not get dhcp info");
return null;
}
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
return InetAddress.getByAddress(quads);
}
*/
class ClientThread implements Runnable {
#Override
public void run() {
try {
socket = new DatagramSocket(SERVERPORT);
socket.setBroadcast(true);
// socket.setSoTimeout(TIMEOUT_MS);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InetAddress serverAddr = null;
try {
serverAddr = InetAddress.getByName(SERVER_IP);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
packet = new DatagramPacket(str.getBytes(), str.length(),serverAddr,SERVERPORT);
try {
socket.send(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
My log cat is:
08-31 21:55:56.277: D/gralloc_goldfish(1669): Emulator without GPU emulation detected.
08-31 21:56:02.467: D/AndroidRuntime(1669): Shutting down VM
08-31 21:56:02.467: W/dalvikvm(1669): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
08-31 21:56:02.517: E/AndroidRuntime(1669): FATAL EXCEPTION: main
08-31 21:56:02.517: E/AndroidRuntime(1669): java.lang.NullPointerException
08-31 21:56:02.517: E/AndroidRuntime(1669): at soft.b.peopleassist.Send$1.onClick(Send.java:113)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.view.View.performClick(View.java:3480)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.view.View$PerformClick.run(View.java:13983)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.os.Handler.handleCallback(Handler.java:605)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.os.Handler.dispatchMessage(Handler.java:92)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.os.Looper.loop(Looper.java:137)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.app.ActivityThread.main(ActivityThread.java:4340)
08-31 21:56:02.517: E/AndroidRuntime(1669): at java.lang.reflect.Method.invokeNative(Native Method)
08-31 21:56:02.517: E/AndroidRuntime(1669): at java.lang.reflect.Method.invoke(Method.java:511)
08-31 21:56:02.517: E/AndroidRuntime(1669): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
08-31 21:56:02.517: E/AndroidRuntime(1669): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
08-31 21:56:02.517: E/AndroidRuntime(1669): at dalvik.system.NativeStart.main(Native Method)
This simply means that the emulator you are using does not have GPU emulation enabled. In Android SDK Tools R15 you can enable GPU emulation.You need to create a new emulator virtual device and set GPU emulation to true in Hardware properties.

NetWork On main thread Exception

Hi, I try to check network connectivity and Internet present by using following method
check = new ConnectionDetector(getApplicationContext());
conn = check.isConnectingToInternet();
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context){
this._context = context;
}
/**
* Checking for all possible internet providers
* **/
/*public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}*/
public boolean isConnectingToInternet(){
try{
ConnectivityManager cm = (ConnectivityManager)_context.getSystemService
(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
Log.d("NetInfo", String.valueOf(netInfo));
if (netInfo != null && netInfo.isConnected())
{
//Network is available but check if we can get access from the network.
URL url = new URL("http://www.Google.com/");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(2000); // Timeout 2 seconds.
urlc.connect();
Log.d("NetInfo Response Code", String.valueOf(urlc.getResponseCode()));
// Toast.makeText(getApplicationContext(), String.valueOf(urlc.getResponseCode()), Toast.LENGTH_LONG).show();
if (urlc.getResponseCode() == 200) //Successful response.
{
return true;
}
else
{
Log.d("NO INTERNET", "NO INTERNET");
return false;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return false;
}
}
Note :
But this will return NetworkOnMainThread Exception like follows.kindly any one suggest me what mistakes i made.......
03-27 12:53:35.617: W/System.err(1095): android.os.NetworkOnMainThreadException
03-27 12:53:35.627: W/System.err(1095): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)
03-27 12:53:35.637: W/System.err(1095): at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
03-27 12:53:35.637: W/System.err(1095): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
03-27 12:53:35.647: W/System.err(1095): at java.net.InetAddress.getAllByName(InetAddress.java:220)
03-27 12:53:35.647: W/System.err(1095): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:71)
03-27 12:53:35.657: W/System.err(1095): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
03-27 12:53:35.668: W/System.err(1095): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:351)
03-27 12:53:35.668: W/System.err(1095): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)
03-27 12:53:35.677: W/System.err(1095): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
03-27 12:53:35.687: W/System.err(1095): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
03-27 12:53:35.699: W/System.err(1095): at libcore.net.http.HttpEngine.connect(HttpEngine.java:303)
03-27 12:53:35.699: W/System.err(1095): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
03-27 12:53:35.707: W/System.err(1095): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
03-27 12:53:35.718: W/System.err(1095): at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
03-27 12:53:35.727: W/System.err(1095): at com.slet.routemytrips.beta.ConnectionDetector.isConnectingToInternet(ConnectionDetector.java:50)
03-27 12:53:35.727: W/System.err(1095): at com.slet.routemytrips.beta.Disclaimer$1.onClick(Disclaimer.java:178)
03-27 12:53:35.738: W/System.err(1095): at android.view.View.performClick(View.java:3480)
03-27 12:53:35.738: W/System.err(1095): at android.view.View$PerformClick.run(View.java:13983)
03-27 12:53:35.748: W/System.err(1095): at android.os.Handler.handleCallback(Handler.java:605)
03-27 12:53:35.757: W/System.err(1095): at android.os.Handler.dispatchMessage(Handler.java:92)
03-27 12:53:35.757: W/System.err(1095): at android.os.Looper.loop(Looper.java:137)
03-27 12:53:35.767: W/System.err(1095): at android.app.ActivityThread.main(ActivityThread.java:4340)
03-27 12:53:35.777: W/System.err(1095): at java.lang.reflect.Method.invokeNative(Native Method)
03-27 12:53:35.777: W/System.err(1095): at java.lang.reflect.Method.invoke(Method.java:511)
03-27 12:53:35.787: W/System.err(1095): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-27 12:53:35.797: W/System.err(1095): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-27 12:53:35.807: W/System.err(1095): at dalvik.system.NativeStart.main(Native Method)
03-27 12:57:05.237: D/dalvikvm(90): GC_CONCURRENT freed 666K, 10% free 12624K/14023K, paused 6ms+10ms
You can't make HTTP requests on the main thread, it would cause the UI to freeze up. So it throws that exception. You need to do it in an AsyncTask or another Thread.
http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
NetworkOnMainThreadException is thrown if you attempt to make a network request in the main UI Thread. So all network related operation should be done on the background thread.
AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask.
http://developer.android.com/reference/android/os/AsyncTask.html
class TheTask extends AsyncTask<Void,Void,Void>
{
protected void onPreExecute()
{ super.onPreExecute();
//display progressdialog.
}
protected void doInBackground(Void ...params)
{
//http request. do not update ui here
return null;
}
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
//dismiss progressdialog.
//update ui
}
}
An alternative to asynctask is Robospice. Can make multiple spice request. Notifies on the ui thread. https://github.com/octo-online/robospice
To check Netowrk Connectivity.
In your activity
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if(CheckNetwork.isInternetAvailable(MainActivity.this))
{
//call asyntask and make http request.
}
}
CheckNetwork class
public class CheckNetwork {
private static final String TAG = CheckNetwork.class.getSimpleName();
public static boolean isInternetAvailable(Context context)
{
NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info == null)
{
Log.d(TAG,"no internet connection");
return false;
}
else
{
if(info.isConnected())
{
Log.d(TAG," internet connection available...");
return true;
}
else
{
Log.d(TAG," internet connection");
return true;
}
}
}
}

How to upload images to dropbox?

i am trying to upload selected image to dropbox from gallery.I am being stuck up from days because i am getting unable to resume Runtime Exception
My onActivityResult() is
if(requestCode == PIC_UPLOAD) {
System.out.println("Reahced 1");
Uri selectedImage = data.getData();
String[] filePathColumn ={MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null); cursor.moveToFirst();
System.out.println("Reahced 2");
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Uri imageUri=data.getData();
List<NameValuePair> params = new ArrayList<NameValuePair>(1);
params.add(new BasicNameValuePair("image", imageUri.getPath()));
System.out.println("Reahced 3");
/* String outPath = imageUri.toString(); File outFile = new
File(outPath); FileInputStream fis = new FileInputStream(outFile);
mDBApi.putFileOverwriteRequest("/Pic1", fis, outFile.length(),null);
*/
Uri photoUri = data.getData();
String[] proj = {MediaStore.Images.Media.DATA };
Cursor actualimagecursor = managedQuery(photoUri, proj,null, null, null);
int actual_image_column_index =
actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToFirst();
String img_path =actualimagecursor.getString(actual_image_column_index);
System.out.println("Image location: " + img_path);
System.out.println("Reached 1");
uploadDropbox(img_path);
}
And uploadDropbox body is:
private void uploadDropbox(String URL) {
// TODO Auto-generated method stub
AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeys, ACCESS_TYPE);
mDBApi = new DropboxAPI<AndroidAuthSession>(session);
System.out.println(URL);
System.out.println("Reahced 4");
mDBApi.getSession().startAuthentication(MyCamActivity.this);
System.out.println("Reahced 5");
// AccessTokenPair access = getStoredKeys();
// mDBApi.getSession().setAccessTokenPair(access);
FileInputStream inputStream = null;
try {
File file = new File(URL.toString());
inputStream = new FileInputStream(file);
com.dropbox.client2.DropboxAPI.Entry newEntry = mDBApi.putFile("/testing.txt", inputStream, file.length(), null, null);
Log.i("DbExampleLog", "The uploaded file's rev is: " + newEntry.rev);
} catch (DropboxUnlinkedException e) {
// User has unlinked, ask them to link again here.
Log.e("DbExampleLog", "User has unlinked.");
} catch (DropboxException e) {
Log.e("DbExampleLog", "Something went wrong while uploading.");
} catch (FileNotFoundException e) {
Log.e("DbExampleLog", "File not found.");
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {}
}
}
}
onResume method body:
protected void onResume() {
super.onResume();
if (mDBApi.getSession().authenticationSuccessful()) {
try {
// MANDATORY call to complete auth.
// Sets the access token on the session
mDBApi.getSession().finishAuthentication();
AccessTokenPair tokens = mDBApi.getSession().getAccessTokenPair();
// Provide your own storeKeys to persist the access token pair
// A typical way to store tokens is using SharedPreferences
storeKeys(tokens.key, tokens.secret);
} catch (IllegalStateException e) {
Log.i("DbAuthLog", "Error authenticating", e);
}
}
}
private AccessTokenPair getStoredKeys() {
// TODO Auto-generated method stub
return mDBApi.getSession().getAccessTokenPair();
}
private void storeKeys(String key, String secret) {
// TODO Auto-generated method stub
// Save the access key for later
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.putString(ACCESS_KEY_NAME, key);
edit.putString(ACCESS_SECRET_NAME, secret);
edit.commit();
}
AndroidManifest.xml
<activity
android:name="com.dropbox.client2.android.AuthActivity"
android:launchMode="singleTask"
android:configChanges="orientation|keyboard">
<intent-filter>
<!-- Change this to be db- followed by your app key -->
<data android:scheme="db-MyKey" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".MyCamActivity"
android:label="#string/app_name"
android:screenOrientation="nosensor" android:configChanges="keyboardHidden|orientation"
android:uiOptions="splitActionBarWhenNarrow"
android:clearTaskOnLaunch="true"
>
Error**:
01-23 14:58:00.855: D/dalvikvm(4238): GC_FOR_ALLOC freed 104K, 2% free 12729K/12935K, paused 16ms
01-23 14:58:00.894: I/System.out(4238): Its not null
01-23 14:58:00.901: D/AndroidRuntime(4238): Shutting down VM
01-23 14:58:00.901: W/dalvikvm(4238): threadid=1: thread exiting with uncaught exception (group=0x40a511f8)
01-23 14:58:00.901: E/AndroidRuntime(4238): FATAL EXCEPTION: main
01-23 14:58:00.901: E/AndroidRuntime(4238): java.lang.RuntimeException: Unable to resume activity {cam.pack/cam.pack.MyCamActivity}: java.lang.NullPointerException
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2444)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2472)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1986)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.app.ActivityThread.access$600(ActivityThread.java:123)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.os.Handler.dispatchMessage(Handler.java:99)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.os.Looper.loop(Looper.java:137)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-23 14:58:00.901: E/AndroidRuntime(4238): at java.lang.reflect.Method.invokeNative(Native Method)
01-23 14:58:00.901: E/AndroidRuntime(4238): at java.lang.reflect.Method.invoke(Method.java:511)
01-23 14:58:00.901: E/AndroidRuntime(4238): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-23 14:58:00.901: E/AndroidRuntime(4238): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-23 14:58:00.901: E/AndroidRuntime(4238): at dalvik.system.NativeStart.main(Native Method)
01-23 14:58:00.901: E/AndroidRuntime(4238): Caused by: java.lang.NullPointerException
01-23 14:58:00.901: E/AndroidRuntime(4238): at cam.pack.MyCamActivity.onResume(MyCamActivity.java:571)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1154)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.app.Activity.performResume(Activity.java:4539)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2434)
01-23 14:58:00.901: E/AndroidRuntime(4238): ... 12 more
I have made a mistake, i have put dropbox session in my own defined function uploadDropbox(), and thats a an error causes NullPointerException, because if i print mDBApi so its NULL. Its not been intialized. We have to put these lines in onCreate() and now its working, images are uploading in CameraUploads folder in Dropbox.
Thanks for comments.

Categories