Emulator won't execute AsyncTask.execute().get() - java

I have a program to download JSON Strings from a server. Things were working fine up until recently, when I try to call
jsonReader.execute(getUrl).get();
Where jsonReader is an AsyncTask to download JSON Strings and getUrl is the URL to execute. This method never gets executed, the weird thing is, it works on my phone.
Here is my code
Method which calls json string reader
private PointOfInterest getPointWithID(int id) {
String getUrl;
JSONReader jsonReader = new JSONReader();
try {
Log.d(TAG,"Trying to get ID: " + id);
getUrl = url + String.valueOf(id);
Log.d(TAG,"Trying to get json from: " + id); <-- Last Log line to get printed when run on emulator
jsonReader.execute(getUrl).get();
} catch (Exception e) {
e.printStackTrace();
}
String jsonString = jsonReader.returnJSONString();
Log.d(TAG,"Downloaded: " + jsonString);
//System.out.println("JSON: " + jsonString);
JSONResponse jsonResponse = JSONResponse.convertJSONToResponse(jsonString);
//System.out.println("JSON RESPONSE " + jsonResponse);
return jsonResponse.getPointofInterest();
}
jsonReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Log;
/**
* Read JSON Strings
* #author Tom
*
*/
public class JSONReader extends AsyncTask <String, Void, String> {
String result;
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
StringBuilder sb = new StringBuilder();
String TAG = "JSONReader";
// constructor
public JSONReader() {
result = "";
}
#Override
protected String doInBackground(String... url) {
Log.d(TAG, "Executing " + url); <--Does not get printed when run on emulator
HttpPost httppost = new HttpPost(url[0]);
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
// json is UTF-8 by default i believe
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}catch(Exception e){
e.printStackTrace();
}
return result = sb.toString();
}
public String returnJSONString(){
return result;
}
}
I have tried restarting adb, making new AVD's but nothing seems to work, my only option is testing on my phone however, this is not desirable as I am developing for api 17. Thanks for your help !

There are a few threading rules that must be followed for this class to work properly:
The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN.
The task instance must be created on the UI thread.
execute(Params...) must be invoked on the UI thread.
Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.
The task can be executed only once (an exception will be thrown if a second execution is attempted.)

Related

Error in mapper.writeValue() method

