Async task doinbackground exception - java

My async function is this:
class ProfileCategoryCall extends AsyncTask<String, String, String>{
public ProfileCategoryCall() {
// TODO Auto-generated constructor stub
}
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
JSONObject HomeCardString = new JSONObject();
JSONObject ABC = new JSONObject();
try {
responseString = result;
joiningYear = new JSONObject(responseString);
HomeCardString = joiningYear.getJSONObject("CategoryLikesResult");
ABC = HomeCardString.getJSONObject("CategoryLikesResult");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Gson gson = new Gson();
try
{
((ProfileActivity)getActivity()).interestResult = gson.fromJson(ABC.toString(), LikeCategorySummaryResult.class);
}
catch(Exception e)
{
Log.i("myyyy", e.getMessage());
e.printStackTrace();
}
} catch (Throwable t) {
Log.e("My App", "Could not parse malformed JSON: \"" + responseString + "\"" + t.getMessage());
}
PopulateData();
progress.setVisibility(View.GONE);
super.onPostExecute(result);
//Do anything with response..
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progress.setVisibility(View.VISIBLE);
super.onPreExecute();
}
}
While Calling async service call this error occurs.
08-28 11:15:38.140: E/AndroidRuntime(14310): FATAL EXCEPTION: AsyncTask #1
08-28 11:15:38.140: E/AndroidRuntime(14310): java.lang.RuntimeException: An error occured while executing doInBackground()
08-28 11:15:38.140: E/AndroidRuntime(14310): at android.os.AsyncTask$3.done(AsyncTask.java:278)
08-28 11:15:38.140: E/AndroidRuntime(14310): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-28 11:15:38.140: E/AndroidRuntime(14310): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-28 11:15:38.140: E/AndroidRuntime(14310): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-28 11:15:38.140: E/AndroidRuntime(14310): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-28 11:15:38.140: E/AndroidRuntime(14310): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
08-28 11:15:38.140: E/AndroidRuntime(14310): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-28 11:15:38.140: E/AndroidRuntime(14310): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-28 11:15:38.140: E/AndroidRuntime(14310): at java.lang.Thread.run(Thread.java:856)
08-28 11:15:38.140: E/AndroidRuntime(14310): Caused by: java.lang.IllegalArgumentException: Illegal character in query at index 355: http://example.net/Service.svc/android/Profile/1361769105/Like/EXAMPLE?category=Public
08-28 11:15:38.140: E/AndroidRuntime(14310): at java.net.URI.create(URI.java:727)
08-28 11:15:38.140: E/AndroidRuntime(14310): at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:75)
08-28 11:15:38.140: E/AndroidRuntime(14310): at com.stalker.androidapp.InterestTabFragment$ProfileCategoryCall.doInBackground(InterestTabFragment.java:308)
08-28 11:15:38.140: E/AndroidRuntime(14310): at com.stalker.androidapp.InterestTabFragment$ProfileCategoryCall.doInBackground(InterestTabFragment.java:1)
08-28 11:15:38.140: E/AndroidRuntime(14310): at android.os.AsyncTask$2.call(AsyncTask.java:264)
08-28 11:15:38.140: E/AndroidRuntime(14310): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-28 11:15:38.140: E/AndroidRuntime(14310): ... 5 more
I have seen other similar questions, but answers were to remove code which is using UI from doInBackground() and I don't think I have any unnecessary code in it. So please tell me if I am wrong.

Related

Android - Error when uploading multiple images

