Consuming Web Service Android 4.0 - android

Folks, I have an web service running on my PC, recently I changed my application from 2.2. for 4.0, and after that I cant connect to my WS anymore.
I'm looking for answers and found nothing.
My application refers the URL like this http://10.0.2.2:8080 ... But it dosn't work.
Heres my code:
private static final String URL_WS = "[this is not a link]http://10.0.2.2:8080/WS_TaxiShare/)";
public String login(String email, String password) throws Exception {
String[] resposta = new WSClient().get(URL_WS + "login/login/?login="+ email +"&password="+ password);
String saida = resposta[1];
if (resposta[0].equals("200")) {
return saida;
} else {
return saida;
}
}
Now the WSClient
public class WSClient {
public final String[] get(String url) {
String[] result = new String[2];
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
Log.i("Get taxi", "Url -> " + url);
response = HttpClientSingleton.getHttpClientInstace().execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
result[0] = String.valueOf(response.getStatusLine().getStatusCode());
InputStream instream = entity.getContent();
result[1] = toString(instream);
instream.close();
Log.i("get", "Result from post JsonPost : " + result[0] + " : " + result[1]);
}
} catch (Exception e) {
Log.i("Exception no get WS taxi", "Exception ->" + e);
result[0] = "0";
result[1] = "Falha de rede!";
}
return result;
}
Someone can help me?
PS: My WS running on Glassfish

Well, i can solve my problem. Android 4.0 (I dont know when it begin), you cant call webservices on the main thread. And all you need to do is create a async method to do what you need in a separeated thread.
Here is my method
private class loginTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
try {
//Pegando o email e a senha da tela
String login = loginLogin.getText().toString();
String password = loginSenha.getText().toString();
WSTaxiShare ws = new WSTaxiShare();
Log.i("inciando login taxi", "Login -> " + login + " Senha -> " + password);
response = ws.login(login, password);
Log.i("String resposta taxi", response + "");
} catch (Exception e) {
Log.i("Exception Login taxi", e + "");
gerarToast("Não Foi possível logar");
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String strJson) {
try {
...
} catch (JSONException e) {
...
}
}
}
And here is the call button:
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
loginTask task = new loginTask();
task.execute(new String[] { "" });
}
});

Related

Webserver to Android JSON parsing data

