How to implement a internet audio stream buffer? - java

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

Related

Download and save PDF on sdcard not found

I'm trying to download a pdf from an url and then save and read it. But I get the error java.io.IOException: /storage/emulated/0/pdf/menu.pdf not found as file or resource. when I try to read it. Any idea ?
Here is my Downloader class :
public class Downloader {
public static void DownloadFile(String fileURL, File directory) {
try {
FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
And the line to download and read the pdf :
String extStorageDirectory = Environment.getExternalStorageDirectory().getAbsolutePath()
.toString();
File folder = new File(extStorageDirectory, "pdf");
folder.mkdir();
File file = new File(folder, "menu.pdf");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
Downloader.DownloadFile("http://webdfd.mines-ales.fr/restau/Menu_Semaine.pdf", file);
PdfReader reader = new PdfReader(Environment.getExternalStorageDirectory().getAbsolutePath()+"/pdf/menu.pdf");
Here is the error :
05-02 13:59:01.138 16747-16747/? I/art: Not late-enabling -Xcheck:jni (already on)
05-02 13:59:01.139 16747-16747/? W/art: Unexpected CPU variant for X86 using defaults: x86
05-02 13:59:01.676 16747-16747/com.example.yohannmbp.ematoufaire I/InstantRun: starting instant run server: is main process
05-02 13:59:01.868 16747-16747/com.example.yohannmbp.ematoufaire 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
05-02 13:59:02.440 16747-16787/com.example.yohannmbp.ematoufaire D/NetworkSecurityConfig: No Network Security Config specified, using platform default
05-02 13:59:02.783 16747-16795/com.example.yohannmbp.ematoufaire I/OpenGLRenderer: Initialized EGL, version 1.4
05-02 13:59:02.783 16747-16795/com.example.yohannmbp.ematoufaire D/OpenGLRenderer: Swap behavior 1
05-02 13:59:02.783 16747-16795/com.example.yohannmbp.ematoufaire W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
05-02 13:59:02.783 16747-16795/com.example.yohannmbp.ematoufaire D/OpenGLRenderer: Swap behavior 0
05-02 13:59:03.029 16747-16747/com.example.yohannmbp.ematoufaire W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
05-02 13:59:11.011 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: java.io.IOException: No such file or directory
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.io.UnixFileSystem.createFileExclusively0(Native Method)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:280)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.io.File.createNewFile(File.java:948)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.example.yohannmbp.ematoufaire.MenuFragment.onCreateView(MenuFragment.java:106)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.os.Handler.handleCallback(Handler.java:751)
05-02 13:59:11.013 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
05-02 13:59:11.013 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.os.Looper.loop(Looper.java:154)
05-02 13:59:11.013 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6119)
05-02 13:59:11.013 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.lang.reflect.Method.invoke(Native Method)
05-02 13:59:11.013 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
05-02 13:59:11.013 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
05-02 13:59:11.015 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: java.io.FileNotFoundException: /storage/emulated/0/pdf/menu.pdf (No such file or directory)
05-02 13:59:11.015 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.io.FileOutputStream.open(Native Method)
05-02 13:59:11.016 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
05-02 13:59:11.016 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:169)
05-02 13:59:11.016 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.example.yohannmbp.ematoufaire.Downloader.DownloadFile(Downloader.java:18)
05-02 13:59:11.016 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.example.yohannmbp.ematoufaire.MenuFragment.onCreateView(MenuFragment.java:110)
05-02 13:59:11.017 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
05-02 13:59:11.017 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
05-02 13:59:11.017 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
05-02 13:59:11.017 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.os.Handler.handleCallback(Handler.java:751)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.os.Looper.loop(Looper.java:154)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6119)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.lang.reflect.Method.invoke(Native Method)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
05-02 13:59:11.088 16747-16752/com.example.yohannmbp.ematoufaire I/art: Do partial code cache collection, code=30KB, data=29KB
05-02 13:59:11.089 16747-16752/com.example.yohannmbp.ematoufaire I/art: After code cache collection, code=23KB, data=25KB
05-02 13:59:11.089 16747-16752/com.example.yohannmbp.ematoufaire I/art: Increasing code cache capacity to 128KB
05-02 13:59:11.127 16747-16747/com.example.yohannmbp.ematoufaire I/System.out: java.io.IOException: /storage/emulated/0/pdf/menu.pdf not found as file or resource.
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
**strong text** #Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(AppConstant.BASE_URL + URLEncoder.encode(sUrl[0], "UTF-8"));
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
fileName = sUrl[0].substring(sUrl[0].lastIndexOf("/") + 1,
sUrl[0].length());
input = connection.getInputStream();
output = new FileOutputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + fileName);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
mWakeLock.release();
mProgressDialog.dismiss();
if (result != null)
Toast.makeText(context, "Download error: File is not Found.", Toast.LENGTH_LONG).show();
else {
new AlertDialog.Builder(context)
//.setTitle("Delete entry")
.setMessage("File Downloaded Successfully. Do you want to open it?")
.setPositiveButton("Open", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + fileName);
MimeTypeMap map = MimeTypeMap.getSingleton();
String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName());
String type = map.getMimeTypeFromExtension(ext);
if (type == null)
type = "*/*";
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri data = Uri.fromFile(file);
intent.setDataAndType(data, type);
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "There is no app registered to handle the type of file selected.", Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show();
}
}
}
try this
downloadTask = new DownloadTask();
downloadTask.execute("http://webdfd.mines-ales.fr/restau/Menu_Semaine.pdf", "", "");
private class DownloadTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
ll_view.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
File sourcePath = Environment.getExternalStorageDirectory();
File path = new File(sourcePath + "/" + Constants.DIR_NAME + "/");
path.mkdir();
File file = new File(path, "/ecute("http://webdfd.mines-ales.fr/restau/Menu_Semaine.pdf");
if (file.exists()) {
file.delete();
}
output = new FileOutputStream(file);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
ll_view.setVisibility(View.GONE);
}
#Override
protected void onProgressUpdate(final Integer... values) {
super.onProgressUpdate(values);
// Log.e("progressing", "" + values[0]);
// edt_search.setText("" + values[0]);
// new Thread(new Runnable() {
// public void run() {
progressBar.setProgress(values[0]);
// tv_downloading.setText("" + values[0] + "%");
// }
// }).start();
}
#Override
protected void onCancelled(String s) {
super.onCancelled(s);
}
#Override
protected void onCancelled() {
super.onCancelled();
}
}
if your target and compile sdk higher than lolipop then you have to add request permission code before download refer this link and read and write external storage permission required

