Error executing a function in a AsyncTask doInBackground JsonParser/PHP - java

Ok, i find a lot of people with the same problem but i was not able to find a good answer yet.
I im doing a simple httprequest with JSON parser, but im getting this error:
12-13 17:11:35.406: E/AndroidRuntime(28346): FATAL EXCEPTION: AsyncTask #1
12-13 17:11:35.406: E/AndroidRuntime(28346): java.lang.RuntimeException: An error occured while executing doInBackground()
12-13 17:11:35.406: E/AndroidRuntime(28346): at android.os.AsyncTask$3.done(AsyncTask.java:278)
I am really lost. Anyone have an answer?
here is my code:
Java: Main Ac.
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Vector;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.exemple.beans.MesaBean;
import com.exemple.json.JSONParser;
public class MainActivity extends Activity {
public static final String ESTABELECIMENTO = "NossoBar";
JSONParser jsonParser = new JSONParser();
EditText numeroMesa;
private ProgressDialog pDialog;
Button criar;
private static String url_create_product = "http://www.naga.net.br/android/beerapp/delete_product.php";
private static final String TAG_SUCCESS = "success";
public static Vector<MesaBean> mesas;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
criar = (Button) findViewById(R.id.btncriar);
numeroMesa = (EditText) findViewById(R.id.numeroMesa);
if (mesas == null) {
mesas = new Vector<MesaBean>();
}
criar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int numero = Integer.valueOf(numeroMesa.getText().toString());
String senha = gerarsenha();
int id = mesas.size()+1;
String currentDateTimeString = DateFormat
.getDateTimeInstance().format(new Date());
MesaBean mb = new MesaBean();
mb.setCriadoEm(currentDateTimeString);
mb.setIdmesa(id);
mb.setSenha(senha);
mb.setMesa(numero);
mesas.add(mb);
String resp = ESTABELECIMENTO+numero+senha;
new CreateNewProduct(resp).execute();
}
});
}
class CreateNewProduct extends AsyncTask<String, String, String> {
String resp;
CreateNewProduct() {
}
public CreateNewProduct(String resp) {
this.resp = resp;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Postando comparação...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
// getting JSON Object
try {
// Note that create product url accepts POST method
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("mesaconta", resp));
params.add(new BasicNameValuePair("lalal", "lalal"));
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
resp = "Sucess";
} else {
resp = "Fail";
}
} catch (JSONException e) {
startActivity(new Intent(getApplicationContext(),
MainActivity.class));
}
if (resp.equalsIgnoreCase("Sucess")) {
// closing this screen
startActivity(new Intent(getApplicationContext(),
ListaMesas.class));
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
private String gerarsenha() {
int min = 0;
int max = 9;
Random r = new Random();
Integer a = r.nextInt(max - min + 1) + min;
Integer b = r.nextInt(max - min + 1) + min;
Integer c = r.nextInt(max - min + 1) + min;
Integer d = r.nextInt(max - min + 1) + min;
Integer e = r.nextInt(max - min + 1) + min;
Integer f = r.nextInt(max - min + 1) + min;
String resp = a.toString() + b.toString() + c.toString() + d.toString()
+ e.toString() + f.toString();
return resp;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
JsonParser:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
The code in PHP on the server allready works fine, im using it in another program.
Can you help me?
Full tracktrace:
12-13 18:03:06.516: E/JSON Parser(31184): Error parsing data org.json.JSONException: End of input at character 1 of
12-13 18:03:06.516: W/dalvikvm(31184): threadid=11: thread exiting with uncaught exception (group=0x41a0b6f0)
12-13 18:03:06.546: E/AndroidRuntime(31184): FATAL EXCEPTION: AsyncTask #1
12-13 18:03:06.546: E/AndroidRuntime(31184): java.lang.RuntimeException: An error occured while executing doInBackground()
12-13 18:03:06.546: E/AndroidRuntime(31184): at android.os.AsyncTask$3.done(AsyncTask.java:278)
12-13 18:03:06.546: E/AndroidRuntime(31184): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
12-13 18:03:06.546: E/AndroidRuntime(31184): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
12-13 18:03:06.546: E/AndroidRuntime(31184): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
12-13 18:03:06.546: E/AndroidRuntime(31184): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
12-13 18:03:06.546: E/AndroidRuntime(31184): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
12-13 18:03:06.546: E/AndroidRuntime(31184): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
12-13 18:03:06.546: E/AndroidRuntime(31184): at java.lang.Thread.run(Thread.java:856)
12-13 18:03:06.546: E/AndroidRuntime(31184): Caused by: java.lang.NullPointerException
12-13 18:03:06.546: E/AndroidRuntime(31184): at com.example.gerente2.MainActivity$CreateNewProduct.doInBackground(MainActivity.java:117)
12-13 18:03:06.546: E/AndroidRuntime(31184): at com.example.gerente2.MainActivity$CreateNewProduct.doInBackground(MainActivity.java:1)
12-13 18:03:06.546: E/AndroidRuntime(31184): at android.os.AsyncTask$2.call(AsyncTask.java:264)
12-13 18:03:06.546: E/AndroidRuntime(31184): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
12-13 18:03:06.546: E/AndroidRuntime(31184): ... 4 more
12-13 18:03:07.306: W/IMGSRV(31184): :0: gralloc_unregister_buffer: ID: 3355 handle: 0x866bf70 size: 540 x 888 fmt: 2 usage: 0x933
12-13 18:03:07.306: W/IMGSRV(31184): :0: gralloc_unregister_buffer: ID: 3356 handle: 0x86bfa60 size: 540 x 888 fmt: 2 usage: 0x933
12-13 18:03:07.316: W/IMGSRV(31184): :0: gralloc_unregister_buffer: ID: 3359 handle: 0x8649a10 size: 392 x 175 fmt: 1 usage: 0x933
12-13 18:03:07.316: W/IMGSRV(31184): :0: gralloc_unregister_buffer: ID: 3360 handle: 0x8669800 size: 392 x 175 fmt: 1 usage: 0x933
12-13 18:03:08.006: E/WindowManager(31184): Activity com.example.gerente2.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#211b52a0 that was originally added here
12-13 18:03:08.006: E/WindowManager(31184): android.view.WindowLeaked: Activity com.example.gerente2.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#211b52a0 that was originally added here
12-13 18:03:08.006: E/WindowManager(31184): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:356)
12-13 18:03:08.006: E/WindowManager(31184): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:267)
12-13 18:03:08.006: E/WindowManager(31184): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:215)
12-13 18:03:08.006: E/WindowManager(31184): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:140)
12-13 18:03:08.006: E/WindowManager(31184): at android.view.Window$LocalWindowManager.addView(Window.java:537)
12-13 18:03:08.006: E/WindowManager(31184): at android.app.Dialog.show(Dialog.java:284)
12-13 18:03:08.006: E/WindowManager(31184): at com.example.gerente2.MainActivity$CreateNewProduct.onPreExecute(MainActivity.java:99)
12-13 18:03:08.006: E/WindowManager(31184): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:561)
12-13 18:03:08.006: E/WindowManager(31184): at android.os.AsyncTask.execute(AsyncTask.java:511)
12-13 18:03:08.006: E/WindowManager(31184): at com.example.gerente2.MainActivity$1.onClick(MainActivity.java:70)
12-13 18:03:08.006: E/WindowManager(31184): at android.view.View.performClick(View.java:3531)
12-13 18:03:08.006: E/WindowManager(31184): at android.view.View$PerformClick.run(View.java:14224)
12-13 18:03:08.006: E/WindowManager(31184): at android.os.Handler.handleCallback(Handler.java:605)
12-13 18:03:08.006: E/WindowManager(31184): at android.os.Handler.dispatchMessage(Handler.java:92)
12-13 18:03:08.006: E/WindowManager(31184): at android.os.Looper.loop(Looper.java:137)
12-13 18:03:08.006: E/WindowManager(31184): at android.app.ActivityThread.main(ActivityThread.java:4699)
12-13 18:03:08.006: E/WindowManager(31184): at java.lang.reflect.Method.invokeNative(Native Method)
12-13 18:03:08.006: E/WindowManager(31184): at java.lang.reflect.Method.invoke(Method.java:511)
12-13 18:03:08.006: E/WindowManager(31184): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
12-13 18:03:08.006: E/WindowManager(31184): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
12-13 18:03:08.006: E/WindowManager(31184): at dalvik.system.NativeStart.main(Native Method)