I got error when I tried to upload all of the images. I use for to loop the process, but still got error in looping. if i don't use for, it still can upload the image but only 1 image that will be uploaded. how can I solve this?
UploadActivity.java
Intent intent = getIntent();
filePath = intent.getStringExtra("filePath");
ArrayList<String> flpath = new ArrayList<String>();
SharedPreferences prefs = getSharedPreferences("SavedFilePathsJSONArray",
Context.MODE_PRIVATE);
String myJSONArrayString = prefs.getString("SavedFilePathsJSONArray",
"");
if (!myJSONArrayString.isEmpty()) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(myJSONArrayString);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < jsonArray.length(); i++) {
try {
flpath.add(jsonArray.get(i).toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
flpath.add(filePath);
JSONArray mJSONArray = new JSONArray(flpath);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("SavedFilePathsJSONArray", mJSONArray.toString()).commit();
for (int i = 0; i < flpath.size(); i++) {
imgFile = new File(flpath.get(i));
if (imgFile.exists()) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(),options);
ImageView myImage = new ImageView(this);
myImage.setMaxHeight(100);
myImage.setMaxWidth(100);
myImage.setImageBitmap(myBitmap);
layout2.addView(myImage);
}
}
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
progressBar.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
progressBar.setVisibility(View.VISIBLE);
// updating progress bar value
progressBar.setProgress(progress[0]);
// updating percentage value
txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
for (int i = 0; i < flPath.size(); i++) {
File file = new File( flPath.get(i));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
// Adding file data to http body
entity.addPart("image", new FileBody(file));
// Extra parameters if you want to pass to server
entity.addPart("website",
new StringBody("www.androidhive.info"));
entity.addPart("email", new StringBody("abc#gmail.com"));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
}
return responseString;
}
Config.Java
public class Config {
public static final String FILE_UPLOAD_URL = "http://....";
// Directory name to store captured images and videos
public static final String IMAGE_DIRECTORY_NAME = "andrd_upload";
}
error logcat
01-27 16:23:45.940: W/dalvikvm(15986): threadid=12: thread exiting with uncaught exception (group=0x40fe7438)
01-27 16:23:45.950: E/AndroidRuntime(15986): FATAL EXCEPTION: AsyncTask #1
01-27 16:23:45.950: E/AndroidRuntime(15986): java.lang.RuntimeException: An error occured while executing doInBackground()
01-27 16:23:45.950: E/AndroidRuntime(15986): at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-27 16:23:45.950: E/AndroidRuntime(15986): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.lang.Thread.run(Thread.java:856)
01-27 16:23:45.950: E/AndroidRuntime(15986): Caused by: java.lang.NullPointerException
01-27 16:23:45.950: E/AndroidRuntime(15986): at com.camerafileupload.UploadActivity$UploadFileToServer.uploadFile(UploadActivity.java:228)
01-27 16:23:45.950: E/AndroidRuntime(15986): at com.camerafileupload.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:221)
01-27 16:23:45.950: E/AndroidRuntime(15986): at com.camerafileupload.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:1)
01-27 16:23:45.950: E/AndroidRuntime(15986): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-27 16:23:45.950: E/AndroidRuntime(15986): ... 5 more
01-27 16:23:46.130: D/HardwareRenderer(15986): draw surface is valid dirty= null
01-27 16:23:46.180: D/HardwareRenderer(15986): draw surface is valid dirty= null
01-27 16:23:46.220: D/HardwareRenderer(15986): draw surface is valid dirty= null
01-27 16:25:29.910: D/dalvikvm(15986): WAIT_FOR_CONCURRENT_GC blocked 0ms
01-27 16:25:29.950: D/dalvikvm(15986): GC_EXPLICIT freed 223K, 8% free 15337K/16583K, paused 2ms+4ms, total 38ms
ScreenShoot
Edit: i put the error logcat and the screenshoot of the error page (UploadActivity.java).

java.lang.NoClassDefFoundError: org.apache.http.Consts