Not moving to profile screen even after giving genuine credentials in login page

In database we have login details {"email":"nagu#gmail.com","pwd":"12345"}.By using REST services I got the URL, I need to validate the credentials and move to next screen. But unable to move to next screen so please help me
public class LoginScreen extends DIBaseActivty {
public static final int CONNECTION_TIMEOUT=10000;
public static final int READ_TIMEOUT=15000;
private EditText editTextUsername;
private EditText editTextPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
editTextUsername = (EditText)findViewById(R.id.emaiId);
editTextPassword = (EditText)findViewById(R.id.password);
}
public void buttonLogin (View arg0)
{
final String username = editTextUsername.getText().toString();
final String password = editTextPassword.getText().toString();
new TaskLogin().execute(username,password);
}
public class TaskLogin extends AsyncTask<String,String,String>
{
ProgressDialog pdLoading = new ProgressDialog(LoginScreen.this);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage("\t Loading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try{
url = new URL("http://localhost:8080/RestSpring/DialysisInfo/login");
} catch (MalformedURLException e) {
e.printStackTrace();
return "exception";
}
try{
conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("username",params[0])
.appendQueryParameter("password",params[1]);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1)
{
e1.printStackTrace();
return "Exception";
}
try{
int response_code = conn.getResponseCode();
if(response_code==HttpURLConnection.HTTP_OK)
{
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line= reader.readLine())!=null)
{
result.append(line);
}
return (result.toString());
} else { return ("unsuccessful");
}
} catch (IOException e)
{
e.printStackTrace();
return "Exception";
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
pdLoading.dismiss();
if(result.equalsIgnoreCase("true"))
{
Intent intent = new Intent(LoginScreen.this,DIUserProfile.class);
startActivity(intent);
LoginScreen.this.finish();
}else if (result.equalsIgnoreCase("false"))
{
Toast.makeText(LoginScreen.this, "Invalid email or password", Toast.LENGTH_LONG).show();
} else if(result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful"))
{
Toast.makeText(LoginScreen.this, "OOPs! Something went wrong. Connection Problem.", Toast.LENGTH_LONG).show();
}
}
}
}
Here is my error log
02-02 10:42:56.660 25016-27263/com.dialysis
W/System.err: java.net.ConnectException: failed to connect to localhost/127.0.0.1 (port 8080) after 10000ms: isConnected failed: ECONNREFUSED (Connection refused)
02-02 10:42:56.661 25016-27263/com.dialysis W/System.err: at libcore.io.IoBridge.isConnected(IoBridge.java:238)
02-02 10:42:56.661 25016-27263/com.dialysis W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:171)
02-02 10:42:56.661 25016-27263/com.dialysis W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:122)
02-02 10:42:56.663 25016-27263/com.dialysis W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
02-02 10:42:56.663 25016-27263/com.dialysis W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:456)
02-02 10:42:56.664 25016-27263/com.dialysis W/System.err: at java.net.Socket.connect(Socket.java:882)
02-02 10:42:56.664 25016-27263/com.dialysis W/System.err: at com.android.okhttp.internal.Platform.connectSocket(Platform.java:174)
02-02 10:42:56.664 25016-27263/com.dialysis W/System.err: at com.android.okhttp.Connection.connect(Connection.java:152)
02-02 10:42:56.665 25016-27263/com.dialysis W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:276)
02-02 10:42:56.665 25016-27263/com.dialysis W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
02-02 10:42:56.665 25016-27263/com.dialysis W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
02-02 10:42:56.665 25016-27263/com.dialysis W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
02-02 10:42:56.666 25016-27263/com.dialysis W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:217)
02-02 10:42:56.666 25016-27263/com.dialysis W/System.err: at com.dialysis.renalteam.app.ui.activities.LoginScreen$TaskLogin.doInBackground(LoginScreen.java:86)
02-02 10:42:56.666 25016-27263/com.dialysis W/System.err: at com.dialysis.renalteam.app.ui.activities.LoginScreen$TaskLogin.doInBackground(LoginScreen.java:49)
02-02 10:42:56.666 25016-27263/com.dialysis W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:292)
02-02 10:42:56.666 25016-27263/com.dialysis W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
02-02 10:42:56.666 25016-27263/com.dialysis W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
02-02 10:42:56.666 25016-27263/com.dialysis W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
02-02 10:42:56.666 25016-27263/com.dialysis W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
02-02 10:42:56.666 25016-27263/com.dialysis W/System.err: at java.lang.Thread.run(Thread.java:818)
02-02 10:42:56.667 25016-27263/com.dialysis W/System.err: Caused by: android.system.ErrnoException: isConnected failed: ECONNREFUSED (Connection refused)
02-02 10:42:56.667 25016-27263/com.dialysis W/System.err: at libcore.io.IoBridge.isConnected(IoBridge.java:223)
02-02 10:42:56.667 25016-27263/com.dialysis W/System.err: ... 20 more
02-02 10:42:56.714 25016-25071/com.dialysis W/EGL_emulation: eglSurfaceAttrib not implemented
02-02 10:42:56.714 25016-25071/com.dialysis W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xb43cbb00, error=EGL_SUCCESS
02-02 10:42:57.143 25016-25071/com.dialysis W/EGL_emulation: eglSurfaceAttrib not implemented
02-02 10:42:57.144 25016-25071/com.dialysis W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xb43cbd20, error=EGL_SUCCESS
02-02 10:52:41.787 25016-25030/com.dialysis W/art: Suspending all threads took: 5.515ms
From your logcat:
java.net.ConnectException: failed to connect to localhost/127.0.0.1 (port 8080) after 10000ms: isConnected failed: ECONNREFUSED (Connection refused)
Your Android app failed to connect to the server. Set debug breakpoints and check the following:
Url is correct
Method name is correct
Parameters key and value are correct
Server is working fine or not
Since you have not specified you are connected to a server from the device or emulator so I guess you are using your application in the emulator.
If you are referring your localhost on your system from the Android emulator then you have to use http://10.0.2.2:8080/ Because Android emulator runs in a Virtual Machine therefore here 127.0.0.1 or localhost will be emulator's own loopback address.
Replace: url = http://localhost:8080/RestSpring/DialysisInfo/login"
With : url = "http://10.0.2.2:8080/RestSpring/DialysisInfo/login"