I am developing a Java application to be the server in a Google Cloud Messaging Android app.
I have been following a tutorial and I managed to do rest of the tutorial with out a trouble.
My Java application has three classes which are Content.java, POST2GCM.java, App.java. These classes do what the name describes.
Content.java class is below.
package com.hmkcode.vo;
import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class Content implements Serializable {
private List<String> registration_ids;
private Map<String,String> data;
public void addRegId(String regId){
if(registration_ids == null)
registration_ids = new LinkedList<String>();
registration_ids.add(regId);
}
public void createData(String title, String message){
if(data == null)
data = new HashMap<String,String>();
data.put("title", title);
data.put("message", message);
}
}
App.java class is below
package com.hmkcode.vo;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmkcode.vo.Content;
public class App
{
public static void main( String[] args )
{
System.out.println( "Sending POST to GCM" );
String apiKey = "AIzaSyB8azikXJKi_NjpWcVNJVO0d........";
Content content = createContent();
POST2GCM.post(apiKey, content);
}
public static Content createContent(){
Content c = new Content();
c.addRegId("APA91bFqnQzp0z5IpXWdth1lagGQZw1PTbdBAD13c-UQ0T76BBYVsFrY96MA4SFduBW9RzDguLaad-7l4QWluQcP6zSoX1HSUaAzQYSmI93....");
c.createData("Test Title", "Test Message");
return c;
}
}
POST2GCM.java class is below
package com.hmkcode.vo;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.fasterxml.jackson.databind.*;
public class POST2GCM {
public static void post(String apiKey, Content content){
try{
// 1. URL
URL url = new URL("https://android.googleapis.com/gcm/send");
// 2. Open connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 3. Specify POST method
conn.setRequestMethod("POST");
// 4. Set the headers
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key="+apiKey);
conn.setDoOutput(true);
// 5. Add JSON data into POST request body
//`5.1 Use Jackson object mapper to convert Content object into JSON
ObjectMapper mapper = new ObjectMapper();
// 5.2 Get connection output stream
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
// 5.3 Copy Content "JSON" into
mapper.writeValue(wr,content);
// 5.4 Send the request
wr.flush();
// 5.5 close
wr.close();
// 6. Get the response
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 7. Print result
System.out.println(response.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The problem arises in the POST2GCM.java class, in the line
mapper.writeValue(wr,content);
Where the suggestions are to add try catch block,Add exception to method signature, Add catch clauses(s).
I did all the suggestions which did not solve the problem.
What would be the problem here?
You need to add the jackson-core-2.4.3.jar library file to your project.
Add it to your java build path too.
Of course ... 2.4.3 is the version I used, but it should work with previous versions.

Android connect with php Mysql

I can't figure out whats wrong with this code , it's supposed to get data from php page that i created.
I'm using Eclipse with android SDK.
package com.myproject.myproject2;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class EntList extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.entlist);
JSONArray jsonArray = null;
String jsonString = null;
StringBuilder stringBuilder = null;
InputStream inStream = null;
TextView tv = (TextView) findViewById(R.id.listtitle);
ArrayList<NameValuePair> nVPArray = new ArrayList<NameValuePair>(); //This is empty because you're asking for data
try{
//Connect to your script, and save get an object to read the data (inStream)
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://sawtaljabal.com/ar/android_connect/test.php"); // Be sure to replace with your actual script
post.setEntity(new UrlEncodedFormEntity(nVPArray));
HttpResponse postResponse = client.execute(post);
HttpEntity responseEntity = postResponse.getEntity();
inStream = responseEntity.getContent();
}catch(Exception e){
Log.e("Error connecting", e.getLocalizedMessage());
}
try{
//read the stream to a single JSON string
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream,"iso-8859-1"), 10); // iso-8859-1 is the character converter
stringBuilder = new StringBuilder();
stringBuilder.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
inStream.close();
jsonString = stringBuilder.toString();
}catch(Exception e){
Log.e("Error creating JSON string", e.getLocalizedMessage());
}
try{
//Turn the JSON string into an array of JSON objects
jsonArray = new JSONArray(jsonString);
JSONObject jsonObject = null;
for(int i=0;i< jsonArray.length();i++){
jsonObject = jsonArray.getJSONObject(i);
//do something with the object, like String data = jsonObject.getString("KEY");
String data = jsonObject.getString("n_t");
tv.setText(data);
}
}
catch(JSONException e){
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
I don't even know what to try , can u help me please, this is my first Application.
To connect php using Android
first your have to call a web service (which may be a php page returning json), call to this page should be in AsynTask class.
Then you need to parse json in right way.
You can try any good tutorial for this. Try this
If this is your first android app you may want to try cloning this project and learn with code there:
https://github.com/jgilfelt/android-jsonarrayadapter?files=1
Hope it helps.
Are you sure, the String you are getting in the response is a JSON Array. I think it should be a JSON object by which you can get the further JSON Array .
which means
// try parse the string to a JSON object
try {
jObj = new JSONObject(jsonString);
} catch (JSONException e) {
}
and then parse the JSON array from JSON Object.
Check Out this link, it might be helpful.
Also do all networking call in AsynTask or in a different thread.

Connect to a MySQL database from android. No indication it's working/not working...?

I've been going through two tutorials to get the code for this project of mine;
Connecting to MySQL database
Connecting Android to remote mysql via PHP and JSON
I've learnt the code up to a point since I'm still a beginner and used a lot of it at the same time. Here is what I have at the moment:
package com.android.history;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
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.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class CurrentSeasonDrivers extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.currentseason_drivers);
}
//PARSE JSON ETC
public void parseJSON() {
String result = "";
String drivername = "";
String drivesfor = "";
InputStream is=null;
//HTTP POST REQUEST
try{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.13/testdatabase.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
Toast.makeText(getBaseContext(), "Could not connect", Toast.LENGTH_LONG).show();
}
//CONVERT DATA TO STRING
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
Toast.makeText(getBaseContext(), "Could not convert result", Toast.LENGTH_LONG).show();
}
//PARSE JSON DATA
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
drivername=json_data.getString("Driver_full_name");
drivesfor=json_data.getString("Drives_for");
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
Toast.makeText(getBaseContext(), "Could not parse data", Toast.LENGTH_LONG).show();
}
}
}
Now I have no errors and the application works fine. When I got to the page that this is all made for I get nothing. A blank page. As you can see from my code I've added toasts exceptions but none of them show up either. Even if I intentionally close my server which is odd. Is there something else I should be doing. As the title says because the toasts are not working I have no indication if the code is actually doing anything. I just have a blank page.
I've added Internet to my manifest to allow the app access to that. If I visit the URL in my code (192.168.0.13/testdatabase.php) via my browser the data from my database shows up just fine.
Edit: The overall outcome I want from this eventually is to have some data from database displayed for my users to see. Instead of putting it in as static text and having to update the entire app just to update some data.
You need to implement your network connection on a separate thread for API level 11 or greater. Take a look on this link: HTTP Client API level 11 or greater in Android.
Also for the POST request, I think that you can use this code:
public String post(String str) {
String result = "";
try {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost postRequest = new HttpPost(SERVER_ADDRESS);
StringEntity input = new StringEntity(str);
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
result = getResult(response).toString();
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return result;
}
private StringBuilder getResult(HttpResponse response) throws IllegalStateException, IOException {
StringBuilder result = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())), 1024);
String output;
while ((output = br.readLine()) != null)
result.append(output);
return result;
}

