Android - Error when uploading multiple images - java

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

Related

AsyncTask error occured while executing doInBackground()

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

Using webAPIs in android for login gives FATAL EXCEPTION: AsyncTask #1 error

I am very new in using JSON in Android. I have got the webAPI that the base URL is
Test server. While developing, I am trying to login using email and password from web server database.
A user token is calculated by following formula:
Token = MD5(email + userId); I do not know what is this. What I tried to do is ;
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
System.out.println("url:: "+url );
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
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;
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
//Making HTTP request
try{
//check for the request method
if(method == "POST"){
//request method to post
//default HTTPClient
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 to 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;
}
}
Login.java
public class Login extends Activity {
EditText inputEmail;
EditText inputPassword;
Button loginBtn;
// Progress Dialog
ProgressDialog pDialog;
// JSONParser class
JSONParser jsonParser = new JSONParser();
// PHP Login Script location
private static final String LOGIN_URL = "http://www.sthng.com/ws/?c=profile&func=login";
// JSON element ids from repsonse of php script:
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.login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
loginBtn = (Button) findViewById(R.id.btnLogin);
loginBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new AttemptLogin().execute();
}
});
}
// AsyncTask is a seperate thread than the thread that runs the GUI
// Any type of networking should be done with asynctask.
class AttemptLogin extends AsyncTask<String, Void, String> {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
//params.add(new BasicNameValuePair("RegistrationID", ));
// Log.d("HERE", email);
// Log.d("HERE2", password);
Log.d("request!", "starting");
// getting users details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "GET", params);
Log.d("DEBUG!", "CHECKPOINT");
// json = json.toString();
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
/* Intent i = new Intent(Login.this, Home.class);
finish();
startActivity(i);*/
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;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
But I am getting error like;
04-29 19:03:22.691: D/request!(15060): starting
04-29 19:03:22.736: D/dalvikvm(15060): GC_CONCURRENT freed 222K, 14% free 9575K/11015K, paused 13ms+22ms, total 82ms
04-29 19:03:22.781: W/dalvikvm(15060): threadid=11: thread exiting with uncaught exception (group=0x41d082a0)
04-29 19:03:22.791: E/AndroidRuntime(15060): FATAL EXCEPTION: AsyncTask #1
04-29 19:03:22.791: E/AndroidRuntime(15060): java.lang.RuntimeException: An error occured while executing doInBackground()
04-29 19:03:22.791: E/AndroidRuntime(15060): at android.os.AsyncTask$3.done(AsyncTask.java:299)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
04-29 19:03:22.791: E/AndroidRuntime(15060): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.lang.Thread.run(Thread.java:856)
04-29 19:03:22.791: E/AndroidRuntime(15060): Caused by: java.lang.IllegalArgumentException: Host name may not be null
04-29 19:03:22.791: E/AndroidRuntime(15060): at org.apache.http.HttpHost.<init>(HttpHost.java:83)
04-29 19:03:22.791: E/AndroidRuntime(15060): at org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:519)
04-29 19:03:22.791: E/AndroidRuntime(15060): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
04-29 19:03:22.791: E/AndroidRuntime(15060): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
04-29 19:03:22.791: E/AndroidRuntime(15060): at com.example.sthng.JSONParser.makeHttpRequest(JSONParser.java:125)
04-29 19:03:22.791: E/AndroidRuntime(15060): at com.example.sthng.Login$AttemptLogin.doInBackground(Login.java:106)
04-29 19:03:22.791: E/AndroidRuntime(15060): at com.example.sthng.Login$AttemptLogin.doInBackground(Login.java:1)
04-29 19:03:22.791: E/AndroidRuntime(15060): at android.os.AsyncTask$2.call(AsyncTask.java:287)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
04-29 19:03:22.791: E/AndroidRuntime(15060): ... 5 more
04-29 19:03:32.686: I/Choreographer(15060): Skipped 589 frames! The application may be doing too much work on its main thread.
04-29 19:03:33.256: E/WindowManager(15060): Activity com.example.sthng.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#427a0298 that was originally added here
04-29 19:03:33.256: E/WindowManager(15060): android.view.WindowLeaked: Activity com.example.clipme.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#427a0298 that was originally added here
04-29 19:03:33.256: E/WindowManager(15060): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:403)
04-29 19:03:33.256: E/WindowManager(15060): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:311)
04-29 19:03:33.256: E/WindowManager(15060): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
04-29 19:03:33.256: E/WindowManager(15060): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
04-29 19:03:33.256: E/WindowManager(15060): at android.view.Window$LocalWindowManager.addView(Window.java:554)
04-29 19:03:33.256: E/WindowManager(15060): at android.app.Dialog.show(Dialog.java:277)
04-29 19:03:33.256: E/WindowManager(15060): at com.example.sthng.Login$AttemptLogin.onPreExecute(Login.java:87)
04-29 19:03:33.256: E/WindowManager(15060): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
04-29 19:03:33.256: E/WindowManager(15060): at android.os.AsyncTask.execute(AsyncTask.java:534)
04-29 19:03:33.256: E/WindowManager(15060): at com.example.sthng.Login$1.onClick(Login.java:61)
04-29 19:03:33.256: E/WindowManager(15060): at android.view.View.performClick(View.java:4232)
04-29 19:03:33.256: E/WindowManager(15060): at android.view.View$PerformClick.run(View.java:17298)
04-29 19:03:33.256: E/WindowManager(15060): at android.os.Handler.handleCallback(Handler.java:615)
04-29 19:03:33.256: E/WindowManager(15060): at android.os.Handler.dispatchMessage(Handler.java:92)
04-29 19:03:33.256: E/WindowManager(15060): at android.os.Looper.loop(Looper.java:137)
04-29 19:03:33.256: E/WindowManager(15060): at android.app.ActivityThread.main(ActivityThread.java:4921)
04-29 19:03:33.256: E/WindowManager(15060): at java.lang.reflect.Method.invokeNative(Native Method)
04-29 19:03:33.256: E/WindowManager(15060): at java.lang.reflect.Method.invoke(Method.java:511)
04-29 19:03:33.256: E/WindowManager(15060): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
04-29 19:03:33.256: E/WindowManager(15060): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
04-29 19:03:33.256: E/WindowManager(15060): at dalvik.system.NativeStart.main(Native Method)
I am sure I have done some stupid mistake but please do not take it bad way. I hope I get some hints and solutions for this.
You are accessing UI element doInBackground()
Intent i = new Intent(Login.this, Home.class);
finish();
startActivity(i);
above method on doInBackground(). You have to call this method onPostExecute.
you are sending email and password two time.
You make url with https:sthng.com/ws?function=login&email=" + email+ "&password=" + password
JSONObject json = jsonParser.makeHttpRequest(
"https:sthng.com/ws?function=login&email=" + email
+ "&password=" + password, "POST", params);
or
Now you make below param.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("androidToken", androidToken));// your token
and passing again
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));// passing again