android sending files using socket

I am using wifi direct to send file between two android phones.
sender code:
OutputStream outputStream = null;
InputStream inputStream = null;
try {
outputStream = socket.getOutputStream();
inputStream = new FileInputStream(exportTempFile);
byte[] buf = new byte[socket.getSendBufferSize()];
int len = 0;
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.flush();
return 0;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
if (outputStream != null) {
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
receiver code:
OutputStream outputStream = null;
InputStream inputStream = null;
try {
tempDir = new File(context.getCacheDir(), "temp");
if (!tempDir.exists()) {
tempDir.mkdir();
}
File file = new File(tempDir, "temp.zip");
file.createNewFile();
outputStream = new FileOutputStream(file);
inputStream = socket.getInputStream();
byte[] buf = new byte[socket.getReceiveBufferSize()];
int len = 0;
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
outputStream.flush();
}
return file;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
if (outputStream != null) {
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
However, I always get "W/System.err" at the receiver side when running bytestream.copy . I wonder if I did something wrong. Did I close socket too early so the other side can not get data?
error is as below:
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ java.net.SocketException: recvfrom failed: ETIMEDOUT (Connection timed out)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at libcore.io.IoBridge.maybeThrowAfterRecvfrom(IoBridge.java:545)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at libcore.io.IoBridge.recvfrom(IoBridge.java:509)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at java.io.InputStream.read(InputStream.java:163)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at cc.megaman.led.service.ImportManager$ImportTask.doInBackground(ImportManager.java:420)
10-15 17:13:50.172 13921-14306/cc.megaman.led W/System.err﹕ at cc.megaman.led.service.ImportManager$ImportTask.doInBackground(ImportManager.java:377)
10-15 17:13:50.172 13921-14306/cc.megaman.led W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
10-15 17:13:50.172 13921-14306/cc.megaman.led W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:234)
10-15 17:13:50.172 13921-14306/cc.megaman.led W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
10-15 17:13:50.172 13921-14306/cc.megaman.led W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
10-15 17:13:50.182 13921-14306/cc.megaman.led W/System.err﹕ at java.lang.Thread.run(Thread.java:841)
10-15 17:13:50.182 13921-14306/cc.megaman.led W/System.err﹕ Caused by: libcore.io.ErrnoException: recvfrom failed: ETIMEDOUT (Connection timed out)
10-15 17:13:50.182 13921-14306/cc.megaman.led W/System.err﹕ at libcore.io.Posix.recvfromBytes(Native Method)
10-15 17:13:50.182 13921-14306/cc.megaman.led W/System.err﹕ at libcore.io.Posix.recvfrom(Posix.java:140)
10-15 17:13:50.182 13921-14306/cc.megaman.led W/System.err﹕ at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:164)
10-15 17:13:50.182 13921-14306/cc.megaman.led W/System.err﹕ at libcore.io.IoBridge.recvfrom(IoBridge.java:506)

Button not creating a file and showing email provider option menu when pressed

I've created a button that creates a file then sends it as an attachment to an email,
it grabs the text from one of the textviews, saves it to a .txt and sends it. A small email service option selector should show up too. The code is meant to create a file path if one is not already there. This code is above the onCreate method and in a regular activity.
i keep getting this in the logcat (specific message marked by (-->)):
-->08-06 12:53:01.019 18432-18432/com.example.adrian.trucktracker W/System.err﹕ java.io.IOException: open failed: ENOENT (No such file or directory)<---
08-06 12:53:01.019 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at java.io.File.createNewFile(File.java:946)
08-06 12:53:01.019 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at com.example.adrian.trucktracker.Locator.clickedUpdate(Locator.java:76)
08-06 12:53:01.019 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
08-06 12:53:01.019 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.view.View$1.onClick(View.java:3860)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.view.View.performClick(View.java:4480)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.view.View$PerformClick.run(View.java:18686)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:733)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:95)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.os.Looper.loop(Looper.java:157)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5872)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:852)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:668)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at libcore.io.Posix.open(Native Method)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at java.io.File.createNewFile(File.java:939)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ ... 15 more
My code:
public void clickedUpdate(View view)
{
TextView dLong = (TextView) findViewById (R.id.textLong);
TextView dLat = (TextView) findViewById (R.id.textLat);
String dataLat = dLat.getText().toString();
String dataLong = dLong.getText().toString();
boolean UpdateResume;
if(!(dataLat.equals("") && !(dataLong.equals(""))))
{
UpdateResume = true;
}
else
{
UpdateResume = false;
}
TelephonyManager telephonemanager =(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
String PhoneNumber = telephonemanager.getLine1Number();
File DataDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"/LocationData");
if(!DataDir.exists())
{
try
{
DataDir.mkdir();
}
catch (Exception e)
{
e.printStackTrace();
}
}
File Data = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"data" + File.separator+"Locationer.txt");
String datapath = Data + ""
if(!Data.exists())
{
try {
line 76 ----> Data.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
while (UpdateResume = true)
{
if (Data.exists())
{
try
{
FileWriter fileWriter = new FileWriter(Data);
BufferedWriter bfWriter = new BufferedWriter(fileWriter);
bfWriter.write(PhoneNumber + "," + dataLat + "," + dataLong);
bfWriter.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
break;
}
}
Intent emailintent = new Intent(Intent.ACTION_SEND);
emailintent.setType("text/plain");
emailintent.putExtra(Intent.EXTRA_EMAIL, new String[]{"apraiswater#legion-logistics.com"});
emailintent.putExtra(Intent.EXTRA_SUBJECT, "Data");
emailintent.putExtra(Intent.EXTRA_TEXT, "Hello World!");
File root = Environment.getExternalStorageDirectory();
String DataAttachment = "Android/data/Locationer.txt";
File filer = new File(root, DataAttachment);
if (!filer.exists() || filer.canRead())
{
return;
}
Uri uri = Uri.fromFile(filer);
emailintent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(emailintent, "Choose an Email provider"));
}
A few details seem relevant:
First you check the existence of the dir:
File DataDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"/LocationData");
if(!DataDir.exists())
{
try
{
DataDir.mkdir();
}
catch (Exception e)
{
e.printStackTrace();
}
}
according to the documentation, your try{}catch(Exception e){} aren't needed. You just would need to check whether the directory actually exists. There's the additional problem that you seem to create a subdirectory of another subdirectory. So, you might want to exchange it to mkdirs() instead.
Afterwards, you try to create the File if it doesn't exist
try {
line 76 ----> Data.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Take a look at the documentation for this method. You might note that it tells you
This method is not generally useful. For creating temporary files, use
createTempFile(String, String) instead. For reading/writing files, use
FileInputStream, FileOutputStream, or RandomAccessFile, all of which
can create files.
but maybe, if you've included the proper permissions, the changes I suggested above will help to make your code work.

KitKat Connection from URL get NullPointerException in AsyncTask

i'm new in java and android programming but i accepted a challenge launched by a friend and now i have to work hard.
I finally managed to have this type of activity working with AsyncTask but it seems to work well on all android but not on 4.4.2 KitKat.
The problem seems to be on url.openConnection and i tried many times to change the way in wich i do it but i haven't had positive results...
I have only to read file from an URL
This is my class code:
public class MenuActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
new HttpTask().execute();
}
public final class HttpTask
extends
AsyncTask<String/* Param */, Boolean /* Progress */, String /* Result */> {
private HttpClient mHc = new DefaultHttpClient();
#Override
protected String doInBackground(String... params) {
publishProgress(true);
InputStream inputstream = null;
URL url = null;
try {
url = new URL("http://somesite/prova.txt");
} catch (MalformedURLException e) {
e.printStackTrace();
}
assert url != null;
URLConnection connection = null;
try {
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputstream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
ByteArrayOutputStream bytearryoutputstream = new ByteArrayOutputStream();
int i;
try {
i = inputstream.read();
while (i != -1) {
bytearryoutputstream.write(i);
i = inputstream.read();
}
inputstream.close();
} catch (IOException e) {
e.printStackTrace();
}
return bytearryoutputstream.toString();
}
#Override
protected void onProgressUpdate(Boolean... progress) {
}
#Override
protected void onPostExecute(String result) {
StringBuilder nuovafrase=new StringBuilder("");
String[] frasone=result.split("\n");
ListView listView = (ListView)findViewById(R.id.listViewDemo);
ArrayAdapter<String> arrayAdapter;
arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.rowmenu, R.id.textViewList, frasone);
listView.setAdapter(arrayAdapter);
}
}
}
And this is the Logcat...
03-11 17:49:37.955 1277-1294/com.example.appsb.app W/System.err﹕ atjava.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-11 17:49:37.955 1277-1294/com.example.appsb.app W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at java.lang.Thread.run(Thread.java:841)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at libcore.io.Posix.getaddrinfo(Native Method)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ ... 18 more
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ Caused by: libcore.io.ErrnoException: getaddrinfo failed: EACCES (Permission denied)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ ... 21 more
03-11 17:49:37.963 1277-1294/com.example.appsb.app W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0xa4d69b20)
03-11 17:49:37.963 1277-1294/com.example.appsb.app E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.example.appsb.app, PID: 1277
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.example.appsb.app.MenuActivity$HttpTask.doInBackground(MenuActivity.java:74)
at com.example.appsb.app.MenuActivity$HttpTask.doInBackground(MenuActivity.java:33)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
              at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
             at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
             at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
             at java.lang.Thread.run(Thread.java:841)
There is a Caused by: java.lang.NullPointerException but i cannot understand why...
Thanks
It could be caused by the inputstream being null. inputstream will only be initialized if the response code is OK. So you need to check what response code is being returned. If it is not causing the error, I'd still add some code for if the response code is not OK. You don't want your app to crash if it can't connect. You should at least display a helpful error message
Example:
else{
showErrorMsg();
return null;
}
Catch FileNotFoundException when trying inputstream.read();
try {
i = inputstream.read();
while (i != -1) {
bytearryoutputstream.write(i);
i = inputstream.read();
}
inputstream.close();
} catch (FileNotFoundException e) {
Log.e("MyTag","Handling empty page...");
} catch (IOException e) {
Log.e("MyTag",e.toString());
}

Categories