I use the following code to copy a directory and some files to sdcard. The directory I copy is placed in the assets folder.
public class CopyAssets extends Activity{
Button btn;
File sdCard = Environment.getExternalStorageDirectory();
private CameraBaseActivity mCamBase;
protected static String copyStatus;
CopyAssets(String path){
//copyFileOrDir(path);
copyStatus = "loading";
mCamBase = CameraBaseActivity.getInstance();
if(isSdPresent())
new MoveDir().execute(path);
}
private class MoveDir extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
copyStatus = "loaded";
copyFileOrDir("edu.cmu.pocketsphinx");
return (copyStatus);
}
#Override
protected void onPostExecute(String result) {
//TextView txt = (TextView) findViewById(R.id.output);
//txt.setText("Executed"); // txt.setText(result);
// might want to change "executed" for the returned string passed
// into onPostExecute() but that is upto you
mCamBase.initARParams();
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
private void copyFileOrDir(String path) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
File dir = new File(sdCard.getAbsolutePath() + "/" + path);
if (!dir.exists()) {
System.out.println("Created directory"
+ sdCard.getAbsolutePath());
boolean result = dir.mkdir();
System.out.println("Result of directory creation" + result);
}
for (int i = 0; i < assets.length; ++i) {
copyFileOrDir(path + "/" + assets[i]);
}
}
} catch (IOException ex) {
System.out.println("Exception in copyFileOrDir" + ex);
}
}
private void copyFile(String filename) {
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
// String newFileName = "/data/data/" + this.getPackageName() + "/"
// + filename;//path for storing internally to data/data
String newFileName = sdCard.getAbsolutePath() + "/" + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
System.out.println("File created in path" + newFileName);
} catch (Exception e) {
System.out.println("Exception in copyFile" + e);
// System.out.println("Exception in copyFile"+e.print);
// Log.e("tag", e.printStackTrace());
}
}
public static boolean isSdPresent() {
return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
}
}
Exception is in doinbackground:
01-01 00:00:41.679: WARN/dalvikvm(1530): threadid=11: thread exiting with uncaught exception (group=0x40b3d1f8)
01-01 00:00:41.687: ERROR/CameraBaseActivity(1530): uncaughtException.
01-01 00:00:41.695: ERROR/CameraBaseActivity(1530): at android.os.AsyncTask$3.done(AsyncTask.java:278)
01-01 00:00:41.695: ERROR/CameraBaseActivity(1530): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-01 00:00:41.695: ERROR/CameraBaseActivity(1530): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-01 00:00:41.703: ERROR/CameraBaseActivity(1530): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-01 00:00:41.703: INFO/ActivityManager(292): Start proc com.test.android.imageplugin for service com.test.android.imageplugin/.ImagePluginServer: pid=1549 uid=6062 gids={1015, 1023}
01-01 00:00:41.710: ERROR/LL_Core(1530): [LifeLogSecurityUtility]lifelogdb permission error
01-01 00:00:41.710: ERROR/CameraBaseActivity(1530): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-01 00:00:41.710: ERROR/CameraBaseActivity(1530): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
01-01 00:00:41.710: ERROR/CameraBaseActivity(1530): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-01 00:00:41.710: ERROR/CameraBaseActivity(1530): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-01 00:00:41.710: ERROR/CameraBaseActivity(1530): at java.lang.Thread.run(Thread.java:856)
01-01 00:00:41.710: ERROR/CameraBaseActivity(1530): java.lang.RuntimeException: An error occured while executing doInBackground()
01-01 00:00:41.710: ERROR/CameraBaseActivity(1530): uncaughtException.
01-01 00:00:41.710: ERROR/CameraBaseActivity(1530): uncaughtException : other thread.
01-01 00:00:41.710: ERROR/CameraBaseActivity(1530): LLDB regist error. unregisted.
01-01 00:00:41.710: DEBUG/Camera(1530): Capture get() mIsExecuteRegistMenu=false
01-01 00:00:41.710: DEBUG/Camera(1530): onResumeImpl start
01-01 00:00:41.710: DEBUG/Camera(1530): execDisplayLayoutChangeNonSync start rotation:0
01-01 00:00:41.726: DEBUG/Camera(1530): onResumeImpl end
01-01 00:00:41.726: INFO/CameraBaseActivity(1530): onResume end
01-01 00:00:41.726: INFO/CameraBaseActivity(1530): onPostResume
01-01 00:00:41.890: INFO/CameraBaseActivity(1530): Camera.finish
I cannot find why it crashes unexpectedly in doinbackground as I cannot see any error with my code I posted here.Any help is much appreciated.
what is LifeLogSecurityUtility?
It is possible this line:
[LifeLogSecurityUtility]lifelogdb permission error
is telling you that you are missing a permission tag in your manifest. Though I am not familiar with this LifeLogSecurityUtility so I wouldn't know which permission that thing is wanting you to have.
If you have not done so already add the WRITE_EXTERNAL_STORAGE permission to your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
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 have a php/mysql query working that looks up the VIN, if the VIN is in the database it returns "VIN already exists" Where did I screw up in this: Error report say Fatal Exception : AsyncTask #2 (I have code that actually works above this, problem started when I tried to rewrite this to run the php checkVin before launching the Sell page)
11-21 16:34:43.736: E/AndroidRuntime(725): FATAL EXCEPTION: AsyncTask #2
11-21 16:34:43.736: E/AndroidRuntime(725): java.lang.RuntimeException: An error occured while executing doInBackground()
11-21 16:34:43.736: E/AndroidRuntime(725): at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-21 16:34:43.736: E/AndroidRuntime(725): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.lang.Thread.run(Thread.java:856)
11-21 16:34:43.736: E/AndroidRuntime(725): Caused by: java.lang.IllegalArgumentException: Host name may not be null
11-21 16:34:43.736: E/AndroidRuntime(725): at org.apache.http.HttpHost.<init>(HttpHost.java:83)
11-21 16:34:43.736: E/AndroidRuntime(725): at org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:497)
11-21 16:34:43.736: E/AndroidRuntime(725): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:626)
11-21 16:34:43.736: E/AndroidRuntime(725): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:616)
11-21 16:34:43.736: E/AndroidRuntime(725): at com.mobile.donswholesale.Scan.getServerResopnse(Scan.java:272)
11-21 16:34:43.736: E/AndroidRuntime(725): at com.mobile.donswholesale.Scan.access$1(Scan.java:260)
11-21 16:34:43.736: E/AndroidRuntime(725): at com.mobile.donswholesale.Scan$4.doInBackground(Scan.java:240)
11-21 16:34:43.736: E/AndroidRuntime(725): at com.mobile.donswholesale.Scan$4.doInBackground(Scan.java:1)
11-21 16:34:43.736: E/AndroidRuntime(725): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-21 16:34:43.736: E/AndroidRuntime(725): ... 5 more
private void addSellButtonListener() {
Button sell = (Button) findViewById(R.id.sell_button);
sell.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendDatatoServer();
}
});
}
private String formatDataAsJASON() {
JSONObject root = new JSONObject();
try {
root.put("User", userId.getText().toString());
root.put("Pword", userPass.getText().toString());
root.put("VIN", VINID.getText().toString());
return root.toString();
} catch (JSONException e) {
Log.d("JWP", "Can't format JSON");
}
return null;
}
private void sendDatatoServer() {
final String json = formatDataAsJASON();
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
return getServerResopnse(json);
}
#Override
protected void onPostExecute(String result) {
if (result == "VIN already exists") {
Toast.makeText(Scan.this,
getString(R.string.vin_exists), Toast.LENGTH_LONG)
.show();
final Intent i = new Intent(Scan.this, Scan.class);
startActivity(i);
} else {
StartSell();
}
}
}.execute();
}
private String getServerResopnse(String json) {
HttpPost post = new HttpPost("http://" + serverIp.getText().toString()
+ "/chekVIN.php");
try {
StringEntity entity = new StringEntity(json);
post.setEntity(entity);
post.setHeader("Content-type", "application/json");
DefaultHttpClient client = new DefaultHttpClient();
BasicResponseHandler handler = new BasicResponseHandler();
String response = client.execute(post, handler);
return response;
} catch (UnsupportedEncodingException e) {
Log.d("JWP", e.toString());
} catch (ClientProtocolException e) {
Log.d("JWP", e.toString());
} catch (IOException e) {
Log.d("JWP", e.toString());
}
return null;
}
private void StartSell() {
final Intent i = new Intent(Scan.this, Sell.class);
EditText editText = (EditText) findViewById(R.id.VIN);
String text = editText.getText().toString();
EditText editText2 = (EditText) findViewById(R.id.Make);
String text2 = editText2.getText().toString();
EditText editText3 = (EditText) findViewById(R.id.Model);
String text3 = editText3.getText().toString();
EditText editText4 = (EditText) findViewById(R.id.Color);
String text4 = editText4.getText().toString();
EditText editText5 = (EditText) findViewById(R.id.Year);
String text5 = editText5.getText().toString();
try {
FileOutputStream fos = openFileOutput(VinHolder,
Context.MODE_PRIVATE);
fos.write(text.getBytes());
fos.close();
FileOutputStream fos2 = openFileOutput(MakeHolder,
Context.MODE_PRIVATE);
fos2.write(text2.getBytes());
fos2.close();
FileOutputStream fos3 = openFileOutput(ModelHolder,
Context.MODE_PRIVATE);
fos3.write(text3.getBytes());
fos3.close();
FileOutputStream fos4 = openFileOutput(ColorHolder,
Context.MODE_PRIVATE);
fos4.write(text4.getBytes());
fos4.close();
FileOutputStream fos5 = openFileOutput(YearHolder,
Context.MODE_PRIVATE);
fos5.write(text5.getBytes());
fos5.close();
}
catch (Exception e) {
Log.d("DEBUGTAG", "File Not Saved" + text);
e.printStackTrace();
}
startActivity(i);
}
Because I use a Text file from another page of the app to hold a manually entered ip address, I needed to carry that info over so that the the HttpPost("http://" +serverIp.getText().toString() + "chechvin.php"); would actually have the ip address in it.
After adding:
public static final String SERVERIP= "sinfo.txt";
everything worked just fine.
I need your help, there is an Fatal Error in my code. I don't know how to solve this problem... please help me out :)
my code
public class MainActivity extends Activity {
// button to show progress dialog
Button btnShowProgress;
// Progress Dialog
private ProgressDialog pDialog;
ImageView my_image;
// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar_type = 0;
// File url to download
private static String file_url = "https://example.pdf";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// show progress bar button
btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
// Image view to show image after downloading
my_image = (ImageView) findViewById(R.id.my_image);
/**
* Show Progress bar click event
* */
btnShowProgress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// starting new Async Task
new DownloadFileFromURL().execute(file_url);
}
});
}
/**
* Showing Dialog
* */
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
private SSLContext context;
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
This line is the error in: URL url = new URL(f_url[0]);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
// Load the truststore that includes self-signed cert as a "trusted" entry.
KeyStore truststore;
truststore = KeyStore.getInstance("BKS");
InputStream in = getActivity().getResources().openRawResource(R.raw.mykeystore);
truststore.load(in, "mysecret".toCharArray());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(truststore);
// Create custom SSL context that incorporates that truststore
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
connection.setSSLSocketFactory(sslContext.getSocketFactory());
connection.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(connection.getInputStream(), 8192);
// Output stream
OutputStream output = new FileOutputStream("/sdcard/downloadedfile.pdf");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
private ContextWrapper getActivity() {
// TODO Auto-generated method stub
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.pdf";
// setting downloaded into image view
my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}
}
}
and this is my Logcat :
03-21 16:36:26.747: E/AndroidRuntime(5751): FATAL EXCEPTION: AsyncTask #1
03-21 16:36:26.747: E/AndroidRuntime(5751): Process: com.example.test2, PID: 5751
03-21 16:36:26.747: E/AndroidRuntime(5751): java.lang.RuntimeException: An error occured while executing doInBackground()
03-21 16:36:26.747: E/AndroidRuntime(5751): at android.os.AsyncTask$3.done(AsyncTask.java:300)
03-21 16:36:26.747: E/AndroidRuntime(5751): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
03-21 16:36:26.747: E/AndroidRuntime(5751): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
03-21 16:36:26.747: E/AndroidRuntime(5751): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
03-21 16:36:26.747: E/AndroidRuntime(5751): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
03-21 16:36:26.747: E/AndroidRuntime(5751): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-21 16:36:26.747: E/AndroidRuntime(5751): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-21 16:36:26.747: E/AndroidRuntime(5751): at java.lang.Thread.run(Thread.java:841)
03-21 16:36:26.747: E/AndroidRuntime(5751): Caused by: java.lang.NullPointerException: println needs a message
03-21 16:36:26.747: E/AndroidRuntime(5751): at android.util.Log.println_native(Native Method)
03-21 16:36:26.747: E/AndroidRuntime(5751): at android.util.Log.e(Log.java:232)
03-21 16:36:26.747: E/AndroidRuntime(5751): at com.example.test1.MainActivity$DownloadFileFromURL.doInBackground(MainActivity.java:194)
03-21 16:36:26.747: E/AndroidRuntime(5751): at com.example.test1.MainActivity$DownloadFileFromURL.doInBackground(MainActivity.java:1)
03-21 16:36:26.747: E/AndroidRuntime(5751): at android.os.AsyncTask$2.call(AsyncTask.java:288)
03-21 16:36:26.747: E/AndroidRuntime(5751): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-21 16:36:26.747: E/AndroidRuntime(5751): ... 4 more
Stacktrace output
03-21 18:39:45.957: W/System.err(2061): java.lang.NullPointerException
03-21 18:39:45.967: W/System.err(2061): at com.example.test1.MainActivity$DownloadFileFromURL.doInBackground(MainActivity.java:147)
03-21 18:39:45.967: W/System.err(2061): at com.example.test1.MainActivity$DownloadFileFromURL.doInBackground(MainActivity.java:1)
03-21 18:39:45.967: W/System.err(2061): at android.os.AsyncTask$2.call(AsyncTask.java:288)
03-21 18:39:45.967: W/System.err(2061): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-21 18:39:45.967: W/System.err(2061): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
03-21 18:39:45.967: W/System.err(2061): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-21 18:39:45.967: W/System.err(2061): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-21 18:39:45.967: W/System.err(2061): at java.lang.Thread.run(Thread.java:841)
Try
Log.e("Error:", " " + e.getMessage());
Instead of Log.e("Error: ", e.getMessage());
// e.getMessage() could be null or empty.
Also add catch(MalformedURLException e) {} and see why the url exception is thrown
Make your AsyncTask extend AsyncTask<String, Void, String>.
I am stuck and gone crazy to resolve this issue but no luck with me. I tried all the guidelines that SO member giving me as i had asked this question before:( Thank all of you who respond. I search alot to resolve it but never succeed last hope is SO, so Kindly guide me where I go wrong and how can I resolve this JSONParsing? I posted data from PHP and want to get it on android EditText boxes. I code it but there are some issue which exist from the day one and not resolved yet. I got different LogCat errors on emulator and on Phone. I have posed you my java code and LogCat errors. Any guide will be precious for me.
my Java code is where i got errors:
// save button
btnSave = (Button) findViewById(R.id.btnSave);
// getting product details from intent
Intent i = getIntent();
// getting product id (pid) from intent
cid = i.getStringExtra(TAG_CID);
// save button click event
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// starting background task to update product
new SaveTaskDetails().execute();
}
});
}
#Override
protected void onStart() {
super.onStart();
// Getting complete product details in background thread
new GetTaskDetails().execute();
}
/**
* Background Async Task to Get complete product details
* */
class GetTaskDetails extends AsyncTask<String, String, JSONObject> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
tDialog = new ProgressDialog(My_Task.this);
tDialog.setTitle("Please Wait");
tDialog.setMessage("Retrieving Task Details.");
tDialog.setIndeterminate(false);
tDialog.setCancelable(true);
tDialog.show();
}
/**
* Getting task details in background thread
* #return
**/
protected JSONObject doInBackground(String... params1) {
JSONObject my_task = null;
// updating UI from Background Thread
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("cid", cid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = JSONParser.makeHttpRequest(
url_read_mytask, "GET", params);
// check your log for json response
// Log.d("Single Task Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray my_taskObj = json
.getJSONArray(TAG_MYTASK); // JSON Array
// get first product object from JSON Array
my_task = my_taskObj.getJSONObject(0);
}
else
{
// task with cid not found
}
}
catch (JSONException e) {
e.printStackTrace();
}
return my_task;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(JSONObject my_task) {
// dismiss the dialog once got all details
cus_name_txtbx = (EditText) findViewById(R.id.cus_name_txtbx);
try {
cus_name_txtbx.setText(my_task.getString(TAG_NAME));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
contact_no_txtbx = (EditText) findViewById(R.id.contact_no_txtbx);
try {
contact_no_txtbx.setText(my_task.getString(TAG_CONTACT));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ticket_no_txtbx = (EditText) findViewById(R.id.ticket_no_txtbx);
try {
ticket_no_txtbx.setText(my_task.getString(TAG_TICKET));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
task_detail_txtbx = (EditText) findViewById(R.id.task_detail_txtbx);
try {
task_detail_txtbx.setText(my_task.getString(TAG_TASKDETAIL));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tDialog.dismiss();
}
}
/**
* Background Async Task to Save product Details
* */
class SaveTaskDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
tDialog = new ProgressDialog(My_Task.this);
tDialog.setTitle("Please Wait");
tDialog.setMessage("Saving Task");
tDialog.setIndeterminate(false);
tDialog.setCancelable(true);
tDialog.show();
}
/**
* Saving product
* */
protected String doInBackground(String... args) {
// getting updated data from EditTexts
String cus_name = cus_name_txtbx.getText().toString();
String contact_no = contact_no_txtbx.getText().toString();
String ticket_no = ticket_no_txtbx.getText().toString();
String task_detail = task_detail_txtbx.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_CID, cid));
params.add(new BasicNameValuePair(TAG_NAME, cus_name));
params.add(new BasicNameValuePair(TAG_CONTACT, contact_no));
params.add(new BasicNameValuePair(TAG_TICKET, ticket_no));
params.add(new BasicNameValuePair(TAG_TASKDETAIL, task_detail));
// sending modified data through http request
// Notice that update product url accepts POST method
JSONObject json = JSONParser.makeHttpRequest(url_update_mytask,
"POST", params);
// check json success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully updated
Intent i = getIntent();
// send result code 100 to notify about product update
setResult(100, i);
finish();
} else {
// failed to update product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product uupdated
tDialog.dismiss();
}
}
My Logcat errors are:
01-01 11:28:52.549: E/WindowManager(31782): at java.lang.reflect.Method.invokeNative(Native Method)
01-01 11:38:15.149: E/WindowManager(1133): Activity com.example.visit.record.My_Task has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4054ce88 that was originally added here
01-01 11:38:15.149: E/WindowManager(1133): android.view.WindowLeaked: Activity com.example.visit.record.My_Task has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4054ce88 that was originally added here
01-01 11:38:15.149: E/WindowManager(1133): at android.view.ViewRoot.<init>(ViewRoot.java:277)
01-01 11:38:15.149: E/WindowManager(1133): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
01-01 11:38:15.149: E/WindowManager(1133): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
01-01 11:38:15.149: E/WindowManager(1133): at android.view.Window$LocalWindowManager.addView(Window.java:433)
01-01 11:38:15.149: E/WindowManager(1133): at android.app.Dialog.show(Dialog.java:288)
01-01 11:38:15.149: E/WindowManager(1133): at com.example.visit.record.My_Task$GetTaskDetails.onPreExecute(My_Task.java:139)
01-01 11:38:15.149: E/WindowManager(1133): at android.os.AsyncTask.execute(AsyncTask.java:391)
01-01 11:38:15.149: E/WindowManager(1133): at com.example.visit.record.My_Task.onStart(My_Task.java:118)
01-01 11:38:15.149: E/WindowManager(1133): at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1225)
01-01 11:38:15.149: E/WindowManager(1133): at android.app.Activity.performStart(Activity.java:3941)
01-01 11:38:15.149: E/WindowManager(1133): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1794)
01-01 11:38:15.149: E/WindowManager(1133): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1842)
01-01 11:38:15.149: E/WindowManager(1133): at android.app.ActivityThread.access$1500(ActivityThread.java:132)
01-01 11:38:15.149: E/WindowManager(1133): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1038)
01-01 11:38:15.149: E/WindowManager(1133): at android.os.Handler.dispatchMessage(Handler.java:99)
01-01 11:38:15.149: E/WindowManager(1133): at android.os.Looper.loop(Looper.java:143)
01-01 11:38:15.149: E/WindowManager(1133): at android.app.ActivityThread.main(ActivityThread.java:4268)
01-01 11:38:15.149: E/WindowManager(1133): at java.lang.reflect.Method.invokeNative(Native Method)
01-01 11:38:15.149: E/WindowManager(1133): at java.lang.reflect.Method.invoke(Method.java:507)
01-01 11:38:15.149: E/WindowManager(1133): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-01 11:38:15.149: E/WindowManager(1133): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-01 11:38:15.149: E/WindowManager(1133): at dalvik.system.NativeStart.main(Native Method)
Kindly guide.
I got an error on new GetTaskDetails().execute(); and on **tDialog.show();** on PreExecute of GetTaskDetails Class
The solution is to call dismiss() on the Dialog you created in
viewP.java:183 before exiting the Activity, e.g. in onPause().
Views have a reference to their parent Context (taken from constructor argument). If you leave an Activity without destroying Dialogs and other dynamically created Views, they still hold this reference to your Activity (if you created with this as
Context: like new ProgressDialog(this),
so, it cannot be collected by the GC, causing a memory leak.
you run your UI in background remove from them and in post execute you
can set (e.gcus_name_txtbx.setText(my_task.getString(TAG_NAME));) you
are not set them in doIn romove every UI into the doIn..
I'm trying to develop an autocomplete location for goofle map. But, I have encountered some errors while developing. I do not know what is the cause of the error.
Below is my code.
public class MainActivity extends Activity {
/** Called when the activity is first created. */
ArrayAdapter<String> adapter;
AutoCompleteTextView textView;
Object[] arg0 = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new ArrayAdapter<String>(this, R.layout.item_list);
textView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
adapter.setNotifyOnChange(true);
textView.setAdapter(adapter);
textView.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (count % 3 == 1) {
adapter.clear();
// GetPlaces task = new GetPlaces();
// now pass the argument in the textview to the task
new GetPlaces().execute(textView.getText().toString());
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
}
class GetPlaces extends AsyncTask<String, Void, ArrayList<String>> {
#Override
// three dots is java for an array of strings
protected ArrayList<String> doInBackground(String... args) {
Log.d("gottaGo", "doInBackground");
ArrayList<String> predictionsArr = new ArrayList<String>();
try {
URL googlePlaces = new URL(
// URLEncoder.encode(url,"UTF-8");
"https://maps.googleapis.com/maps/api/place/autocomplete/json?input="
+ URLEncoder.encode(arg0[0].toString(), "UTF-8")
+ "&types=geocode&language=en&sensor=true&key=<API-key here>");
URLConnection tc = googlePlaces.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
StringBuffer sb = new StringBuffer();
// take Google's legible JSON and turn it into one big
// string.
while ((line = in.readLine()) != null) {
sb.append(line);
}
// turn that string into a JSON object
JSONObject predictions = new JSONObject(sb.toString());
// now get the JSON array that's inside that object
JSONArray ja = new JSONArray(
predictions.getString("predictions"));
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
// add each entry to our array
predictionsArr.add(jo.getString("description"));
}
} catch (IOException e) {
Log.e("YourApp", "GetPlaces : doInBackground", e);
} catch (JSONException e) {
Log.e("YourApp", "GetPlaces : doInBackground", e);
}
return predictionsArr;
}
// then our post
#Override
protected void onPostExecute(ArrayList<String> result) {
Log.d("YourApp", "onPostExecute : " + result.size());
// update the adapter
adapter = new ArrayAdapter<String>(getBaseContext(),
R.layout.item_list);
adapter.setNotifyOnChange(true);
// attach the adapter to textview
textView.setAdapter(adapter);
for (String string : result) {
Log.d("YourApp", "onPostExecute : result = " + string);
adapter.add(string);
adapter.notifyDataSetChanged();
}
Log.d("YourApp",
"onPostExecute : autoCompleteAdapter" + adapter.getCount());
}
Here is the logcat error:
10-24 15:10:54.609: E/AndroidRuntime(14346): FATAL EXCEPTION: AsyncTask #1
10-24 15:10:54.609: E/AndroidRuntime(14346): java.lang.RuntimeException: An error occured while executing doInBackground()
10-24 15:10:54.609: E/AndroidRuntime(14346): at android.os.AsyncTask$3.done(AsyncTask.java:278)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
10-24 15:10:54.609: E/AndroidRuntime(14346): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.lang.Thread.run(Thread.java:856)
10-24 15:10:54.609: E/AndroidRuntime(14346): Caused by: java.lang.NullPointerException
10-24 15:10:54.609: E/AndroidRuntime(14346): at com.test.main.MainActivity$GetPlaces.doInBackground(MainActivity.java:76)
10-24 15:10:54.609: E/AndroidRuntime(14346): at com.test.main.MainActivity$GetPlaces.doInBackground(MainActivity.java:1)
10-24 15:10:54.609: E/AndroidRuntime(14346): at android.os.AsyncTask$2.call(AsyncTask.java:264)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
The source of the error is obviously in MainActivity line 76, where you are accessing a null object
in 76th line..
use "URLEncoder.encode(args[0].toString()" instead of "URLEncoder.encode(arg0[0].toString()"