POST request from real android device - android

I working on android application which post its location to server. Here's one problem.
When I run this application in genymotion, it succesfully send POST requests to server. However, when I installed on samsung galaxy note, it doesn't send these post requests.
Where can be the problem?
EDIT: I successfully can fetch data from internet by GET request
Code:
class Posting extends AsyncTask<Location, String, String>{
#Override
protected void onPreExecute(){
}
#Override
protected String doInBackground(Location... locations){
RestAdapter restAdapter = new RestAdapter.Builder().setLogLevel(RestAdapter.LogLevel.FULL).setEndpoint(RetrofitClient.API_URL2).build();
RetrofitClient.TestRetro retrofit = restAdapter.create(RetrofitClient.TestRetro.class);
IssdDeviceLog body=new IssdDeviceLog();
body.setDeviceNo("hello from SAMSUNG MAIN ACTIVITY service");
body.setLatitude(new BigDecimal(locations[0].getLatitude()));
body.setLongtitude(new BigDecimal(locations[0].getLongitude()));
Date date= new Date();
body.setDate(date.toString());
Gson gson = new Gson();
String json = gson.toJson(body);
Response response=retrofit.sendLocation(json);
Log.d("status code"," "+response.getStatus());
return null;
}
#Override
protected void onPostExecute(String file_url) {
}
}
With regards

can you put your error if you getting any error or you can use volley library i am sharing this code you can use this for your post request
public class send_data extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(main.this);
mProgressDialog.setCancelable(false);
mProgressDialog.setTitle("please wait...");
mProgressDialog.show();
}
protected String doInBackground(String... args) {
String url = "http://your_url";
try {
ArrayList<BasicNameValuePair> nvp = new ArrayList<BasicNameValuePair>(
1);
nvp.add(new BasicNameValuePair("key for your data","yourdata"));
String str_responsebody = obj_service.executer(url, nvp);
Log.i("responce", str_responsebody + "===");
return str_responsebody;
} catch (Exception e) {
Log.i("error1", "" + e.toString());
return null;
}
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
Log.i("result", result);
mProgressDialog.dismiss();
}
} catch (Exception e) {
Log.e("error2", "" + e.toString());
e.printStackTrace();
mProgressDialog.dismiss();
}
}
}
download volley lib and add in your project. tutorial [link]: http://www.androidhive.info/2014/05/android-working-with-volley-library-1/

Related

Geo location Json data is not displayed