I am converting my project in Studio from eclipse.I am sending image in multi part to sever using httpmime 4.5.1 jar file. This is my code.it gives me NoClassDefFoundError: org.apache.http.Consts error.
Please help me.
This is my code.
new AsyncTask<String, Integer, Void>() {
#Override
protected void onPreExecute() {
// setting progress bar to zero
progressBar.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
// updating progress bar value
progressBar.setProgress(progress[0]);
txtPercentage.setText(progress[0] + "%");
}
#SuppressWarnings("deprecation")
#Override
protected Void doInBackground(String... params) {
for (i = 0; i < allPath.length; i++) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
txtCount.setText((i + 1) + "/"
+ allPath.length);
}
});
allPath[i] = selected.get(i).sdcardPath;
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
Config.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(
compressImage(allPath[i]));
// Adding file data to http body
entity.addPart("tag", new StringBody(
"productAdd"));
// Adding file data to http body
entity.addPart("image",
new FileBody(sourceFile));
entity.addPart(
"seller_id",
new StringBody(
CommonUtilities
.getSellerId(getApplicationContext())));
entity.addPart(
"shop_id",
new StringBody(
CommonUtilities
.getCurentShopId(
getApplicationContext())
.toString()));
entity.addPart(
"product_pId",
new StringBody(
CommonUtilities
.getMaxProductId(
getApplicationContext())
.toString()));
entity.addPart("cat_id", new StringBody(cat_id));
entity.addPart("product_image", new StringBody(
allPath[i]));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient
.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine()
.getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils
.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
flagForError = true;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
flagForError = true;
} catch (IOException e) {
responseString = e.toString();
flagForError = true;
}
if (flagForError == false) {
updateAfterResponse(responseString);
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
uploadDialog.cancel();
dialogForError();
}
});
task.cancel(true);
break;
}
runOnUiThread(new Runnable() {
#Override
public void run() {
progressBar.setProgress(0);
}
});
if (i == allPath.length - 1) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
txtCount.setText("Done");
}
});
}
// return responseString;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// showing the server response in an alert
// dialog
super.onPostExecute(result);
// if (i == (allPath.length - 1)) {
if (uploadDialog.isShowing()) {
uploadDialog.dismiss();
}
}
}.execute();
and it is giving me error
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: Process: com.elsner.orderlite, PID: 10320
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: java.lang.RuntimeException: An error occured while executing doInBackground()
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at android.os.AsyncTask$3.done(AsyncTask.java:300)
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: a`enter code here`t java.util.concurrent.FutureTask.run(FutureTask.java:242)
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at java.lang.Thread.run(Thread.java:841)
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: Caused by: java.lang.NoClassDefFoundError: org.apache.http.Consts
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at org.apache.http.entity.mime.content.StringBody.<init>(StringBody.java:147)
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at com.elsner.sellerproduct.CustomGalleryActivity$2$1.doInBackground(CustomGalleryActivity.java:311)
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at com.elsner.sellerproduct.CustomGalleryActivity$2$1.doInBackground(CustomGalleryActivity.java:221)
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at android.os.AsyncTask$2.call(AsyncTask.java:288)
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at java.lang.Thread.run(Thread.java:841) 
in bundle.gradle use
compile('org.apache.httpcomponents:httpmime:4.3.6') {
exclude module: 'httpclient'
}
compile 'org.apache.httpcomponents:httpclient-android:4.3.5'
To do multipart POST calls, you need to get three additional Apache
open source projects: Apache Commons IO, Mime4j, and HttpMime. You can
download these projects from the following web sites: Commons IO:
http://commons.apache.org/io/ Mime4j: http://james.apache.org/mime4j/
HttpMime: http://hc.apache.org/downloads.cgi (inside of HttpClient)
If you are using sdk version 23, you have to add to your gradle:
android {
compileSdkVersion 23
...
useLibrary 'org.apache.http.legacy'
...
}

AsyncTask error occured while executing doInBackground()

