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());
}
}
Related
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());
}
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
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.
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()"
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" />