Android HttpClient for my PC

I need to develop an helper class on top of org.apache.httpclient for my android application. Following code works fine for android, but not for JavaSE 1.6 in my PC.
Question is: Can I use org.apache.httpclient both for android and for PC? If I cant: what is your http client library advise?
I want to develop one helper class and use it at all.
Here is the code that works fine in android but some classes cannot be resolved for on Java SE 1.6.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class HTTPClient {
public static void connect(String url)
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
// now you have the string representation of the HTML request
instream.close();
}
} catch (Exception e) {}
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
Yes you can, you should avoid naming your client helper class as the same thing as an already defined class. Although Java is case sensitive, it is confusing will trip you up when you least expect it. It may even be guilty for causing this problem. Why not call it HttpClientHelper as that is what it truly is.
Here's an example of HttpClient http://hc.apache.org/httpclient-3.x/tutorial.html

Internal Server Error [duplicate]

This question already has answers here:
How to do a HTTP Post in Android?
(2 answers)
Closed 7 years ago.
I am working on an SMS Sending application and for login purpose i want to send the username and password using POST method from my Android Application to the web server.
When I click on lo-gin button the application is not responding and the console prints the following message in response of the Post request.
HTTP/1.1 500 Internal Server Error
While my application running fine with the GET method.
I am not able to figure out why this is causing...
the whole code is here:
package com.vikas.httplogin;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
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.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class HttpLogin extends Activity {
TextView tv;
private static final String tag ="FATAL_ERROR";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
connecttoServer();
}
private void connecttoServer()
{
BufferedReader br = null;
try
{
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost("url of my site");
List<NameValuePair> params = new ArrayList<NameValuePair>(3);
params.add(new BasicNameValuePair("username","vikaspatidar"));
params.add(new BasicNameValuePair("password", "patidar"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params);
request.setEntity(entity);
Log.v(tag,request.getMethod().toString());
HttpResponse response = client.execute(request);
Log.v(tag, response.getStatusLine().toString());
br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = br.readLine()) != null) {
sb.append(line + NL);
}
br.close();
String result = sb.toString();
Log.v(tag, result);
} catch (ClientProtocolException e)
{
Log.v(tag, e.getMessage());
}
catch (IllegalStateException e) {
Log.v(tag, e.getMessage());
} catch (IOException e) {
Log.v(tag, e.getMessage());
}
}
}
That's definitely looks like server-side error, not android problem. Look at server log files.
The way you're setting parameters to request looks weird, try setting parameters like this:
HttpPost post = new HttpPost("url of my site");
BasicHttpParams basicHttpParams = new BasicHttpParams();
basicHttpParams.setParameter("username", "vikaspatidar");
basicHttpParams.setParameter("password", "patidar");
post.setParams(basicHttpParams);
//...
Here is solution for this:
How to do a HTTP Post in Android?

Categories