I'm getting an error in following code, calling asyn method for http request. It gives me a java.lang.RuntimeException error inside doInBackground() method.
_____________MAIN class____________
TextView testoInput = (TextView) findViewById(R.id.input);
final String località = testoInput.getText().toString();
bottone1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
TaskAsincrono nuovo = new TaskAsincrono();
nuovo.execute(località);
}
__________ASYNC Class________
public class TaskAsincrono extends AsyncTask > {
protected ArrayList<String> doInBackground(String...params) {
String s = params[0];
ArrayList<String> risultato =null;
//Inizio sessione di invio dati rest con sistema GET
DefaultHttpClient client = new DefaultHttpClient();
String url ="http://www.replycoupon.it/php/rest_Server/index.php?nome="+s;
try {
URI uri = new URI(url);
HttpGet get = new HttpGet(uri);
HttpResponse res = client.execute(get);
InputStream data = res.getEntity().getContent();
//Inizio l'operazione di buffering per la lettura
BufferedReader streamReader = new BufferedReader(new InputStreamReader(data));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr =null;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
JSONObject jObj = new JSONObject(responseStrBuilder.toString());
String clima = jObj.getString("clima");
String temperatura = jObj.getString("temperatura");
//Prima di inviare alla main metto il risultato in un arrylist
risultato.add(clima);
risultato.add(temperatura);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return risultato;
}
protected void onPostExecute(final ArrayList<String> risultato) {
final TextView testoClima = (TextView) findViewById(R.id.Output);
final TextView testoTemp = (TextView) findViewById(R.id.Output2);
testoClima.setText(risultato.get(0).toString());
testoTemp.setText(risultato.get(1).toString());
}
}
LOG
10-02 20:53:07.068: D/dalvikvm(4050): GC_FOR_ALLOC freed 234K, 4% free 7914K/8188K, paused 16ms, total 16ms
10-02 20:53:09.728: W/dalvikvm(4050): threadid=11: thread exiting with uncaught exception (group=0x41800ba8)
10-02 20:53:09.728: E/AndroidRuntime(4050): FATAL EXCEPTION: AsyncTask #1
10-02 20:53:09.728: E/AndroidRuntime(4050): Process: luca.tirocinio.client_json, PID: 4050
10-02 20:53:09.728: E/AndroidRuntime(4050): java.lang.RuntimeException: An error occured while executing doInBackground()
10-02 20:53:09.728: E/AndroidRuntime(4050): at android.os.AsyncTask$3.done(AsyncTask.java:300)
10-02 20:53:09.728: E/AndroidRuntime(4050): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
10-02 20:53:09.728: E/AndroidRuntime(4050): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
10-02 20:53:09.728: E/AndroidRuntime(4050): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
10-02 20:53:09.728: E/AndroidRuntime(4050): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
10-02 20:53:09.728: E/AndroidRuntime(4050): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
10-02 20:53:09.728: E/AndroidRuntime(4050): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
10-02 20:53:09.728: E/AndroidRuntime(4050): at java.lang.Thread.run(Thread.java:841)
10-02 20:53:09.728: E/AndroidRuntime(4050): Caused by: java.lang.NullPointerException
10-02 20:53:09.728: E/AndroidRuntime(4050): at luca.tirocinio.client_json.MainActivity$TaskAsincrono.doInBackground(MainActivity.java:117)
10-02 20:53:09.728: E/AndroidRuntime(4050): at luca.tirocinio.client_json.MainActivity$TaskAsincrono.doInBackground(MainActivity.java:1)
10-02 20:53:09.728: E/AndroidRuntime(4050): at android.os.AsyncTask$2.call(AsyncTask.java:288)
10-02 20:53:09.728: E/AndroidRuntime(4050): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
10-02 20:53:09.728: E/AndroidRuntime(4050): ... 4 more
10-02 20:53:13.768: I/Process(4050): Sending signal. PID: 4050 SIG: 9
You're trying to add results to ArrayList<String> risultato which is null. Just replace it with ArrayList<String> risultato = new ArrayList<String>();

controll null values in fetching json in android

i get this error in fetching json(null values):
03-21 12:32:02.918: E/AndroidRuntime(20383): FATAL EXCEPTION: AsyncTask #2
03-21 12:32:02.918: E/AndroidRuntime(20383): java.lang.RuntimeException: An error occured while executing doInBackground()
03-21 12:32:02.918: E/AndroidRuntime(20383): at android.os.AsyncTask$3.done(AsyncTask.java:299)
03-21 12:32:02.918: E/AndroidRuntime(20383): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
03-21 12:32:02.918: E/AndroidRuntime(20383): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
03-21 12:32:02.918: E/AndroidRuntime(20383): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
03-21 12:32:02.918: E/AndroidRuntime(20383): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
03-21 12:32:02.918: E/AndroidRuntime(20383): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
03-21 12:32:02.918: E/AndroidRuntime(20383): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
03-21 12:32:02.918: E/AndroidRuntime(20383): at java.lang.Thread.run(Thread.java:856)
03-21 12:32:02.918: E/AndroidRuntime(20383): Caused by: java.lang.NullPointerException
03-21 12:32:02.918: E/AndroidRuntime(20383): at Dic.proj.pkg.notifService$check_last_asyn.doInBackground(notifService.java:253)
03-21 12:32:02.918: E/AndroidRuntime(20383): at Dic.proj.pkg.notifService$check_last_asyn.doInBackground(notifService.java:1)
03-21 12:32:02.918: E/AndroidRuntime(20383): at android.os.AsyncTask$2.call(AsyncTask.java:287)
03-21 12:32:02.918: E/AndroidRuntime(20383): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
03-21 12:32:02.918: E/AndroidRuntime(20383): ... 4 more
and this is my check_last_asyn AsynTask:
// check if notification is available asyntask
class check_last_asyn extends AsyncTask<Void, Integer, Boolean> {
#Override
protected Boolean doInBackground(Void... arg0) {
if(isOnline()){
RestClient client = new RestClient(
"http://mysite.org/api/check_last.php");
client.AddParam("last", String.valueOf(last_notif_no));
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
String response = client.getResponse();
if(!response.equals(null)){
update_response = response;
}else{
update_response= "{'update':'no'}";
}
}
return true;
}
}
i know this is because of null values but i dont know how to controll null values in this code...
This should do
if(response!=null && !(response.trim()).equals("")){
update_response = response;
}else{
update_response= "{'update':'no'}";
}
the check should be something like:
if(response != null && !response.equals(""))
I think, String responce var could be null, so just add check for null value:
String responce = client.getResponce();
if (responce == null) {
// As flag, which represents, that there is no answer from service
// Or other logic
return false;
}
// your code
you may control like
if(!TextUtils.isEmpty(response)){
try {
JSONObject jobj = new JSONObject(response);
String stolan_id = null;
Boolean bstolan_id = jobj.has("keyhere");
if(bstolan_id){
stolan_id = jobj.getString("keyhere");
}
} catch (JSONException e) {
e.printStackTrace();
}
}

Error with ArrayAdapter in AsyncTask

I have the following code but I get an error on this line “userSpinner.setAdapter(adapter);”
private class Task extends AsyncTask<Void, Void, Void>
{
protected void onPreExecute() {
showDialog(DIALOG_TASKING);
}
protected Void doInBackground(Void... JSONArray) {
try
{
HttpGet request = new HttpGet(SERVICE_URI + "/GetBusNames");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
char[] buffer = new char[(int)responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
JSONObject jsonResponse = new JSONObject(new String(buffer));
JSONArray myUsers = jsonResponse.getJSONArray("GetBusNamesResult");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(RealestateActivity.this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.add("Select a Buseness...");
for (int i = 0; i < myUsers.length(); ++i)
{
adapter.add(myUsers.getString(i));
adapter.add(myUsers.getJSONObject(i).getString("BusName"));
}
userSpinner.setAdapter(adapter); // I get an error here if I wrap these two lines in /*...*/ the whole thing loads as expected but the spinner is empty
userSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
}
catch (Exception e)
{
e.printStackTrace();
displayExceptionMessage(e.getMessage());
}
return null;
}
protected void onPostExecute(Void unused) {
dismissDialog(DIALOG_TASKING);
}
}
The following is the Stack Trace produced,
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): FATAL EXCEPTION: AsyncTask #1
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): java.lang.RuntimeException: An error occured while executing doInBackground()
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at android.os.AsyncTask$3.done(AsyncTask.java:200)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at java.lang.Thread.run(Thread.java:1096)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at android.os.Handler.<init>(Handler.java:121)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at android.widget.Toast.<init>(Toast.java:68)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at android.widget.Toast.makeText(Toast.java:231)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at com.fnesse.realestate.RealestateActivity.displayExceptionMessage(RealestateActivity.java:271)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at com.fnesse.realestate.RealestateActivity$Task.doInBackground(RealestateActivity.java:131)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at com.fnesse.realestate.RealestateActivity$Task.doInBackground(RealestateActivity.java:1)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at android.os.AsyncTask$2.call(AsyncTask.java:185)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): ... 4 more
11-07 19:56:22.714: ERROR/PowerManagerService(2464): CurLock p:3 mPS:1
11-07 20:06:26.577: ERROR/libnetutils(2464): dhcp start cmd 11 : [dhcpcd:-ABK]
11-07 20:06:27.054: ERROR/HierarchicalStateMachine(2464): TetherMaster - unhandledMessage: msg.what=3
The code works in its own method but not in the AsyncTask.
Any idea’s.
Cheers,
Mike.
You can't perform Display/Update UI inside the doInBackground() method, instead either you can perform by implement runOnUIThread() method or write display/Update statement inside the onPostExecute() method.
In your case, write below statement inside the onPostExecute() and declare JSONArray myUsers at class level:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(RealestateActivity.this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.add("Select a Buseness...");
for (int i = 0; i < myUsers.length(); ++i)
{
adapter.add(myUsers.getString(i));
adapter.add(myUsers.getJSONObject(i).getString("BusName"));
}
userSpinner.setAdapter(adapter); // I get an error here if I wrap these two lines in /*...*/ the whole thing loads as expected but the spinner is empty
userSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
}
catch (Exception e)
{
e.printStackTrace();
displayExceptionMessage(e.getMessage());
}
Final Solution:
private class Task extends AsyncTask<Void, Void, Void>
{
JSONArray myUsers = null;
JSONObject jsonResponse = null; // this is also needed at class level
protected void onPreExecute() {
showDialog(DIALOG_TASKING);
}
protected Void doInBackground(Void... JSONArray) {
try
{
HttpGet request = new HttpGet(SERVICE_URI + "/GetBusNames");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
char[] buffer = new char[(int)responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
jsonResponse = new JSONObject(new String(buffer));
}
catch (Exception e)
{
e.printStackTrace();
displayExceptionMessage(e.getMessage());
}
return null;
}
protected void onPostExecute(Void unused) {
dismissDialog(DIALOG_TASKING);
myUsers = jsonResponse.getJSONArray("GetBusNamesResult");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(RealestateActivity.this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.add("Select a Buseness...");
for (int i = 0; i < myUsers.length(); ++i)
{
adapter.add(myUsers.getString(i));
adapter.add(myUsers.getJSONObject(i).getString("BusName"));
}
userSpinner.setAdapter(adapter); // I get an error here if I wrap these two lines in /*...*/ the whole thing loads as expected but the spinner is empty
userSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
}
Use below code inside your onPostExecute method.
userSpinner.setAdapter(adapter);
userSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
Try this it may help you..
you need to move all the UI manipulation into postExecute method which is executed in the main app thread. Android UI is not thread safe.
Don't do UI related tasks in doInBackground(). Collect your data in doInBackground() and return i from there. Get your data as a parameter to onPostExecute() and issue your userSpinner.* calls there.

Categories

Resources