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>();
Related
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).
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'
...
}
I make an android application on movies. I have a database movies. In the application I display the movies in ListView and I add a new movie.
I have a problem when I try to insert in my dataBase a new movie. Indeed, I have n error in my AsyncTask in the doInBackground but I don't know why. When I use the debugger, I have reject on the begin of the doInBackground at the line :
String title = eTitle.getText().toString();
So I give you my java code :
public class AddMovie extends Activity implements OnClickListener{
// Edit and Button that the user fill
private EditText eTitle, eActors, eDirector, eKind, eDate, eImage, eSummary ;
private Button bAdd;
// Progress Dialog
private ProgressDialog pDialog;
//JSON parser class
//JSONParser jsonParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_movie);
eTitle = (EditText)findViewById(R.id.title);
eActors = (EditText)findViewById(R.id.actors);
eDirector = (EditText)findViewById(R.id.director);
eKind = (EditText)findViewById(R.id.kind);
eDate = (EditText)findViewById(R.id.date);
eImage = (EditText)findViewById(R.id.image);
eSummary = (EditText)findViewById(R.id.summary);
bAdd = (Button)findViewById(R.id.addMovies);
bAdd.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.addMovies:
new AttempMovie().execute();
// here we have used, switch case, because on login activity you may //also want to show registration button, so if the user is new ! we can go the //registration activity , other than this we could also do this without switch //case.
default:
break;
}
}
class AttempMovie extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddMovie.this);
pDialog.setMessage("Attempting for add new movie...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
int success;
String title = eTitle.getText().toString();
String actors = eActors.getText().toString();
String director = eDirector.getText().toString();
String kind = eKind.getText().toString();
String date = eDate.getText().toString();
String image = eImage.getText().toString();
String summary = eSummary.getText().toString();
try {
// Building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("title", title));
params.add(new BasicNameValuePair("actors", actors));
params.add(new BasicNameValuePair("director", director));
params.add(new BasicNameValuePair("kind", kind));
params.add(new BasicNameValuePair("date", date));
params.add(new BasicNameValuePair("image", image));
params.add(new BasicNameValuePair("summary", summary));
Log.d("request!", "starting");
JSONObject json = JSONfunctions.getJSONfromURL("http://10.0.0.35/BD_Enterprise_Mobility_Movies/add_movie.php");
// checking log for json response
Log.d("Register attempt", json.toString());
// success tag for json
success = json.getInt(TAG_SUCCESS);
if (success == 1)
{
Log.d("Successfully Register!", json.toString());
return json.getString(TAG_MESSAGE);
}
else
{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* Once the background process is done we need to Dismiss the progress dialog asap
* **/
protected void onPostExecute(String message) {
pDialog.dismiss();
if (message != null){
Intent i = new Intent(AddMovie.this,MainActivity.class);
finish();
// this finish() method is used to tell android os that we are done with current //activity now! Moving to other activity
startActivity(i);
Toast.makeText(AddMovie.this, message, Toast.LENGTH_LONG).show();
}
}
}
}
I give you also my JSONfunctions.java
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject json = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
json = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return json;
}
}
And my error in the logcat:
03-20 18:28:19.753: E/AndroidRuntime(14656): FATAL EXCEPTION: AsyncTask #3
03-20 18:28:19.753: E/AndroidRuntime(14656): Process: com.mickKoza.jsonkoza, PID: 14656
03-20 18:28:19.753: E/AndroidRuntime(14656): java.lang.RuntimeException: An error occured while executing doInBackground()
03-20 18:28:19.753: E/AndroidRuntime(14656): at android.os.AsyncTask$3.done(AsyncTask.java:300)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
03-20 18:28:19.753: E/AndroidRuntime(14656): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.lang.Thread.run(Thread.java:818)
03-20 18:28:19.753: E/AndroidRuntime(14656): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
03-20 18:28:19.753: E/AndroidRuntime(14656): at com.mickKoza.jsonkoza.AddMovie$AttempMovie.doInBackground(AddMovie.java:81)
03-20 18:28:19.753: E/AndroidRuntime(14656): at com.mickKoza.jsonkoza.AddMovie$AttempMovie.doInBackground(AddMovie.java:1)
03-20 18:28:19.753: E/AndroidRuntime(14656): at android.os.AsyncTask$2.call(AsyncTask.java:288)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-20 18:28:19.753: E/AndroidRuntime(14656): ... 4 more
03-20 18:28:20.184: E/WindowManager(14656): android.view.WindowLeaked: Activity com.mickKoza.jsonkoza.AddMovie has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{3e1b7378 V.E..... R......D 0,0-1026,288} that was originally added here
03-20 18:28:20.184: E/WindowManager(14656): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
03-20 18:28:20.184: E/WindowManager(14656): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
03-20 18:28:20.184: E/WindowManager(14656): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
03-20 18:28:20.184: E/WindowManager(14656): at android.app.Dialog.show(Dialog.java:298)
03-20 18:28:20.184: E/WindowManager(14656): at com.mickKoza.jsonkoza.AddMovie$AttempMovie.onPreExecute(AddMovie.java:74)
03-20 18:28:20.184: E/WindowManager(14656): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
03-20 18:28:20.184: E/WindowManager(14656): at android.os.AsyncTask.execute(AsyncTask.java:535)
03-20 18:28:20.184: E/WindowManager(14656): at com.mickKoza.jsonkoza.AddMovie.onClick(AddMovie.java:54)
03-20 18:28:20.184: E/WindowManager(14656): at android.view.View.performClick(View.java:4756)
03-20 18:28:20.184: E/WindowManager(14656): at android.view.View$PerformClick.run(View.java:19749)
03-20 18:28:20.184: E/WindowManager(14656): at android.os.Handler.handleCallback(Handler.java:739)
03-20 18:28:20.184: E/WindowManager(14656): at android.os.Handler.dispatchMessage(Handler.java:95)
03-20 18:28:20.184: E/WindowManager(14656): at android.os.Looper.loop(Looper.java:135)
03-20 18:28:20.184: E/WindowManager(14656): at android.app.ActivityThread.main(ActivityThread.java:5221)
03-20 18:28:20.184: E/WindowManager(14656): at java.lang.reflect.Method.invoke(Native Method)
03-20 18:28:20.184: E/WindowManager(14656): at java.lang.reflect.Method.invoke(Method.java:372)
03-20 18:28:20.184: E/WindowManager(14656): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
03-20 18:28:20.184: E/WindowManager(14656): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Thank you for your help
Michaël
One (or possibly all) of these views is null:
String title = eTitle.getText().toString();
String actors = eActors.getText().toString();
String director = eDirector.getText().toString();
String kind = eKind.getText().toString();
String date = eDate.getText().toString();
String image = eImage.getText().toString();
String summary = eSummary.getText().toString();
Possibly the view IDs that you're referencing during onCreate to find these views are not correct?
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.
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();
}
}