Have you checked the string that you are receiving back from that server? The
Error parsing data org.json.JSONException: End of input at character 1
Means you're getting an empty response back from the server.

Related

Value Unknown of type java.lang.String cannot be converted to JSONObject [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
im tryin to make an app and connect it to my database(MySQL wamp) . i have made my php files and this is the NewProductActivity.java file that's giving errors.I have made a sample to do so. I have got the code from here
package com.example.abc.androidhive;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class NewProductActivity extends Activity {
// Progress Dialog
-private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputDesc;
// url to create new product
private static String url_create_product = "http://api.androidhive.info/android_connect/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);
// Edit Text
inputName = (EditText) findViewById(R.id.inputName);
inputPrice = (EditText) findViewById(R.id.inputPrice);
inputDesc = (EditText) findViewById(R.id.inputDesc);
// Create button
Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String price = inputPrice.getText().toString();
String description = inputDesc.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("description", description));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
the part giving errors is:
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String price = inputPrice.getText().toString();
String description = inputDesc.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("description", description));
My Logcat is:
03-03 04:06:10.552 1944-1967/? E/JSON Parser: Error parsing data org.json.JSONException: Value Unknown of type java.lang.String cannot be converted to JSONObject
03-03 04:06:10.552 1944-1967/? W/dalvikvm: threadid=15: thread exiting with uncaught exception (group=0xb17d3678)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #5
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: java.lang.RuntimeException: An error occured while executing doInBackground()
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at android.os.AsyncTask$3.done(AsyncTask.java:299)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:239)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at java.lang.Thread.run(Thread.java:841)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: Caused by: java.lang.NullPointerException
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at com.example.abc.androidhive.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:100)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at com.example.abc.androidhive.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:64)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at android.os.AsyncTask$2.call(AsyncTask.java:287)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:234)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at java.lang.Thread.run(Thread.java:841) 
Please suggest me of possible rectifications.
The problem is that what your server returns it's not a valid json. You should check what is the response of this call
I tried with casual params (name = a, price = b, description = c) and the server returns
Unknown database 'download_androidhive'
This is a string and 99% is the reason of your issue.
It's not because of this class, It is the error of your JSONParser class where these lines were written
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
I want to suggest you that it doesn't seems a single JsonObject at all. So just try replacing this line
jObj = new JSONObject(json);
with
JSONArray jsonArray = new JSONArray(json);
JSONObject jObj = jsonArray.getJSONObject(0);

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).

