Rest with 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 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[] { "" });
}
});
}

Related

Async not working while sending image to server?

I need to send image to service, pre-execute method working where as do in background not working. Code is below for same:
private class SendImageAsync extends AsyncTask<String, String, String> {
private Context context;
private String serverUrl;
private String path;
public SendImageAsync(Context context, String serverUrl,
String path) {
this.context = context;
this.serverUrl = serverUrl;
this.path = path;
}
#Override
protected void onPreExecute() {
LogWrite.i(TAG, "onPreExecute method enters!!");
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
LogWrite.i(TAG, "doInBackground method enters!!");
byte[] imageBytes = getFileBytes(path);
ImageToSend sendImage = new ImageToSend();
boolean responseStatus = sendImage.send(context, serverUrl,
imageBytes );
String responseString = responseStatus ? "Success!" : "Fail!";
LogWrite.e(TAG, "Response " + responseString);
return "";
}
#Override
protected void onPostExecute(String result) {
LogWrite.i(TAG, "onPostExecute method enters!!");
super.onPostExecute(result);
}
}
Help me on same, why it is not working?
Update code:
I had created an interface, that will notify on image click and provide me path of file:
#Override
public void onImageCapture(File file) {
if (file != null) {
LogWrite.d(TAG, "File Path ::: " + file.getAbsolutePath());
if (isFromCommand) {
LogWrite.d(TAG, "Is from command : "+ isFromCommand);
try {
SendImageAsync async = new SendImageAsync (activity,
serverUrl, file.getAbsolutePath());
async.execute("");
} catch (Exception e) {
LogWrite.e(TAG, "SendImageAsync Exception : " + e.toString());
}
}
Bitmap myBitmap = showBitmapFromFile(file.getAbsolutePath());
myBitmap = RotateBitmap(myBitmap, 90);
Drawable ob = new BitmapDrawable(getResources(), myBitmap);
saveImageView.setBackgroundDrawable(ob);
}
// saveImageView.setImageBitmap(myBitmap);
}
I'm not sure but you probably want to send a request and not a response...
I found the solution, I was using this AsyncTask on another AsyncTask, So its not working, even it was not giving any exception.
Here are the basic sample code you can refer, hope this help
/**
* Async task to post file to remote web api
*/
public class PostFileToWebAPI extends AsyncTask<String, Integer, Object> {
...
#Override
protected Object doInBackground(String... params) {
String filePath = params[1];
try {
return postFile(mAPI_URL, filePath);
} catch (Exception e) {
return e.getMessage();
}
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
}
}
private String postFile(String apiUrl, String filePath) throws Exception {
// init httpClient, httpPost...
...
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
File file = new File(filePath);
FileBody fileBody = new FileBody(file);
final long totalSize = fileBody.getContentLength();
builder.addPart("file", fileBody);
httpEntity = builder.build();
httpPost.setEntity(httpEntity);
httpResponse = httpClient.execute(httpPost);
statusCode = httpResponse.getStatusLine().getStatusCode();
if ((statusCode != HttpStatus.SC_OK) && (statusCode != HttpStatus.SC_INTERNAL_SERVER_ERROR)) {
return httpResponse.getStatusLine().toString();
} else {
return getStringContent(httpResponse);
}
}

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.

AsyncTask read and return data from URL