I think i write wrong my code where i try to retrieve geolocation data:
All relevant api keys are added and relevant api enabled...
private class GetCoordinates extends AsyncTask<String, Void, String>
{
ProgressDialog dialog = new ProgressDialog(AroundMeMapsActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Please wait...");
dialog.setCanceledOnTouchOutside(true);
dialog.show();
}
#Override
protected String doInBackground(String... strings) {
String response;
try {
Toast.makeText(AroundMeMapsActivity.this, "!!!!", Toast.LENGTH_SHORT).show();
String address = strings[0];
HttpDataHandler http = new HttpDataHandler();
//String url = String.format("https://maps.googleapis.com/maps/api/geocode/json?adress=%s", address);
String url = String.format("https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=AIzaSyAzSgqQEZS1K1fowxhUnwxl4hMsKMsLlN4", address);
response = http.getHTTPData(url);
return response;
} catch (Exception ex) {
}
return null;
}
#Override
protected void onPostExecute(String s) {
try {
Toast.makeText(AroundMeMapsActivity.this, "????", Toast.LENGTH_SHORT).show();
JSONObject jsonObject=new JSONObject(s);
String lat=((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry")
.getJSONObject("location").get("lat").toString();
String lng=((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry")
.getJSONObject("location").get("lng").toString();
answer_location.setText(String.format("Coordinates: %s / %s",lat,lng));
if(dialog.isShowing())
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I should get lat and lng coordinate, but it is not displayed...
Could you help to check why?

In AsyncTask server's data is not getting on first time in android

I am trying to get data from server using AsyncTask, on first time result not showing, but its working from second time. I seen so many examples but none of them working for me. please see my code below
private void event_load_data_from_server(int id){
AsyncTask<Integer,Void,Void> task = new AsyncTask<Integer, Void, Void>() {
#Override
protected Void doInBackground(Integer... integers) {
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://api.zesteve.com/posteventlist.php?city="+ucl+"&eveid="+eveid+"&id="+integers[0])
.build();
try {
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
JSONObject object =array.getJSONObject(i);
if(object.has("name")){
pname=object.getString("name");
}else{
pname="";
}
if(object.has("timestamp")){
timestamp =object.getString("timestamp");
}else{
timestamp="";
}
if(object.has("id")){
eveid=object.getInt("id");
}else {
eveid=0;
}
if(object.has("address")){
address=object.getString("address");
}else {
address="";
}
if(object.has("thumbnail")){
thumbnail=object.getString("thumbnail");
}else {
thumbnail="";
}
EventPost events = new EventPost(pname, eveid, thumbnail,address,timestamp);
eventPostList.add(events);
}
}catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
System.out.println("End of Catagory");
}
return null;
}
#Override
protected void onPreExecute(){
super.onPreExecute();
progressDialog.setMessage("Events Loading Wait...");
showDialog();
}
#Override
protected void onPostExecute(Void aVoid) {
hideDialog();
adapter.notifyDataSetChanged();
}
};
task.execute(id);
}
Whenever you want to use onPostExecute() method in AsyncTask, just make sure use String or other type instead of Void as result parameter of AsyncTask<x, y, String> where x,y are any data type(Integer,String,etc..).
Therefore, make changes in code as per below:
Make both AsyncTask<...> like this AsyncTask<Integer,Void,String>
Change return type of doInBackground from Void to String
Change return null; with return ""; at last line in doInBackground.
Change onPostExecute(Void aVoid) to onPostExecute(String s) for override function of onpostexecute.
Then try it.
private void event_load_data_from_server(int id){
AsyncTask<Integer,Void,JSONArray> task = new AsyncTask<Integer, Void, JSONArray>() {
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://api.zesteve.com/posteventlist.php?city="+ucl+"&eveid="+eveid+"&id="+integers[0])
.build();
#Override
protected JSONArray doInBackground(Object... integers) {
try {
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
return array;
}catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
System.out.println("End of Catagory");
}
return null;
}
#Override
protected void onPreExecute(){
super.onPreExecute();
progressDialog.setMessage("Events Loading Wait...");
showDialog();
}
#Override
protected void onPostExecute(JSONArray array) {
for (int i=0; i<array.length(); i++){
JSONObject object =array.getJSONObject(i);
if(object.has("name")){
pname=object.getString("name");
}else{
pname="";
}
if(object.has("timestamp")){
timestamp =object.getString("timestamp");
}else{
timestamp="";
}
if(object.has("id")){
eveid=object.getInt("id");
}else {
eveid=0;
}
if(object.has("address")){
address=object.getString("address");
}else {
address="";
}
if(object.has("thumbnail")){
thumbnail=object.getString("thumbnail");
}else {
thumbnail="";
}
EventPost events = new EventPost(pname, eveid, thumbnail,address,timestamp);
eventPostList.add(events);
}
hideDialog();
adapter.notifyDataSetChanged();
}
};
task.execute(id);
}

Implementation of AsyncTask in Android

I have implemented AsyncTask like this in my code. Can you tell me if I used AsyncTask correctly? Thanks.
protected class AsyncTranslator extends AsyncTask<String, JSONObject, String>
{
#Override
protected String doInBackground(String... params) {
String mymeaning = null;
RestAPI api = new RestAPI();
try
{
JSONObject jsonObj = api.GetMeaning(params[0]);
mymeaning = jsonObj.toString();
}
catch (Exception e)
{
Log.d("Error", e.getMessage());
}
return mymeaning ;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(context, "Please wait.", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute(String mymeaning) {
Log.d("onPostExecute", null);
Intent i = new Intent(SendMeaningActivity.this, ShowMeaningActivity.class);
i.putExtra("meaning", mymeaning);
startActivity(i);
}
}
Yes you used it correctly.
Fot API call, think to use library like Retrofit. It will make your life easier.

Which is the correct way to call async task in onCompleted method in facebook 3.0 Request.newMeRequest method

I tried this, but I'm getting WindowLeaked error message after postexecute method is called.
here Is my code:
Request meRequest=Request.newMeRequest(session, new GraphUserCallback()
{
#Override
public void onCompleted(GraphUser user, Response response)
{
if(response.getError()==null)
{
try
{
MyAsyncTask async = new MyAsyncTask ();
async.execute("fbsignup");
} catch (Exception e)
{
Log.v("FB error:::::::::", e.getMessage());
}
}
}
});
meRequest.executeAsync();
This is MyAsyncTask class, When I tried to call Intent without using asynctask it is working fine, so i guess my error is in asynctask only.
private class MyAsyncTask extends AsyncTask<String, Void, Void> {
private ProgressDialog pDialog = null;
private String responseFromServer = null;
private boolean hasExceptionOccured = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... params) {
try
{
// Parse graph user data and check whether user has registered or not.
// If user is not registered mandatory password popup.
ServiceHandler handler = new ServiceHandler();
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
if(params[0].equalsIgnoreCase("fbsignup"))
{
parameters.add(new BasicNameValuePair("email", UserEmailID));
responseFromServer = handler.makeServiceCall(URL, 2, parameters);
}
} catch (Exception e)
{
Log.v("CLassName::::::SignupwithEmail:::::::AsyncTask", e.getMessage());
hasExceptionOccured = true;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog!=null)
{
pDialog.dismiss();
}
try
{
if(responseFromServer.contains("success"))
{
Intent i = new Intent(getActivity(), HomePage.class);
getActivity().startActivity(i);
getActivity().finish();
}
} catch (Exception e)
{
Log.v("Main FRagment FB async::::::", e.getMessage());
}
}
}
hey you can use updated facebook v3.6 sdk. Please download and get some sample app also available inside. Facebook v3.6
user after login session
Session session = Session.getActiveSession();
requestMyAppFacebookFriends(session);
private List<GraphUser> getResults(Response response) {
GraphMultiResult multiResult = response
.getGraphObjectAs(GraphMultiResult.class);
GraphObjectList<GraphObject> data = multiResult.getData();
return data.castToListOf(GraphUser.class);
}
private void requestMyAppFacebookFriends(Session session) {
Request friendsRequest = createRequest(session);
friendsRequest.setCallback(new Request.Callback() {
#Override
public void onCompleted(Response response) {
//List<GraphUser> friends = getResults(response);
//Log.e("RESULT : ", "#"+friends.size());
// TODO: your code here
}
});
friendsRequest.executeAsync();
}
private Request createRequest(Session session) {
Request request = Request.newGraphPathRequest(session, "me/friends", null);
Set<String> fields = new HashSet<String>();
String[] requiredFields = new String[] { "id", "name", "picture","installed" };
fields.addAll(Arrays.asList(requiredFields));
Bundle parameters = request.getParameters();
parameters.putString("fields", TextUtils.join(",", fields));
request.setParameters(parameters);
return request;
}
I added
Looper.loop();
after
async.execute("fbsignup");
This solved my problem.

ProcessDialog is not appearing properly?

This is my function that is in LoginActivity.java.So onclick of button i am calling this function.
public void postHttpRequest(String userId,String pass,TextView error){
RequestClient reqClient = new RequestClient(LoginActivity.this);
String AppResponse = null;
try {
url = "myurl";
Log.d("URL", url);
AppResponse = reqClient.execute().get();
String status = ValidateLoginStatus.checkLoginStatus(AppResponse);
Log.d("Status recived", status);
if(status.equals("200")){
saveInformation(userId,pass);
startingActivity(HOST_URL);
}else{
error.setText("Incorrect UserName or Password");
}
} catch (Exception e) {
Log.e("Exception Occured", "Exception is "+e.getMessage());
}
}
From this function i am calling a AsynkTask for Http Communication.So onclick of button when i am geeting the response then my processDialog in opening just for one sec.I want as i click the buttoon my processDialog should get open utill i got the response
public class RequestClient extends AsyncTask<String, Void, String>{
ProgressDialog pDialog;
Context context;
public RequestClient(Context c) {
context = c;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Authenticating user...");
pDialog.show();
}
#Override
protected String doInBackground(String... aurl){
String responseString="";
DefaultHttpClient httpClient=new DefaultHttpClient();
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(LoginActivity.url);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
responseString = EntityUtils.toString(resEntityGet);
Log.i("GET RESPONSE", responseString);
}
} catch (Exception e) {
Log.d("ANDRO_ASYNC_ERROR", "Error is "+e.toString());
}
Log.d("ANDRO_ASYNC_ERROR", responseString);
httpClient.getConnectionManager().shutdown();
return responseString;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
if(pDialog!=null)
pDialog.dismiss();
}
}
So please suggest me what changes i have to make so that processDialog should display properly in the center of the device
//add style in your progressbialog
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setMessage("Authenticating user...");
if (pDialog != null && !pDialog.isShowing()) {
pDialog.show();
}
}
AsyncTask return value only after using get() method
Drawing from the above link
Calling the get() method of AsyncTask will block the main thread and wait for the result to be returned. This effectively makes using an AsyncTask become a synchronous operation in which case there's no point in using an AsyncTask.
The only reason I can think of to use the get() method would be from a thread other than the main (UI) thread although I can't think of many reasons to do that.
On Button click
RequestClient reqClient = new RequestClient(LoginActivity.this,new TheInterface() {
#Override
public void theMethod(String result) {
Log.i("Result =",result);
}
});
reqClient.execute(url); // no get(). pass url to doInBackground()
In your activity class
public interface TheInterface {
public void theMethod(String result);
}
}
AsyncTask
public class RequestClient extends AsyncTask<String, Void, String>{
ProgressDialog pDialog;
Context context;
TheInterface listener;
public RequestClient(Context c,TheInterface listen) {
context = c;
listener = listen;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Authenticating user...");
pDialog.show();
}
#Override
protected String doInBackground(String... aurl){
String responseString="";
HttpClient client;
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(aurl[0]); // url
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
responseString = EntityUtils.toString(resEntityGet);
Log.i("GET RESPONSE", responseString);
}
} catch (Exception e) {
Log.d("ANDRO_ASYNC_ERROR", "Error is "+e.toString());
}
Log.d("ANDRO_ASYNC_ERROR", responseString);
client.getConnectionManager().shutdown();
return responseString;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
pDialog.dismiss();
if (listener != null)
{
listener.theMethod(result);
}
}
}
It seems that your button code is not correct, because it's async, but you are trying to use it as standart sync code.
Try to move this code into onPostExecute:
String status = ValidateLoginStatus.checkLoginStatus(response);
Log.d("Status recived", status);
if(status.equals("200")){
saveInformation(userId,pass);
startingActivity(HOST_URL);
}else{
error.setText("Incorrect UserName or Password");
}
and make this button click code:
public void postHttpRequest(String userId,String pass,TextView error){
RequestClient reqClient = new RequestClient(LoginActivity.this);
String AppResponse = null;
try {
url = "myurl";
Log.d("URL", url);
reqClient.execute();
} catch (Exception e) {
Log.e("Exception Occured", "Exception is "+e.getMessage());
}
}

Categories

Resources