Android HttpClient Two different httpposts not working?

I have the following code.
I want to post on the first time the user press a button that the data will be send to httpclient and will return data. This works fine (Button 1). When a user press button 1 it will give the right results.
Then I want to post a second time with different data to the httpclient. When a user press button 2. The data will be send to the function but the logs (see code) returns in the exceptions every time NULL. So I think it will not send to httpclient and will not fill the httppost with the data I want to send.
My question is, what do I wrong or do I forget?
Do I need to create a second httpclient handler?
Do I need to create a second httppost handler?
Please help.
Thank you.
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import info.androidhive.customlistviewvolley.util.MyHttpClient;
public class Login extends Activity {
HttpPost httppost;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
ProgressDialog offlineDialog = null;
String logged, token, valid;
String expired = "expired";
String status, responseContent = "0";
String msg = "";
public void onCreate(Bundle savedInstanceState) {
httpclient=new MyHttpClient(getApplicationContext());
httppost= new HttpPost("https://www.test.com/json/index.php");
b = (Button)findViewById(R.id.buttonLogin);
c = (Button)findViewById(R.id.shareData);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(Login.this, "","Validating user...", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
});
String username = 'abc';
String password = 'xxx';
String token = '12321abcksadkm';
c.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
offlineDialog = ProgressDialog.show(Login.this, "", "Share content...", true);
new Thread(new Runnable() {
public void run() {
// This will be executed but will give NULL and offcourse no results
share.connectDP(username,password,"share","18228",token);
}
}).start();
}
});
}
void login(){
try{
final byte[] SALT;
Random random = new Random();
random.setSeed(System.currentTimeMillis());
byte[] buf = new byte[20];
random.nextBytes(buf);
SALT = buf;
nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("token",SALT.toString().trim()));
Log.i("Salt", "Key =" + SALT.toString().trim());
Log.i("test", "test" + nameValuePairs);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
String responseContent = EntityUtils.toString(response.getEntity());
//Log.d("Response", responseContent );
JSONObject jsonObject = new JSONObject(responseContent);
JSONArray jArray = jsonObject.getJSONArray("result");
for (int i = 0; i < jArray.length(); i++) {
try {
JSONObject json_data = jArray.getJSONObject(i);
logged = json_data.getString("status"); // obtain status
token = json_data.getString("token"); // obtain token
valid = json_data.getString("valid"); // obtain validation period
expired = "no";
Log.i("Logged JSON", "Result?" + json_data.getString("status"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void connectDP(String username, String password, String action, String id, String token){
// This is passed, it returns the data = :)
Log.i("connect", "username" + username);
Log.i("connect", "password" + password);
Log.i("connect", "action" + action);
Log.i("connect", "id" + id);
Log.i("connect", "token" + token);
try{
final byte[] SALT;
Random random = new Random();
random.setSeed(System.currentTimeMillis());
byte[] buf = new byte[20];
random.nextBytes(buf);
SALT = buf;
nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("username",username.toString().trim()));
nameValuePairs.add(new BasicNameValuePair("password",password.toString().trim()));
nameValuePairs.add(new BasicNameValuePair("token",SALT.toString().trim()));
Log.i("Salt", "Key =" + SALT.toString().trim());
Log.i("test", "test" + nameValuePairs);
//// <!---- After here it will break, but no any error or warning -----!>
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
String responseContent = EntityUtils.toString(response.getEntity());
//Log.d("Response", responseContent );
JSONObject jsonObject = new JSONObject(responseContent);
JSONArray jArray = jsonObject.getJSONArray("result");
for (int i = 0; i < jArray.length(); i++) {
try {
JSONObject json_data = jArray.getJSONObject(i);
logged = json_data.getString("status"); // obtain status
token = json_data.getString("token"); // obtain token
valid = json_data.getString("valid"); // obtain validation period
expired = "no";
Log.i("Logged JSON", "Result?" + json_data.getString("status"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
}
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/connect﹕ usernameabc
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/connect﹕ passwordxxx
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/connect﹕ actionshare
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/connect﹕ id18228
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/connect﹕ token12321abcksadkm
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/test 1﹕ test[username=abc, password=xxx, requestAction=share, requestFile=18228, load_remote_token=12321abcksadkm
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 1a﹕ testnull
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 2﹕ testnull
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 2a﹕ testnull
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 3﹕ testnull
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 4﹕ testnull
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 4a﹕ testnull
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 5﹕ 0
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/System.out﹕ Exception : Value 0 of type java.lang.Integer cannot be converted to JSONObject
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/Log share﹕ [ 04-03 19:33:25.390 169:0x204 W/InputManagerService ]
Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#4156a2c8
package info.androidhive.customlistviewvolley.util;
import android.content.Context;
import info.androidhive.customlistviewvolley.R;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import java.io.InputStream;
import java.security.KeyStore;
import org.apache.http.conn.ssl.SSLSocketFactory;
public class MyHttpClient extends DefaultHttpClient {
final Context _context;
public MyHttpClient(Context context) {
this._context = context;
}
#Override
protected ClientConnectionManager createClientConnectionManager() {
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
// Register for port 443 our SSLSocketFactory with our keystore
// to the ConnectionManager
registry.register(new Scheme("https", (org.apache.http.conn.scheme.SocketFactory) newSslSocketFactory(), 443));
return new SingleClientConnManager(getParams(), registry);
}
private SSLSocketFactory newSslSocketFactory() {
try {
// Get an instance of the Bouncy Castle KeyStore format
KeyStore trusted = KeyStore.getInstance("BKS");
// Get the raw resource, which contains the keystore with
// your trusted certificates (root and any intermediate certs)
InputStream in = _context.getResources().openRawResource(R.raw.keystore);
try {
// Initialize the keystore with the provided trusted certificates
// Also provide the password of the keystore
trusted.load(in, "xxxxxxxx".toCharArray());
} finally {
in.close();
}
// Pass the keystore to the SSLSocketFactory. The factory is responsible
// for the verification of the server certificate.
SSLSocketFactory sf = new SSLSocketFactory(trusted);
// Hostname verification from certificate
// http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
return sf;
} catch (Exception e) {
throw new AssertionError(e);
}
}
}
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ java.lang.NullPointerException
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at info.androidhive.customlistviewvolley.Login.connectDP(Login.java:247)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at info.androidhive.customlistviewvolley.adater.CustomGridOfflineMedia$2.onClick(CustomGridOfflineMedia.java:200)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.view.View.performClick(View.java:3511)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.view.View$PerformClick.run(View.java:14110)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:605)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:92)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.os.Looper.loop(Looper.java:137)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:4424)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:511)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
i hope somebody more qualified will answer your question soon, until then something to maybe look into:
HttpPost.reset inherited from AbstractExecutionAwareRequest
says in the docs:
"Resets internal state of the request making it reusable."
making me think that maybe if you do not reset the httppost object it isn't reusable...
src: http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/methods/AbstractExecutionAwareRequest.html#reset()
According to the logcat, your API doesnt response a valid JSON format.
It must be "response" : "0" or something liek that instead of plain 0.
I suggest you to check the server side code for connectDB function and what it returns.
This has been solved by changing some code.

Choose activity dynamically during splashscreen

I'm doing a small project, and today I had to make a conditional validation in splashscreen. The project was practically finalized when we decided to do this validation in splashscreen.
Modified my class and was working ok, but I had to include the time for the splash disappears (variable SPLASH_TIME_OUT) and started giving an error that I do not understand.
My splashscreen clas (now) is:
package com.clubee.vote;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Splashscreen extends Activity {
// Splash screen timer
private static String url_Pesquisa_voto = "http://dev.clubee.com.br/dbvote/PesquisaVoto.php";
JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
private static final String TAG_SUCCESS = "success";
public String retrieveMacAddress(Context context) {
WifiManager wfman = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String macAddress = wfman.getConnectionInfo().getMacAddress();
if (macAddress == null) {
macAddress = "Dispositivo sem endereço mac address ou wi-fi desabilitado";
}
return macAddress;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new PesquisaVoto().execute();
}
class PesquisaVoto extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Splashscreen.this);
pDialog.setMessage("Pesquisando Voto..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
int SPLASH_TIME_OUT = 2000;
WifiManager wfman = (WifiManager) getSystemService(Context.WIFI_SERVICE);
String macAddress = wfman.getConnectionInfo().getMacAddress();
if (macAddress == null) {
macAddress = "Dispositivo sem endereço mac";
}
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("macAddress", macAddress));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_Pesquisa_voto, "GET", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
new Handler().postDelayed(new Runnable() {
public void run() {
Intent i = new Intent(Splashscreen.this, ResultadoFalho.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
} else {
new Handler().postDelayed(new Runnable() {
public void run() {
Intent i = new Intent(Splashscreen.this, MainActivity.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
}
The error I am getting is:
03-03 17:38:49.882 10432-10450/com.clubee.vote D/Create Response﹕ {"voto":[{"count":"1"}],"success":1}
03-03 17:38:49.882 10432-10450/com.clubee.vote W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x4164dd88)
03-03 17:38:49.892 10432-10450/com.clubee.vote E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.clubee.vote, PID: 10432
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done
Anyone knows what I did wrong? Is it possivel to implement the Runnable inside the IF statement? If I do not put the timeout variable, everything is right.
UPDATE THE LOG WITH ERROR
03-03 22:01:50.016 18731-18746/com.clubee.vote W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x4164dd88)
03-03 22:01:50.026 18731-18746/com.clubee.vote E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.clubee.vote, PID: 18731
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.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.(Handler.java:200)
at android.os.Handler.(Handler.java:114)
at com.clubee.vote.Splashscreen$PesquisaVoto.doInBackground(Splashscreen.java:87)
at com.clubee.vote.Splashscreen$PesquisaVoto.doInBackground(Splashscreen.java:48)
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)
03-03 22:01:50.697 18731-18731/com.clubee.vote E/WindowManager﹕ android.view.WindowLeaked: Activity com.clubee.vote.Splashscreen has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{44aa2458 V.E..... R......D 0,0-681,345} that was originally added here
at android.view.ViewRootImpl.(ViewRootImpl.java:350)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:294)
at com.clubee.vote.Splashscreen$PesquisaVoto.onPreExecute(Splashscreen.java:58)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.clubee.vote.Splashscreen.onCreate(Splashscreen.java:44)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2201)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:212)
at android.app.ActivityThread.main(ActivityThread.java:5135)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
at dalvik.system.NativeStart.main(Native Method)
03-03 22:01:52.529 18731-18746/com.clubee.vote I/Process﹕ Sending signal. PID: 18731 SIG: 9
Tks in advance for answers and comments. I corrected my code, re-wrote and re-structured it, became easier to see where the mistakes were.
below, I leave the code that is working for future research. thank you very much
package com.clubee.vote;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Splashscreen extends Activity {
// Splash screen timer
private static String url_Pesquisa_voto = "http://dev.clubee.com.br/dbvote/PesquisaVoto.php";
JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
private static final String TAG_SUCCESS = "success";
private static int SPLASH_TIME_OUT = 2000;
public String retrieveMacAddress(Context context) {
WifiManager wfman = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String macAddress = wfman.getConnectionInfo().getMacAddress();
if (macAddress == null) {
macAddress = "Dispositivo sem endereço mac address ou wi-fi desabilitado";
}
return macAddress;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
new PesquisaVoto().execute();
}
}, SPLASH_TIME_OUT);
}
class PesquisaVoto extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Splashscreen.this);
pDialog.setMessage("Pesquisando Voto..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
WifiManager wfman = (WifiManager) getSystemService(Context.WIFI_SERVICE);
String macAddress = wfman.getConnectionInfo().getMacAddress();
if (macAddress == null) {
macAddress = "Dispositivo sem endereço mac";
}
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("macAddress", macAddress));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_Pesquisa_voto, "GET", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Intent i = new Intent(Splashscreen.this, ResultadoFalho.class);
startActivity(i);
}
else {
Intent i = new Intent(Splashscreen.this, MainActivity.class);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
}
I cannot clearly see what is wrong based on the Logs you provided but there is something wrong with your structure.
You are starting an Activity within doInBackground Process and then dismissing the Progress Dialog which belongs to the Activity that you just finished.
Try to pass a parameter to the onPostExecute and then finish your Activity there.
And post some more details from your Log to make it clear. There has to be some more logs indicating what went wrong.

Android unable to add getByName

I'm trying to add getByName to get the IP address of a hostname and use it in my POST command
the problem is wherever i insert this code it crashes
i tried to insert in doInBackground it also crashes So where should i insert it ??
package com.example.loginad;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Logindb extends Activity {
Button login;
EditText u,p;
TextView res;
String result;
String x="mobile";
String host;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.logindb);
login=(Button)findViewById(R.id.login);
u=(EditText)findViewById(R.id.u);
p=(EditText)findViewById(R.id.p);
res=(TextView)findViewById(R.id.res);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new MyAsyncTask().execute(u.getText().toString(),p.getText().toString());
}
});
}
private class MyAsyncTask extends AsyncTask<String, Integer, Boolean>{
#Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
boolean success = postData(params[0],params[1]);
try
{
InetAddress address=null;
address = InetAddress.getByName("Nicky-PC");
host=address.getHostAddress();
}
catch(Exception e)
{
e.printStackTrace();
}
return success;
}
protected void onPostExecute(Boolean localres){
if (localres){
res.setText("A Correct Username and Password");
}else{
res.setText("Incorrect Username or Password");
}
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Integer... progress){
//pb.setProgress(progress[0]);
//Toast.makeText(getApplicationContext(), "Done", Toast.LENGTH_LONG).show();
}
/*public void ObtainHost()
{
try
{
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
} */
public Boolean postData(String a,String b) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", a));
postParameters.add(new BasicNameValuePair("password", b));
postParameters.add(new BasicNameValuePair("mobileid",x));
// String valid = "1";
String response = null;
try {
// Toast.makeText(getApplicationContext(), host.toString(), Toast.LENGTH_LONG).show();
response = CustomHttpClient.executeHttpPost("http://"+host+"/new/check.php",postParameters);
//now in result you will have the response from php file either 0 or 1.
result = response.toString();
// res = res.trim();
result = result.replaceAll("\\s+", "");
// error.setText(res);
} catch (Exception e) {
res.setText(e.toString());
}
return result.equals("1");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.logindb, menu);
return true;
}
}
Stacktrace
11-26 21:28:37.856: D/libEGL(17150): loaded /system/lib/egl/libEGL_genymotion.so
11-26 21:28:37.876: D/(17150): HostConnection::get() New Host Connection established 0xb8ed35a8, tid 17150
11-26 21:28:37.900: D/libEGL(17150): loaded /system/lib/egl/libGLESv1_CM_genymotion.so
11-26 21:28:37.900: D/libEGL(17150): loaded /system/lib/egl/libGLESv2_genymotion.so
11-26 21:28:37.968: W/EGL_genymotion(17150): eglSurfaceAttrib not implemented
11-26 21:28:37.976: E/OpenGLRenderer(17150): Getting MAX_TEXTURE_SIZE from GradienCache
11-26 21:28:37.996: E/OpenGLRenderer(17150): Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
11-26 21:28:37.996: D/OpenGLRenderer(17150): Enabling debug mode 0
11-26 21:28:44.876: W/dalvikvm(17150): threadid=13: thread exiting with uncaught exception (group=0xa4c1f648)
11-26 21:28:44.920: E/AndroidRuntime(17150): FATAL EXCEPTION: AsyncTask #3
11-26 21:28:44.920: E/AndroidRuntime(17150): java.lang.RuntimeException: An error occured while executing doInBackground()
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.lang.Thread.run(Thread.java:841)
11-26 21:28:44.920: E/AndroidRuntime(17150): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:5908)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:837)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:358)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.widget.TextView.checkForRelayout(TextView.java:6524)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.widget.TextView.setText(TextView.java:3771)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.widget.TextView.setText(TextView.java:3629)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.widget.TextView.setText(TextView.java:3604)
11-26 21:28:44.920: E/AndroidRuntime(17150): at com.example.loginad.Logindb$MyAsyncTask.postData(Logindb.java:130)
11-26 21:28:44.920: E/AndroidRuntime(17150): at com.example.loginad.Logindb$MyAsyncTask.doInBackground(Logindb.java:70)
11-26 21:28:44.920: E/AndroidRuntime(17150): at com.example.loginad.Logindb$MyAsyncTask.doInBackground(Logindb.java:1)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-26 21:28:44.920: E/AndroidRuntime(17150): ... 4 more
11-26 21:28:44.932: D/dalvikvm(17150): GC_FOR_ALLOC freed 259K, 5% free 6365K/6660K, paused 8ms, total 8ms
First if you will use AsyncHttpClient then you do not need AsyncTask but if you will use HttpClient then you need AsyncTask task.
the below code is part from working code to execute get and post requests. Modify it as your need
#Override
protected String doInBackground(String... params) {
backGroundExecuted = false;
Log.d("doInBackground", "Start processing doInBackground");
HttpClient httpClient = null;
HttpPost httpPost = null;
HttpGet httpGet = null;
if (httpMethodType == null || url == null) {
Log.d("doInBackground" , "The URL and Method Type is mandatory, cannot be null - httpMethodType =" + httpMethodType + " and url =" + url);
this.getApiResponse().setSuccess(false);
this.getApiResponse().setResponseCode(HttpResponseCode.BAD_REQUEST);
this.getApiResponse().setResponseDescription("The URL and Method Type is mandatory, cannot be null");
return null;
}
try {
//set timeout
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, TIME_OUT);
HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIME_OUT);
httpClient = new DefaultHttpClient(httpParameters);
HttpResponse httpResponse = null;
if (httpMethodType.equals(HTTPMethodType.POST.toString())) {
httpPost = new HttpPost(url);
//setting json object to request.
if (postParams != null) {
AbstractHttpEntity entity = null;
entity = new ByteArrayEntity(postParams.getBytes("UTF8"));
if (httpContentType != null) {
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, httpContentType));
}
httpPost.setEntity(entity);
}
httpResponse = httpClient.execute(httpPost);
} else if (httpMethodType.equals(HTTPMethodType.GET.toString()) || httpMethodType.equals(HTTPMethodType.PUT.toString())) {
if (queryParams != null) {
url = url + "?" + URLEncodedUtils.format(queryParams, "utf-8");
Log.d(TAG ,"new URL :" + url);
}
httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
this.getApiResponse().setResponseCode(httpResponse.getStatusLine().getStatusCode());
this.getApiResponse().setResponseDescription(httpResponse.getStatusLine().getReasonPhrase());
if (this.getApiResponse().getResponseCode() != HttpStatus.SC_OK) {
this.getApiResponse().setSuccess(false);
Log.w(getClass().getSimpleName(),
"Error " + this.getApiResponse().getResponseCode() + " for URL " + url);
Log.w(getClass().getSimpleName(),
"Error " + this.getApiResponse().getResponseDescription() + " for URL " + url);
}
Log.d("doInBackground", "The API call executed and will check the response");
HttpEntity entityResp = httpResponse.getEntity();
if (entityResp != null) {
this.getApiResponse().setResponse(appHelper.getStringFromInputStream(entityResp.getContent()));
Log.d("doInBackground","The response is :" + this.getApiResponse().getResponse());
this.getApiResponse().setSuccess(true);
}
} catch (UnsupportedEncodingException e1) {
Log.e("doInBackground","Exception :" + e1.toString());
this.getApiResponse().setSuccess(false);
this.getApiResponse().setResponseCode(HttpResponseCode.BAD_REQUEST);
this.getApiResponse().setResponseDescription("Exception :" + e1.toString());
Log.e("doInBackground","Exception :" + e1.toString());
e1.printStackTrace();
} catch (Exception e) {
Log.e("doInBackground","Exception :" + e.toString());
this.getApiResponse().setSuccess(false);
this.getApiResponse().setResponseCode(HttpResponseCode.BAD_REQUEST);
this.getApiResponse().setResponseDescription("Exception :" + e.toString());
if (httpPost != null && !httpPost.isAborted()) {
httpPost.abort();
}
} finally {
if (httpClient != null) {
httpClient.getConnectionManager().shutdown();
}
backGroundExecuted = true;
}
return null;
}

Categories

Resources