It reads image from the channel and write it to card. the image in card is completely written and is fine. The only problem is thread in hanged and does not execute any line after that loop.
protected Bitmap doInBackground(String... arg0) {
// TODO Auto-generated method stub'
// Runtime.getRuntime().availableProcessors();
System.out.println("Inside doinback"+ RemoteScreen.out.toString());
try {
RemoteScreen.out.write(210);
//Home.threadloop = false;
Bitmap bitmap = null;
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "a.png";
String imageInSD = baseDir + File.separator + fileName;
System.out.println(imageInSD);
if (is!= null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
// Log.i("IMSERVICE", "FILERECCC-1");
//ContextWrapper context = null;
fos = new FileOutputStream(imageInSD);
bos = new BufferedOutputStream(fos);
byte[] aByte = new byte[1024];
int bytesRead;
//thread stuck in this loop and does not move forward
while ( (bytesRead = is.read(aByte)) > 0 ) {
if (bytesRead == 1)
break;
bos.write(aByte, 0, bytesRead);
System.out.println("Loop"+aByte);
}
bos.close();
Log.i("IMSERVICE", "out of loop");
java.io.FileInputStream in = new FileInputStream(imageInSD);
bitmap = BitmapFactory.decodeStream(in);
bitmap = BitmapFactory.decodeFile(imageInSD);
Log.i("IMSERVICE", "saved");
if (bitmap != null)
System.out.println(bitmap.toString());
} catch (IOException ex) {
// Do exception handling
// Log.i("IMSERVICE", "exception ");
}
}
publishProgress(b);
b = null;
ch = 4646;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
log trace shows following error.
05-10 20:34:42.715: E/AndroidRuntime(1135): FATAL EXCEPTION: AsyncTask #3
05-10 20:34:42.715: E/AndroidRuntime(1135): java.lang.RuntimeException: An error occured while executing doInBackground()
05-10 20:34:42.715: E/AndroidRuntime(1135): at android.os.AsyncTask$3.done(AsyncTask.java:299)
05-10 20:34:42.715: E/AndroidRuntime(1135): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
05-10 20:34:42.715: E/AndroidRuntime(1135): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
05-10 20:34:42.715: E/AndroidRuntime(1135): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
05-10 20:34:42.715: E/AndroidRuntime(1135): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
05-10 20:34:42.715: E/AndroidRuntime(1135): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
05-10 20:34:42.715: E/AndroidRuntime(1135): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
05-10 20:34:42.715: E/AndroidRuntime(1135): at java.lang.Thread.run(Thread.java:856)
05-10 20:34:42.715: E/AndroidRuntime(1135): Caused by: java.lang.NullPointerException
05-10 20:34:42.715: E/AndroidRuntime(1135): at com.rms.remotedesktop1.screencahnge.doInBackground(screencahnge.java:43)
05-10 20:34:42.715: E/AndroidRuntime(1135): at com.rms.remotedesktop1.screencahnge.doInBackground(screencahnge.java:1)
05-10 20:34:42.715: E/AndroidRuntime(1135): at android.os.AsyncTask$2.call(AsyncTask.java:287)
05-10 20:34:42.715: E/AndroidRuntime(1135): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
According to the logcat, the code is crashing at line 43 with a Null Pointer Exception, and I can't tell which line 43 is. However:
Have you checked that Environment.getExternalStorageDirectory().getAbsolutePath() is returning non null? It maybe that there is no external storage directory, or you don't have permission to know about it.
It is also worth reading the developer pages, http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory(), which note that you shouldn't write to that directory, which you seem to be doing.
I solved this problem by myself. There was error in static variable who was changing his value due to logical error in code.
Related
I have created an application containing image to video maker and i using MediaMuxer to creating video from sequence of images but SlideEncoder add second image to auto close MediaMuxer and application is crush.
05-22 07:58:33.691 6091-6122/com.aspiration.imagetovideomaker E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.IllegalStateException
at android.media.MediaCodec.native_configure(Native Method)
at android.media.MediaCodec.configure(MediaCodec.java:257)
at com.aspiration.imagetovideomaker.encoding.SlideEncoder.prepareEncoder(SlideEncoder.java:57)
at com.aspiration.imagetovideomaker.ImageToVideo$EncodingTask.doInBackground(ImageToVideo.java:221)
at com.aspiration.imagetovideomaker.ImageToVideo$EncodingTask.doInBackground(ImageToVideo.java:205)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
here my video creation code:
SlideEncoder slideEncoder = new SlideEncoder();
try {
slideEncoder.prepareEncoder(outputFile);
Bitmap prevBm = null;
dialog.setMax(MyApplication.bitmapList.size());
for (int idx = 0; idx < MyApplication.bitmapList.size(); idx++) {
publishProgress(String.valueOf(idx + 1));
SlideShow.init();
if (idx > 0) prevBm = MyApplication.bitmapList.get(idx - 1);
Bitmap curBm = MyApplication.bitmapList.get(idx);
for (int i = 0; i < (MyApplication.FRAME_PER_SEC * MyApplication.SLIDE_TIME); i++) {
// Drain any data from the encoder into the muxer.
slideEncoder.drainEncoder(false);
// Generate a frame and submit it.
slideEncoder.generateFrame(curBm, curBm);
//slideEncoder.generateFrame(prevBm, curBm);
}
}
slideEncoder.drainEncoder(true);
} catch (IOException e) {
e.printStackTrace();
} finally {
slideEncoder.releaseEncoder();
}
here my prepareEncoder
public void prepareEncoder(File outputFile) throws IOException {
mBufferInfo = new MediaCodec.BufferInfo();
try {
MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, WIDTH, HEIGHT);
format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
format.setInteger(MediaFormat.KEY_BIT_RATE, MyApplication.BIT_RATE);
format.setInteger(MediaFormat.KEY_FRAME_RATE, MyApplication.FRAME_PER_SEC);
format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, IFRAME_INTERVAL);
mEncoder = MediaCodec.createEncoderByType(MIME_TYPE);
mEncoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
mInputSurface = mEncoder.createInputSurface();
mEncoder.start();
mMuxer = new MediaMuxer(outputFile.getPath().toString(), MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
mTrackIndex = -1;
mMuxerStarted = false;
} catch (Exception e) {
e.printStackTrace();
Log.e("SlideEncoder", e.toString());
}
}
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
I have this doInBackground method which records audio streams from the internet. The main work is being done inside while (len != -1) { }. This works fine however the buffer = new byte[] doesn't work as I expected - when the connection is interrupted the IOException is called immidiately and the buffer is not used anymore. How can I make this buffer to "feed" my code till it is empty? I want to have the same behavior like it is in audio players; so first when you connect to the stream (it is buffering), then playing and if the connection is interrupted it is still playing from the buffer (till it is empty).
Recorder:
protected Boolean doInBackground(String... StringUrls) {
boolean fdetermined = false;
Environment env = new Environment();
Calendar c = Calendar.getInstance();
BufferedOutputStream bufOutstream = null;
buffer = new byte[1024 * 10];
int len=-1;
InputStream in = null;
URLConnection conn = null;
try{
conn = new URL(StringUrls[0]).openConnection();
conn.setConnectTimeout(5000);
in = conn.getInputStream();
len = in.read(buffer);
File dir = new File(env.getExternalStorageDirectory() + "/somewhere");
if (!dir.exists()) {
dir.mkdir();
}
filename = env.getExternalStorageDirectory()+"/somewhere/file";
bufOutstream = new BufferedOutputStream(new FileOutputStream(new File(filename)));
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}
while (len != -1) {
if(in != null && buffer != null && bufOutstream != null) {
try {
bufOutstream.write(buffer, 0, len);
len = in.read(buffer);
if (Recorder.this.isCancelled) {
Recorder.this.stopSelf();
break;
}
} catch (IOException e) {
e.printStackTrace();
conn = null;
in = null;
}
}
}
try{
if(bufOutstream != null) {
bufOutstream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
IO Exception:
12-16 14:37:16.999 31950-32021/com.app.example W/System.err﹕ java.net.SocketException: recvfrom failed: ETIMEDOUT (Connection timed out)
12-16 14:37:17.059 31950-32021/com.app.example W/System.err﹕ at libcore.io.IoBridge.maybeThrowAfterRecvfrom(IoBridge.java:542)
12-16 14:37:17.109 31950-32021/com.app.example W/System.err﹕ at libcore.io.IoBridge.recvfrom(IoBridge.java:506)
12-16 14:37:17.109 31950-32021/com.app.example W/System.err﹕ at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
12-16 14:37:17.109 31950-32021/com.app.example W/System.err﹕ at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
12-16 14:37:17.119 31950-32021/com.app.example W/System.err﹕ at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
12-16 14:37:17.119 31950-32021/com.app.example W/System.err﹕ at java.io.BufferedInputStream.read(BufferedInputStream.java:304)
12-16 14:37:17.149 31950-32021/com.app.example W/System.err﹕ at libcore.net.http.UnknownLengthHttpInputStream.read(UnknownLengthHttpInputStream.java:41)
12-16 14:37:17.149 31950-32021/com.app.example W/System.err﹕ at java.io.InputStream.read(InputStream.java:163)
12-16 14:37:17.189 31950-32021/com.app.example W/System.err﹕ at com.app.example.Recorder$RecordTask.doInBackground(Recorder.java:376)
12-16 14:37:17.189 31950-32021/com.app.example W/System.err﹕ at com.app.example.Recorder$RecordTask.doInBackground(Recorder.java:288)
12-16 14:37:17.189 31950-32021/com.app.example W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:264)
12-16 14:37:17.189 31950-32021/com.app.example W/System.err﹕ at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:137)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at java.lang.Thread.run(Thread.java:856)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ Caused by: libcore.io.ErrnoException: recvfrom failed: ETIMEDOUT (Connection timed out)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at libcore.io.Posix.recvfromBytes(Native Method)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at libcore.io.Posix.recvfrom(Posix.java:131)
12-16 14:37:17.209 31950-32021/com.app.example W/System.err﹕ at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:164)
12-16 14:37:17.209 31950-32021/com.app.example W/System.err﹕ at libcore.io.IoBridge.recvfrom(IoBridge.java:503)
I have added finally block below:
while (len != -1) {
if(in != null && buffer != null && bufOutstream != null) {
try {
bufOutstream.write(buffer, 0, len);
len = in.read(buffer);
if (Recorder.this.isCancelled) {
Recorder.this.stopSelf();
break;
}
} catch (IOException e) {
e.printStackTrace();
conn = null;
in = null;
}
finally{
//do your work here. This block will execute no matter of what exception is thrown
try{
if(bufOutstream != null) {
bufOutstream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Hi there I have 2 classes in order to push a file into an android device.
My Server CLass:
public class FileServer {
public static void main (String [] args ) throws IOException {
// create socket
ServerSocket servsock = new ServerSocket(13267);
while (true) {
System.out.println("Waiting...");
Socket sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
// sendfile
File myFile = new File ("C:\\Users\\Petrica\\Desktop\\zzz.txt");
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();
sock.close();
}
}
}
And my Client Class:
public class TCPClient extends AsyncTask{
#Override
protected Object doInBackground(Object... params) {
int filesize=6022386; // filesize temporary hardcoded
long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
// localhost for testing
Socket sock = null;
try {
sock = new Socket("127.0.0.1",13267);
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("Connecting...");
// receive file
try {
byte [] mybytearray = new byte [filesize];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("/mnt/sdcard/zzz.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
// thanks to A. Cádiz for the bug fix
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
sock.close();
// TODO Auto-generated method stub
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
I get an error
09-09 15:52:39.261: E/AndroidRuntime(802): FATAL EXCEPTION: AsyncTask #1
09-09 15:52:39.261: E/AndroidRuntime(802): java.lang.RuntimeException: An error occured while executing doInBackground()
09-09 15:52:39.261: E/AndroidRuntime(802): at android.os.AsyncTask$3.done(AsyncTask.java:299)
09-09 15:52:39.261: E/AndroidRuntime(802): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
09-09 15:52:39.261: E/AndroidRuntime(802): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
09-09 15:52:39.261: E/AndroidRuntime(802): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
09-09 15:52:39.261: E/AndroidRuntime(802): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
09-09 15:52:39.261: E/AndroidRuntime(802): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
09-09 15:52:39.261: E/AndroidRuntime(802): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
09-09 15:52:39.261: E/AndroidRuntime(802): at java.lang.Thread.run(Thread.java:841)
09-09 15:52:39.261: E/AndroidRuntime(802): Caused by: java.lang.NullPointerException
09-09 15:52:39.261: E/AndroidRuntime(802): at com.aaaaaa.TCPClient.doInBackground(TCPClient.java:33)
09-09 15:52:39.261: E/AndroidRuntime(802): at com.aaaaaa.TCPClient.doInBackground(TCPClient.java:1)
09-09 15:52:39.261: E/AndroidRuntime(802): at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-09 15:52:39.261: E/AndroidRuntime(802): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
09-09 15:52:39.261: E/AndroidRuntime(802): ... 4 more
MainActivity:
public class MainActivity extends Activity {
TCPClient tcpc;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.send_button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tcpc.execute();
}
});
}
}
Does anyone have an idea what should I do ??? In the future i would like to send 2 files :D .Thanks in advice .
You're really expected to be able to sort out your own NullPointerExceptions: at least I expect it, but when you get past that, your copy code is wrong. You are presently ignoring the count returned by read() and assuming it fills the buffer. It isn't guaranteed to do that. See the Javadoc.
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
Use this at both ends, with any buffer size > 0, typically 8192.
I don't think your Socket is connecting, but its hard to tell. IN your log output, it says NullPointerException caused by doInBackground() line 33. You should check line 33 in your editor, and better yet, show us in your post which line is 33. I kind of have a feeling that you call Socket sock = null;, then you try and instantiate a new Socket in a try block, but that fails, so sock still == null, then you call a method on sock, and boom, NPE.
If you are running the Server on a computer, and the AsyncTask on an Android device, you won't be able to try and connect to localhost (127.0.0.1). You should instead try to connect to the internal network ip of your computer (something like 192.168.1.XXX), assuming both devices are on WiFi. If you are running an android emulator, then 127.0.0.1 refers back to the emulated device, and all emulator sessions run on an emulated router that you will have to configure for port forwarding before you can refer to the development machine, see here-->http://developer.android.com/tools/devices/emulator.html#emulatornetworking
As Andras Balazs Lajtha says, it looks like TCPClient isn't ever initialized/created during onCreate(), it is only declared. Since your logcat output shows errors from TCPClient though, I assume you have that code actually running.
In general, when you post a log output that refers to problems with a specific line of code, you should start there, and when you post, tell us or show us which line that is. And of course, if line 33 isn't related to a null Socket object, then I haven't been much help at all :)
my AsyncCode and Service code is running fine, but when i merge them together it crashes my application's GUI, the code manages to write to the database.
I am new to android development so i do not quite know why it crashes.
This is my code for the method
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Log.e("<<myServiceRunner-onStart>>", "I am alive-3!");
Thread triggerService = new Thread(new Runnable(){
String msg = "message";
long startingTime = System.currentTimeMillis();
long tics = 0;
#Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; (i < 120) & isRunning; i++) {
try {
tics = System.currentTimeMillis() - startingTime;
Intent myFilterResponse = new Intent("liren.action.GOSERVICE3");
//WIFI METHOD START
mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
registerReceiver(new BroadcastReceiver()
{
#Override
public void onReceive(Context c, Intent intent)
{
results = mainWifi.getScanResults();
size = results.size();
ScanResult bestSignal = null;
for (ScanResult result : results) {
if (bestSignal == null
|| WifiManager.compareSignalLevel(bestSignal.level, result.level) < 0)
{
bestSignal = result;
}
}
msg = tics + " Strongest Network: " + bestSignal.SSID + " - Signal Strength:" + bestSignal.level;
new sendPostData().execute(Integer.toString(bestSignal.level) ,bestSignal.SSID.toString());
}
}, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
mainWifi.startScan();
//WIFI METHOD END
myFilterResponse.putExtra("serviceData", msg);
sendBroadcast(myFilterResponse);
Thread.sleep(1000);
} catch (Exception e){
e.printStackTrace();
}
}
}});
triggerService.start();
}
private class sendPostData extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpPost request = new HttpPost(SERVICE_URI + "/StrongestWifi");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
JSONStringer getWifiInfo;
try {
getWifiInfo = new JSONStringer()
.object()
.key("myWifiClass")
.object()
.key("SignalStrength").value(params[0])
.key("SSID").value(params[1])
.endObject()
.endObject();
StringEntity entity = new StringEntity(getWifiInfo.toString());
request.setEntity(entity);
// Send request to WCF service
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
Log.d("WebInvoke", "Saving : " + response.getStatusLine().getStatusCode());
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
}
}
And here is my log cat:
>06-02 09:58:42.112: E/<<myServiceRunner-onStart>>(21871): I am alive-3!
>06-02 09:58:42.151: E/MAIN>>>(21871): message - receiving data 179736967
>06-02 09:58:42.252: E/SpannableStringBuilder(21871): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
>06-02 09:58:42.260: E/SpannableStringBuilder(21871): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
>06-02 09:58:42.276: E/SpannableStringBuilder(21871): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
>06-02 09:58:42.276: E/SpannableStringBuilder(21871): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
>06-02 09:58:43.127: W/dalvikvm(21871): threadid=18: thread exiting with uncaught exception (group=0x40d09930)
>06-02 09:58:43.135: E/MAIN>>>(21871): 2 Strongest Network: Chiameng - Signal Strength:-69 - receiving data 179737949
>06-02 09:58:43.166: E/AndroidRuntime(21871): FATAL EXCEPTION: AsyncTask #5
>06-02 09:58:43.166: E/AndroidRuntime(21871): java.lang.RuntimeException: An error occured while executing doInBackground()
>06-02 09:58:43.166: E/AndroidRuntime(21871): at android.os.AsyncTask$3.done(AsyncTask.java:299)
>06-02 09:58:43.166: E/AndroidRuntime(21871): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
>06-02 09:58:43.166: E/AndroidRuntime(21871): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
>06-02 09:58:43.166: E/AndroidRuntime(21871): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
>06-02 09:58:43.166: E/AndroidRuntime(21871): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
>06-02 09:58:43.166: E/AndroidRuntime(21871): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
>06-02 09:58:43.166: E/AndroidRuntime(21871): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
>06-02 09:58:43.166: E/AndroidRuntime(21871): at java.lang.Thread.run(Thread.java:856)
>06-02 09:58:43.166: E/AndroidRuntime(21871): Caused by: java.lang.IllegalArgumentException: Illegal character in scheme at index 0: 192.168.1.64:4567/AllocationService.svc/StrongestWifi
>06-02 09:58:43.166: E/AndroidRuntime(21871): at java.net.URI.create(URI.java:727)
>06-02 09:58:43.166: E/AndroidRuntime(21871): at org.apache.http.client.methods.HttpPost.<init>(HttpPost.java:79)
>06-02 09:58:43.166: E/AndroidRuntime(21871): at com.example.pcsprojectnetworkcodes.myServiceRunner$sendPostData.doInBackground(myServiceRunner.java:118)
>06-02 09:58:43.166: E/AndroidRuntime(21871): at com.example.pcsprojectnetworkcodes.myServiceRunner$sendPostData.doInBackground(myServiceRunner.java:1)
>06-02 09:58:43.166: E/AndroidRuntime(21871): at android.os.AsyncTask$2.call(AsyncTask.java:287)
>06-02 09:58:43.166: E/AndroidRuntime(21871): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
>06-02 09:58:43.166: E/AndroidRuntime(21871): ... 4 more
>06-02 09:58:44.166: E/MAIN>>>(21871): 2 Strongest Network: Chiameng - Signal Strength:-69 - receiving data 179738981
>06-02 09:58:44.409: W/dalvikvm(21871): threadid=12: thread exiting with uncaught exception (group=0x40d09930)
>06-02 09:58:44.409: I/Process(21871): Sending signal. PID: 21871 SIG: 9
There is a probleme with your SERVICE_URI variable. Maybe a misplaced space.
Or maybe you have forgotten the "http://" (or equivalent) at the beginning...
There seems to be a problem here:
Illegal character in scheme at index 0
which refers to this line here:
HttpPost request = new HttpPost(SERVICE_URI + "/StrongestWifi");
Most likely you have a space at the beginning of the SERVICE_URI?
I would bet that you have a space (' ') in front of the URL that you're passing:
192.168.1.64:4567/AllocationService.svc/StrongestWifi
Double-check that. You might just need to do a String#trim() on the URL.
In Your Async Task you should have Return type of doInBackground and postExecute must be same . And You are return null that why it give you error