I've been having a lot of problems making this code work.
My main activity uses ZXing to scan a barcode, and then I want to take the result of that scan and query my API with it. I know I have to use an AsyncTask to do this, but I've never used one before and I'm having a lot of trouble with it. My goal is to query the API within the AsyncTask, and then update my upcTxt TextView element with the resulting JSON String. What am I supposed to do next in my ReadJSON code?
Here's my main activity code:
public class Barcode extends Activity implements OnClickListener {
private Button scanBtn;
private TextView formatTxt, contentTxt, upcTxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_barcode);
scanBtn = (Button)findViewById(R.id.scan_button);
formatTxt = (TextView)findViewById(R.id.scan_format);
contentTxt = (TextView)findViewById(R.id.scan_content);
upcTxt = (TextView)findViewById(R.id.upc);
scanBtn.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.barcode, menu);
return true;
}
public void onClick(View v){
//respond to clicks
if(v.getId()==R.id.scan_button){
//scan
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
String scanResult = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
formatTxt.setText("FORMAT: " + scanFormat);
contentTxt.setText("CONTENT: " + scanResult);
new ReadJSON().execute(new String[] {scanResult});
} else {
Toast toast = Toast.makeText(getApplicationContext(), "No scan data received!", Toast.LENGTH_LONG);
toast.show();
}
}}
And here is my ReadJSON code:
public class ReadJSON extends AsyncTask<String, Void, Void> {
private String content;
private TextView upcTxt;
private String url;
#Override
protected Void doInBackground(String... scanResult) {
url = "REDACTED";
content = "";
HttpClient Client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url + scanResult[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try {
content = Client.execute(httpget, responseHandler);
// Update upcTxt here
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Thank you in advance.
Update: Whenever I try to run the code on my phone, I can scan the barcode just fine but then the program crashes once it tries to access the URL.
LogCat:
01-18 17:26:44.731: E/AndroidRuntime(24876): at com.peter.barcodetest.ReadJSON.doInBackground(ReadJSON.java:30)
01-18 17:26:44.731: E/AndroidRuntime(24876): at com.peter.barcodetest.ReadJSON.doInBackground(ReadJSON.java:1)
01-18 17:26:46.473: D/CrashAnrDetector(376): processName: com.peter.barcodetest
01-18 17:26:46.473: D/CrashAnrDetector(376): broadcastEvent : com.peter.barcodetest data_app_crash
01-18 17:26:46.913: D/PackageBroadcastService(26662): Received broadcast action=android.intent.action.PACKAGE_REPLACED and uri=com.peter.barcodetest
01-18 17:26:55.122: I/ActivityManager(376): Process com.peter.barcodetest (pid 24876) (adj 13) has died.
I changed your code to this:
Edited ReadJSON only
AsyncTask (edited)
public class ReadJSON extends AsyncTask<String, Integer, String> {
private String content;
private TextView upcTxt;
private String url;
private static final String TAG = "ReadJSON";
String s = "";
Context context;
ReadJSONCallBack callback;
public ReadJSONTask (Context context, ReadJSONCallBack cb) {
super();
this.callback = cb;
this.context = context;
}
#Override
protected String doInBackground(String... scanResult) {
url = "REDACTED";
HttpClient Client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url + scanResult[0]);
try {
HttpResponse response = Client.execute(httpget);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
InputStream in = response.getEntity().getContent();
Log.d(TAG, "Got response");
InputStreamReader inputStreamReader = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
Log.d(TAG, "Content: " + stringBuilder.toString());
return stringBuilder.toString();
// Update upcTxt here
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
protected void onPostExecute(String result) {
callback.setString(s);
}
// method for parsing JSON object
public String parseJSONObject(String output) {
try {
JSONArray jArray = new JSONArray(output);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
String id = jObject.getString("id");
String customer = jObject.getString("name");
String description = jObject.getString("description");
Long time = (Long) jObject.get("timeAsDate");
// do something
}
} catch (JSONException e) {
}
return description;
}
}

Consuming Web Service 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 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[] { "" });
}
});

AsyncTask - onPostExecute is not called

I'm working on one project and I need to call one AsyncTask, but the onPostExecute method is not called.
This is my class:
public class WebService extends AsyncTask<String, String, String> {
private ArrayList<SimpleObserver> listeners;
private int responseCode;
private String message;
private String response;
private String URL;
public WebService() {
listeners = new ArrayList<SimpleObserver>();
}
public void addListener(SimpleObserver obs) {
listeners.add(obs);
}
public void removeListener(SimpleObserver obs) {
listeners.remove(obs);
}
public void notifyListener(String s) {
for (SimpleObserver listener : listeners)
listener.onChange(s);
}
public String getResponse() {
return response;
}
public String getErrorMessage() {
return message;
}
public int getResponseCode() {
return responseCode;
}
#Override
protected void onPreExecute() {
//notifyListener("A calcular");
}
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
HttpParams my_httpParams = new BasicHttpParams();
final String proxyHost = android.net.Proxy.getDefaultHost();
final int proxyPort = android.net.Proxy.getDefaultPort();
if(proxyPort != -1)
{
my_httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, proxyPort));
}
DefaultHttpClient client = new DefaultHttpClient(my_httpParams);
HttpGet httpGet = new HttpGet(url);
Log.d("URL serviço HttpGet", url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
Log.d("RESPOSTA do web service", response);
} catch (Exception e) {
e.printStackTrace();
response = e.getMessage();
Log.e("ERRO de respota", e.getMessage());
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
Log.d("onPostExecute Serviço", result);
notifyListener(result);
}
}
I have created this method:
public void executeService(String param) {
try {
Log.d("Entrar", "no serviço");
s.execute(new String [] {URL+param});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Erro ao aceder ao web service", e.getMessage());
}
}
to call the task.
these are the results of Log
08-28 17:47:21.936: D/URL serviço HttpGet(2055): http://192.168.56.1:8080/pt.Agile21.Acerola.WebService/rest/acerola?id=g;ana#eu.com
08-28 17:47:22.456: D/RESPOSTA do web service(2055): ana;ana#eu.com;pass;0
08-28 17:47:22.456: D/RESPOSTA do web service(2055): ana;ana#eu.com;pass;0
As you can see I have all the results of doInBackground(). :S
Someone can help me to understand which is the problem?
Something that I saw now looking for the Log files.. my onPostExeute method returns when I finish my app on purpose.. it is not normal.. :S can someone help me?

Categories

Resources