Gson and Google

I have the following code:
public String test(){
URL url = null;
try {
url = new URL("http://api.heroesofnewerth.com/player_statistics/ranked/nickname/Hieratic/?token=0CZGH8ZI7UR8J2GN");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader reader = null;
String x = "";
try {
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
x = line;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if (reader !=null) try{reader.close();} catch (IOException ignore) {
}{}
}
JsonElement root = new JsonParser().parse(x);
return x;
}
}
now i want to insert the text into the following textView.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_competetion);
TextView tv = (TextView) findViewById(R.id.competetion_text);
JsonCollector jc = new JsonCollector();
tv.setText(jc.test());
However when i try to run it. i get the following error:
FATAL EXCEPTION: main
E/AndroidRuntime(1800): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.konkurrencesigner/com.example.konkurrencesigner.CreateCompetetion}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
E/AndroidRuntime(1800): at android.app.ActivityThread.access$600(ActivityThread.java:141)
E/AndroidRuntime(1800): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
E/AndroidRuntime(1800): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(1800): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(1800): at android.app.ActivityThread.main(ActivityThread.java:5039)
E/AndroidRuntime(1800): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(1800): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(1800): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(1800): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(1800): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(1800): Caused by: android.os.NetworkOnMainThreadException
E/AndroidRuntime(1800): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
E/AndroidRuntime(1800): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
E/AndroidRuntime(1800): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
E/AndroidRuntime(1800): at java.net.InetAddress.getAllByName(InetAddress.java:214)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
E/AndroidRuntime(1800): at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)
Can anyone tell me why this is happening?
please note that i have already added the following line in my android manifest:
<uses-permission android:name="android.permission.INTERNET" />
You are doing HTTP communication on the main thread, that's why you're getting a NetworkOnMainThreadException. Do it in a separate thread, using an AsyncTask would be an ideal solution, here's an example of how you could implement it:
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_competetion);
tv = (TextView) findViewById(R.id.competetion_text);
JsonCollector jc = new JsonCollector();
// Create and execute a new AsyncTask, the TextView will
// be updated asynchronously when the task has finished.
updateTextView();
}
private void updateTextView() {
new AsyncTask<Void, Void, String>() {
#Override
/* Runs on a separate thread */
protected String doInBackground(Void... params) {
String result = null;
BufferedReader reader = null;
try {
URL url = new URL("http://api.heroesofnewerth.com/player_statistics/ranked/nickname/Hieratic/?token=0CZGH8ZI7UR8J2GN");
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
result = line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// Ignore
}
}
}
return result;
}
#Override
/* Runs on the UI/Main thread when doInBackground()
* has finished */
protected void onPostExecute(String result) {
if(result != null) {
// Update the TextView only if we got a result
// from the HTTP request
tv.setText(result);
}
}
}.execute();
}
If you need networking in main thread add these lines of code in the onCreate() method
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

Java Android HTTP POST login error