please have a look at my basic Android-Webserver code.
Data should from Android smartphone should be sent to a webserver, webserver should put data in database and then give the query:
{"query_result":"SUCCESS"}
(when i access the server-side script via browser i get this JSON-message, also the data is insterted into database)
The problem is that my app doesn't parse the JSON response correct or even doesn't get any response?
My code so far:
http://bits.works/view/466210bb
The code shows "Error parsing JSON data" on Android screen.
Call of method:
//Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
new SignupActivity(AndroidGPSTrackingActivity.this).execute(Double.toString(latitude), Double.toString(latitude), Double.toString(longitude), Double.toString(longitude), Double.toString(latitude));
Class with method:
public class SignupActivity extends AsyncTask<String, Void, String> {
private Context context;
public SignupActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String fullName = arg0[0];
String userName = arg0[1];
String passWord = arg0[2];
String phoneNumber = arg0[3];
String emailAddress = arg0[4];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?fullname=" + URLEncoder.encode(fullName, "UTF-8");
data += "&username=" + URLEncoder.encode(userName, "UTF-8");
data += "&password=" + URLEncoder.encode(passWord, "UTF-8");
data += "&phonenumber=" + URLEncoder.encode(phoneNumber, "UTF-8");
data += "&emailaddress=" + URLEncoder.encode(emailAddress, "UTF-8");
link = "http://qqqqqtech/signup.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Data inserted.", Toast.LENGTH_SHORT).show();
} else if (query_result.equals("FAILURE")) {
Toast.makeText(context, "Data could not be inserted.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
}
Check the returned value from doInBackground before the line
String query_result = jsonObj.getString("query_result");
This is because doInBackground might have caught an exception and returned that instead of a valid response. So, make a Toast with jsonStr before trying to parse it to see what it contains.

Asyntask not executing onPostExecute()

This is my Asyntask code which is not firing the onPostExecute() Any one has any idea why this might be happening???
EDIT: The Asyntask is called this way
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main);
.
.
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), SignUp.class);
startActivity(intent);
}
});
textView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Feedback.class);
startActivity(intent);
}
});
fbLoginButton = (LoginButton) findViewById(R.id.login_button);
fbLoginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
token=loginResult.getAccessToken().getToken().toString();
Log.v("tag", "Token:\n" + token);
try {
get_profile();
}catch (Exception ex) {
String error = ex.getMessage();
}
}
#Override
public void onCancel() {
Toast.makeText(MainActivity.this, "Login cancelled by user!", Toast.LENGTH_LONG).show();
System.out.println("Facebook Login failed!!");
}
#Override
public void onError(FacebookException e) {
Toast.makeText(MainActivity.this, "Login unsuccessful!", Toast.LENGTH_LONG).show();
System.out.println("Facebook Login failed!!");
}
});
}
The get_profile(); method is defined like this
//Method to get profile details
public void get_profile() throws UnsupportedEncodingException {
try {
// Calling async task to get json
new FetchOperation().execute();
} catch (Exception e) {
e.printStackTrace();
}
}
This is inside the Main class too
//Asynctask to get Getting fb profile details
private class FetchOperation extends AsyncTask<Void, Void, String> {
String fb_token;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Get user defined values
fb_token = token;
}
#Override
protected String doInBackground(Void... params) {
String response = "";
String Urls = "https://graph.facebook.com/me?access_token=";
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(Urls +token);
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
try {
httpResponse = httpclient.execute(httpget);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.v("Response", "Hi From e1 : " + e.toString());
} catch (IOException e) {
e.printStackTrace();
}
try {
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
Log.v("Response", "Hi From 2 : "+response.toString());
return response;
} catch (IOException e) {
e.printStackTrace();
Log.v("Response", "Hi From e2 : " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(String jsonStr) {
super.onPostExecute(jsonStr);
Log.v("tag", "Result:" + jsonStr);
if (jsonStr != null) {
try{
JSONObject jsonObj = new JSONObject(jsonStr);
String email = jsonObj.getString("email");
String firstName = jsonObj.getString("first_name");
String lastName = jsonObj.getString("last_name");
String gender = jsonObj.getString("gender");
String country = jsonObj.getString("locale");
id = jsonObj.getString("id");
user = firstName.concat(" ");
user = user.concat(lastName);
image = "http://graph.facebook.com/" + id + "/picture?type=large";
Log.v("Fb name", "Bla bla Name : " + user);
new UploadOperation().execute();
}
catch (JSONException e) {
e.printStackTrace();
}
}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}
}
This is the last lines of the logcat
06-29 14:30:49.927 2091-2091/com.example.kmi_dev.fbloginsample V/tag﹕ Token:
CA****************************************************************xr
06-29 14:30:50.697 2091-2135/com.example.kmi_dev.fbloginsample V/Response﹕ Hi From 2 : {"id":"910***********6","first_name":"Shivanshu","gender":"male","last_name":"Verma","link":"https:\/\/www.facebook.com\/app_scoped_user_id\/910***********6\/","locale":"en_GB","name":"Shivanshu Verma","timezone":5.5,"updated_time":"2015-06-22T04:17:39+0000","verified":true}
06-29 14:31:23.827 2091-2098/com.example.kmi_dev.fbloginsample W/art﹕ Suspending all threads took: 10ms
I intend to fire another asyntask which will then save the data fetched by this asyntask into the database.
Make these changes, it will work -
private class FetchOperation extends AsyncTask<Void, Void, String>
change to - private class FetchOperation extends AsyncTask<Void, String, String> , because, you are trying to return String.
response = EntityUtils.toString(httpEntity);
change to - response = EntityUtils.toString(httpEntity).toString();
at the next line of this you have actually done it.
At the very end of doInBackground method where return null;
change to - return response;
4.No need to call super in onPostExecute()
5.Inside onPostExecute() check jsonStr is null or not and do whatever you want to do if null and if contains json data.
Your JSONObject does not contain a JSONString "email", so it is falling over at line
String email = jsonObj.getString("email");
and going straight to catch block.

IOException on HTTP post request

I am creating a login form using Account Manageraccount manager and HTTP task for webservices. when i enter the username and password it gives me IOException, I have added the INTERNET PERMISSION and all the account related permission. If anyone knows any github example which uses account manager and webservices please share the url.please help.this is the code
`
public void userSignUp(String name, String email, String pass, String authType, final SignUPHandler handler) {
HttpPost localHttpPost = new HttpPost(ApiURL.USERSIGNIN);
JSONObject json_user = new JSONObject();
try {
json_user.put("email", email);
json_user.put("password", pass);
StringEntity se = new StringEntity(json_user.toString());
localHttpPost.setEntity(se);
if ((this.currentTask != null) && (this.currentTask.getStatus() != AsyncTask.Status.FINISHED))
this.currentTask.cancel(true);
this.currentTask = new HttpTask(ApiURL.HTTP_LOGIN_HOST, new HttpResponseHandler() {
public void handleException(Exception paramException) {
Log.e("Exceptionssssssss:", "" + paramException);
handler.handleException(paramException);
}
public void handleResponse(JSONObject json)
throws IOException {
Log.d("response", "" + json);
handler.handleResponse(json);
}
});
this.currentTask.execute(new HttpUriRequest[]{localHttpPost});
} catch (Exception localException) {
Log.d("Exception ID", "" + localException.getMessage());
}
}`

android HttpGet/HttpPost parameters allways arrive as null to the server

I'm trying to send data to the server but it seems that I always send null values, any idea? The idea is to add a new customer through the mobile application to my database hosted in a server.
Here's my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nuevo_insert);
//etResponse = (EditText) findViewById(R.id.etResponse2);
etNombre = (EditText) findViewById(R.id.etNombre);
etApellido = (EditText) findViewById(R.id.etApellido);
etEdad = (EditText) findViewById(R.id.etEdad);
nombre = etNombre.getText().toString();
apellido = etApellido.getText().toString();
edad = etEdad.getText().toString();
}
public void insertar(View view) {
// Call AsyncTask to perform network operation on separate thread
// working in localhost you CAN'T put localhost in that address, you
// MUST put your IP address or it will crush
new HttpAsyncTask().execute("http://192.168.1.34/android/insertCustomer.php");
}
public static String GET(String url) {
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpClient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpClient.execute(new HttpGet(url+ "?nombre=" + nombre + "&apellido=" + apellido + "&edad="+ edad));
// receive response as InputStream
inputStream = httpResponse.getEntity().getContent();
// convert InputStream to string
if (inputStream != null) {
result = convertInputStreamToString(inputStream);
} else {
result = "No ha funcionat!";
}
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask
#Override
protected void onPostExecute(String result) {
String s = "";
Toast.makeText(getBaseContext(),getResources().getString(R.string.rebut), Toast.LENGTH_LONG).show();
JSONArray jArray;
try {
jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json = jArray.getJSONObject(i);
s = s + "Nom: " + json.getString("FirsName") + " "
+ json.getString("LastName") + "\n" + "Edat: "+ json.getInt("Age") + "\n\n";
}
etResponse.setText(s);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This is my php file:
<?php
$con = mysql_connect('localhost', 'root', '');
if(!$con){
die("No se ha podido realizar la conexion: ".mysql_error());
}
mysql_select_db("TestDatabase", $con);
$nombre = $_GET['nombre'];
$apellido = $_GET['apellido'];
$edad = $_GET['edad'];
print_r($nombre."-".$apellido."-".$edad);
$result = mysql_query("insert into customer(FirsName, LastName, Age) values ('$nombre', '$apellido', '$edad')");
mysql_close($con);
?>
OK the problem was that I was retrieving the data from EditText boxes in the onCreate and I had to do it in the GET method :-)
If you are getting null value means that mean u r passing wrong type parameters or url may be wrong you do check it out
Change
HttpResponse httpResponse = httpClient.execute(new HttpGet(url+ "?nombre=" + nombre + "&apellido=" + apellido + "&edad="+ edad));
to this:
String request = url+ "?nombre=" + nombre + "&apellido=" + apellido + "&edad="+ edad;
Log.d("DEBUG", request);
HttpResponse httpResponse = httpClient.execute(request);
and see your logcat for your url, maybe it is broken.
if the url is ok, then try opening this url in your browser and check the results.

Rest with Android 4.0

Folks, I have an web service running on my PC, recently I changed my application from 2.2. for 4.0, and after that I cant connect to my WS anymore.
I'm looking for answers and found nothing.
My application refers the URL like thishttp://10.0.2.2:8080 ... But it dosn't work.
Heres my code:
private static final String URL_WS = "http://10.0.2.2:8080/WS_TaxiShare/)";
public String login(String email, String password) throws Exception {
String[] resposta = new WSClient().get(URL_WS + "login/login/?login="+ email +"&password="+ password);
String saida = resposta[1];
if (resposta[0].equals("200")) {
return saida;
} else {
return saida;
}
}
Now the WSClient
public class WSClient {
public final String[] get(String url) {
String[] result = new String[2];
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
Log.i("Get taxi", "Url -> " + url);
response = HttpClientSingleton.getHttpClientInstace().execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
result[0] = String.valueOf(response.getStatusLine().getStatusCode());
InputStream instream = entity.getContent();
result[1] = toString(instream);
instream.close();
Log.i("get", "Result from post JsonPost : " + result[0] + " : " + result[1]);
}
} catch (Exception e) {
Log.i("Exception no get WS taxi", "Exception ->" + e);
result[0] = "0";
result[1] = "Falha de rede!";
}
return result;
}
Well, i can solve my problem. Android 4.0 (I dont know when it begin), you cant call webservices on the main thread. And all you need to do is create a async method to do what you need in a separeated thread.
Here is my method
private class loginTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
try {
WSTaxiShare ws = new WSTaxiShare();
response = ws.login(login, password);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String strJson) {
}
and here is the call button
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
loginTask task = new loginTask();
task.execute(new String[] { "" });
}
});
}

Categories

Resources