i have a problem logging in to a website made in asp...
Here is the code i am using:
public class MainActivity extends Activity {
Button bottone;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottone = (Button) findViewById(R.id.button1);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
bottone.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// starting new Async Task
try {
login();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public static void login() throws IOException
{
String loginurl = "https://www.blurum.it/Web/", user, pass;
user = "tester55";
pass = "provapassword321";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(loginurl);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("ctrl_LoginControl$loginView$c01$RPLogin$LoginView$Username", user));
nameValuePairs.add(new BasicNameValuePair("ctrl_LoginControl$loginView$c01$RPLogin$LoginView$Password", pass));
nameValuePairs.add(new BasicNameValuePair("remember", "on"));
nameValuePairs.add(new BasicNameValuePair("ctrl_LoginControl$loginView$c01$RPLogin$LoginView$LoginButton", "Accedi"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpClient.execute(httpPost);
Log.d("logggd", "response stat code " + response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() < 400) {
String cookie = response.getFirstHeader("Cookie")
.getValue();
Log.d("logggdc", "cookie: " + cookie);
// get the contacts page
HttpGet getContacts = new HttpGet("https://www.blurum.it/Web/default.aspx");
getContacts.setHeader("Cookie", cookie);
response = httpClient.execute(getContacts);
InputStream ins = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(
ins));
String inputLine;
while ((inputLine = in.readLine()) != null) {
Log.d("logggd1", " " + inputLine);
}
in.close();
} else {
Log.d("logggd2", "Response error: "
+ response.getStatusLine().getStatusCode());
}
}
}
But my application crash, so i can't find the error in the code... Here is the logcat:
11-12 20:05:37.678: W/dalvikvm(1806): threadid=1: thread exiting with uncaught exception (group=0xb4177180)
11-12 20:05:37.688: E/AndroidRuntime(1806): FATAL EXCEPTION: main
11-12 20:05:37.688: E/AndroidRuntime(1806): java.lang.NullPointerException
11-12 20:05:37.688: E/AndroidRuntime(1806): at com.example.testlogin.MainActivity.login(MainActivity.java:93)
11-12 20:05:37.688: E/AndroidRuntime(1806): at com.example.testlogin.MainActivity$1.onClick(MainActivity.java:53)
11-12 20:05:37.688: E/AndroidRuntime(1806): at android.view.View.performClick(View.java:3511)
11-12 20:05:37.688: E/AndroidRuntime(1806): at android.view.View$PerformClick.run(View.java:14105)
11-12 20:05:37.688: E/AndroidRuntime(1806): at android.os.Handler.handleCallback(Handler.java:605)
11-12 20:05:37.688: E/AndroidRuntime(1806): at android.os.Handler.dispatchMessage(Handler.java:92)
11-12 20:05:37.688: E/AndroidRuntime(1806): at android.os.Looper.loop(Looper.java:137)
11-12 20:05:37.688: E/AndroidRuntime(1806): at android.app.ActivityThread.main(ActivityThread.java:4424)
11-12 20:05:37.688: E/AndroidRuntime(1806): at java.lang.reflect.Method.invokeNative(Native Method)
11-12 20:05:37.688: E/AndroidRuntime(1806): at java.lang.reflect.Method.invoke(Method.java:511)
11-12 20:05:37.688: E/AndroidRuntime(1806): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
11-12 20:05:37.688: E/AndroidRuntime(1806): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
11-12 20:05:37.688: E/AndroidRuntime(1806): at dalvik.system.NativeStart.main(Native Method)
11-12 20:05:38.218: I/dalvikvm(1806): threadid=3: reacting to signal 3
11-12 20:05:38.228: I/dalvikvm(1806): Wrote stack traces to '/data/anr/traces.txt'
I extracted the posted data to the server in firefox with Tamper Data, here is a screen, the login i think is divided in 2 post, here are the screen:
http://i.stack.imgur.com/GZiZ0.png
http://i.stack.imgur.com/FKH3P.png
I am not sure if i have to send the first page or the second post data, can be this the error? thanks.
It seems response.getFirstHeader("Cookie") is returning null.
As per javadoc
Returns the first header with a specified name of this message. Header values are ignored. If there is more than one matching header in the message the first element of getHeaders(String) is returned. If there is no matching header in the message null is returned
Solution:
Do a null check before calling getValue();
Example:
String cookie = null;
if(response.getFirstHeader("Cookie") != null)
{
cookie = response.getFirstHeader("Cookie")
.getValue();
}
You can't call the below line more than once in your code block;
response.getStatusLine()
You are calling it more than once in your lines that look like this;
Log.d("logggd", "response stat code " + response.getStatusLine().getStatusCode());
And then you're calling it again on this line;
if (response.getStatusLine().getStatusCode() < 400) {
Comment out the first calling of response.getStatusLine() - that's where you're trying to log the status code. So your code should look like this;
//Log.d("logggd", "response stat code " + response.getStatusLine().getStatusCode());
You also want to try and do this somewhere there in your method called login();
// Execute HTTP Post Request
HttpResponse response = httpClient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
Log.d("logggd", "response stat code " + statusLine.getStatusCode());
if (statusLine.getStatusCode() < 400) {
String cookie = null;
if(response.getFirstHeader("Cookie") != null){
cookie = response.getFirstHeader("Cookie").getValue();
}
Log.d("logggdc", "cookie: " + cookie);
//...etc....etc...etc

Error with ArrayAdapter in AsyncTask

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

Categories

Resources