My post request code as follows
When post request to the server it reach twice in to the server
and i am sure call httpRequest once.When i call once the request reach server twice or thrise;
private void invokePostOrderRestService(
final RestPostDataCallback<Order> callback,
final RequestOrder requestOrder) {
String URL = BASE_URL + "postOrder";
Log.e("post ordercccccc", "orderPosted");
JSONObject jsonObject = convertOrderRequestToJson(requestOrder);
if (jsonObject != null) {
OrderProApplication
.getContext()
.getRestClient()
.postJsonObject(URL, jsonObject,
new ResponseListener<JSONObject>() {
#Override
public void onSuccess(JSONObject response) {
// TODO Auto-generated method stub
Log.e("Order Post Success","Post Order Successssssssssssssssss");
String status = "";
try {
status = response.getString("status");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (status.equals("OK")) {
callback.onRestPostDataCompleted(
ResultCode.RESULT_OK, null);
} else {
callback.onRestPostDataCompleted(
ResultCode.RESULT_FAIL, null);
}
}
#Override
public void onRestError(RestError error) {
// TODO Auto-generated method stub
Log.e("Order Post Failed","Post Order failedddddddddddddddddddd");
i = i + 1;
callback.onRestPostDataCompleted(
ResultCode.RESULT_FAIL, null);
}
});
} else {
callback.onRestPostDataCompleted(ResultCode.RESULT_FAIL, null);
}
}
And am pretty sure my url is correct.
Thanks:).
Most likely your method is being called twice. Check where you are calling out the method - this might be occurred thanks to misunderstanding of Activity/Fragment lifecycle.
Put a print in the beginning of your invoke method and check, if it prints out twice.
Related
I would like to connect to Api link which can have multiple pages and store all the JSON values as a object in a list.
Here is a Api link example with multiple pages, note the number as last being the page you're on.
Problems that I have so far encountered and unable to solve. Return type of doInBackground as constructor class apiRootObject and how to deserialize the Json result, its logical why it doesnt work since I its extended from AsyncTask but i do not know how to work around this problem or what other road to take.
This is the code I have so far.
Calling the initial function in my Activity.java
String userSearchRequest = search_activity_data.getString("userSearchRequest");
String URL = "http://www.gw2spidy.com/api/v0.9/json/item-search/" + userSearchRequest + "/";
//Api link example with multiple pages = "http://www.gw2spidy.com/api/v0.9/json/item-search/Iron"
AsyncFetch parkingInfoFetch = new AsyncFetch(this);
parkingInfoFetch.setOnResponse(this);
parkingInfoFetch.execute(URL);
My AsyncFetch.java class which is called from aboves code
public class AsyncFetch extends AsyncTask {
public AsyncFetch(Context context) {
this.context = context;
}
private Context context;
private JSONObject jsonObject;
private onResponse onResponse;
public void setOnResponse(onResponse onResponse) {
this.onResponse = onResponse;
}
#Override
protected apiRootObject doInBackground(String... params) { //Incompatible return type
// TODO Auto-generated method stub
apiRootObject apiRootObject = null;
apiRootObject tempApiRootObject = null;
int page = 0;
try {
do {
HttpGet get = new HttpGet(params[0] + page);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
//jsonObject = new JSONObject(result);
tempApiRootObject = /*Deserialize into <RootObject>(result)*/
if (apiRootObject == null){
apiRootObject = tempApiRootObject;
}
else{
apiRootObject.results.addAll(tempApiRootObject.results);
apiRootObject.count += tempApiRootObject.count;
}
page++;
}
while(tempApiRootObject.last_page != tempApiRootObject.page);
} 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();
}
return apiRootObject;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
this.onResponse.onResponse(result);
}
public interface onResponse {
public void onResponse(JSONObject object);
}
}
And back in the activity.java everything is being added to the list in the onResponse function.
public void onResponse(JSONObject object) {//Still expecting a JSONObject while I am changing this return type
Log.i("gw2Log", object.toString());
apiRootObject resultClass = new apiRootObject();
try {
resultClass.setCount(object.getInt("count"));
resultClass.setPage(object.getInt("page"));
resultClass.setLast_page(object.getInt("last_page"));
resultClass.setTotal(object.getInt("total"));
JSONArray list = new JSONArray(object.getString("results"));
for (int i = 0; i < resultClass.getCount(); i++) {
JSONObject resultsObject = list.getJSONObject(i);
apiResults temp = new apiResults();
temp.setData_id(resultsObject
.getInt("data_id"));
temp.setName(resultsObject
.getString("name"));
temp.setRarity(resultsObject
.getInt("rarity"));
temp.setRestriction_level(resultsObject
.getInt("restriction_level"));
temp.setImg(resultsObject
.getString("img"));
temp.setType_id(resultsObject
.getInt("type_id"));
temp.setSub_type_id(resultsObject
.getInt("sub_type_id"));
temp.setPrice_last_changed(resultsObject
.getString("price_last_changed"));
temp.setMax_offer_unit_price(resultsObject
.getInt("max_offer_unit_price"));
temp.setMin_sale_unit_price(resultsObject
.getInt("min_sale_unit_price"));
temp.setOffer_availability(resultsObject
.getInt("offer_availability"));
temp.setSale_availability(resultsObject
.getInt("sale_availability"));
temp.setSale_price_change_last_hour(resultsObject
.getInt("sale_price_change_last_hour"));
temp.setOffer_price_change_last_hour(resultsObject
.getInt("offer_price_change_last_hour"));
resultClass.addObject(temp);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i = 0; i < resultClass.count; i++) {
Log.i("gw2Log", resultClass.getObject(i).name);
}
}
Ofcourse there are also 2 constructor classes apiResults and apiRootObject.
EDIT:
If you take the link on the top of the question you get a lot of JSON values returned, every page can have 50 of these results if there are more a new page is created.
I want to connect to this Api link, and retrieve all values that are being returned. If there are multiple pages it needs to loop through all existing pages and add these JSON values to the exact same list.
I have asked a similiar question before in c# and here I've got it working but I now need the exact same in Android Java. For android java i was told i need to use AsyncTask in order to make a connection and do all of this in the background of the application. If there is a better or easier way, please enlighten me.
It might not be too late to use Retrofit .
gson is the easiest way to convert json into a class.
//your class
public class Foo {
public final int bar;
public final String bazz;
public foo(int bar, String bazz) {
this.bar = bar;
this.bazz = bazz;
}
}
//your json
{ "bar" : 4, "bazz" : "interesting content" }
//your gson call
Gson gson = new Gson();
Foo foo = gson.fromJson(json, Foo.class);
you can even do nested objects and it will deserialize them all.
public class FooHaver {
public final String prop1;
public final Foo foo;
}
//your json
{ "prop1" : "more content", "foo" : { "bar" : 4, "bazz" : "even more content" } }
you can also do json arrays as arrays or as a java List of any type you want
try this
#Override
protected apiRootObject doInBackground(String... params) { //Incompatible return type
// TODO Auto-generated method stub
apiRootObject apiRootObject = null;
apiRootObject tempApiRootObject = null;
List<apiRootObject> myList=new ArrayList<apiRootObject>();
int page = 0;
try {
do {
HttpGet get = new HttpGet(params[0] + page);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
jsonObject = new JSONObject(result);
//handling json exceptions
if(jsonObejct!=null && !jsonObject.isNull("page")&&..){
tempApiRootObject.page=jsonObject.getString("page");
tempApiRootObject.last_page=jsonObject.getString("last_page");
//here we put the results in the tempsApiRootObject
JSONArray ja = jsonObject.getJSONArray("results");
for (int i = 0; i < ja.length(); i++) {
JSONObject c = ja.getJSONObject(i);//this is an item
int data_id= c.getInt("data_id");
String name= c.getString("name");
//the other values
//here you add them in your arraylist of <apiResults> (*)
}
//and here we add the arraylist in (*) to tempApiRootObject
myList.add(tempApiRootObject);
/* if (apiRootObject == null){
apiRootObject = tempApiRootObject;
}
else{
apiRootObject.results.addAll(tempApiRootObject.results);
apiRootObject.count += tempApiRootObject.count;
}*/ i didn't understand this
}page++;
}
while(tempApiRootObject.last_page != tempApiRootObject.page);
} 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();
}
return myList// apiRootObject;
}
and this
public void onResponse(List<apiRootObject> myList) {
for(int i=0;i++;i<myList.size()){
apiRootObject resultClass =myList.get(i);
//do something
}
}
In the AsyncTask android. When calling a method in another class gets an exception which equals to null in the doInBackGround() task.
Even the hard coded inside the rest.request(url, method, json) doesn't work
protected JSONArray doInBackground(Void... arg0) {
try {
return rest.request(url, method, json); // <-- returns json array
} catch (Exception e) {
this.e = e;
}
return null; // <--- returning this null
}
Other things are like this,
private class doRequest extends AsyncTask<Void, JSONArray, JSONArray>
protected void onPostExecute(JSONArray data)
/*rest client class*/
public class AndrestClient {
// The client to use for requests
DefaultHttpClient client = new DefaultHttpClient();
public JSONArray request(String url, String method, String json) throws RESTException {
if (method.matches("GET")) {
return get(url);
} else if (method.matches("POST")) {
return post(url, json);
} else if (method.matches("PUT")) {
//return put(url, data);
} else if (method.matches("DELETE")) {
//return delete(url);
}
throw new RESTException("Error! Incorrect method provided: " + method);
}
public JSONArray get(String url) throws RESTException {
String jsonjr = "['Chanuthi','Damsith','Dunili','Isath','Minuka','Uvin','Vidath']";
JSONArray jsonAraay = null;
try {
jsonAraay = new JSONArray(jsonjr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonAraay;
}
}
The exception I got is e=null. All the other things work properly. When I am hard coding the result inside in the doInBackGround it works properly. Also the rest client get method returns the exact thing.
It appears you're using AsyncTask improperly. Firstly, you must subclass/nest your AsyncTask as per the Android documentation:
http://developer.android.com/reference/android/os/AsyncTask.html
In addition, you should follow the fundamental rules for calling methods of an outter class from a nested class.
There are some alternatives, like:
Create the AndrestClient object in onPreExecute() of the AsyncTask
Pass the AndrestClient object to the doInBackground as a parameter, then call its methods by doing something like this in the outter class:
doRequest.execute(rest);
I'm trying to call a web service I made using Jersey.
I tested the services by calling them from a console java app, and its working perfectly fine.
When calling from Android, it first gave me android.os.NetworkOnMainThreadException, I searched and found out that i should use AsyncTask to solve that,
the following code crashes when "response.getEntity(String.class)" is called
while calling a get service, if i return the status ( response.getStatus()) instead of getEntity, it works fine. But the same thing doesnt work in case of a post request. getEntity() crashes on both
public String postTest(String arg){
Log.d("Service", "postRegister1");
client = Client.create();
WebResource service=client.resource(getBaseURI());
Log.d("Service", "postRegister2");
Form form = new Form();
form.add("arg", "lol");
int status;
ClientResponse response=null;
try{
response = service.path("test").get(ClientResponse.class);
//post
// response = service.path("post").path("test").post(ClientResponse.class,from);
Log.d("Service", "postRegister3");
status = response.getStatus();
//comment out the following if statement and the code will work perfectly fine, returning the stats
if(status == 200){
return response.getEntity(String.class);
}
return String.valueOf(response.getStatus());
}
catch(ClientHandlerException e){
Log.d("Exception1",e.getMessage()+ " ");
}
catch(UniformInterfaceException e){
Log.d("Exception2",e.getMessage()+ " ");
}
catch(Exception e){
Log.d("Exception3",e.getMessage()+ " ");
}
return "exception";
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Log.d("doInback", params[0]);
return postTest(params[0]);
}
the code above code is part of the class:
public class Service extends AsyncTask<String, Void, String>{
and is called like:
try {
alert(new Service().execute("lol").get(),view);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
the alert method just displays an alert.
Solved by using a library for implementing Async Http
client.
The tutorial which i followed can be found here.
My Android App needs some basic data to run. This data is downloaded from a server using JSON. In Xcode I simply used the sendsynchronous request but I noticed that Eclipse gives me a error when i do networking on the main ui.
Found a lot of stuff on asynctask but i want my app to wait till the required data is downloaded (synchronous?).
I tried using asynctask .execute().get() and setting the variables in onPostExecute but when I return the variable I get a NullPointerException. Does someone know how to make this work? I really need this data before the app can run so I want my app to wait till the data is downloaded.
MainActivity calls this:
SingletonClass appIDSingleton = SingletonClass.getInstance();
this.ID = appIDSingleton.getAppID();
Singleton Class:
public String getAppID() {
try {
new DownloadAppID().execute(APP_ID_URL).get(5000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return AppID; //AppID is still NULL (because the download isnt finished yet?)
}
private class DownloadAppID extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new 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;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
System.out.println(result);
AppID = result;
}
}
You need to understand that your getAppID method can't return a result that is going to be computed asynchronously.
You could for instance provide a listener to your async task in order to notify when app ID is available:
SingletonClass appIDSingleton = SingletonClass.getInstance();
appIDSingleton.getAppID(new AppIdDownloadListener() {
#Override
public void appIDAvailable(String appId) {
this.ID = appId;
}
});
public void getAppID(AppIdDownloadListener listener) {
try {
new DownloadAppID(listener).execute(APP_ID_URL).get(5000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public interface AppIdDownloadListener {
public void appIDAvailable(String appId);
}
private class DownloadAppID extends AsyncTask<String, Void, String> {
private AppIdDownloadListener listener;
public DownloadAppID(AppIdDownloadListener listener) {
this.listener = listener;
}
#Override
protected String doInBackground(String... params) {
/* Your stuff here */
}
#Override
protected void onPostExecute(String result) {
System.out.println(result);
listener.appIDAvailable(result);
}
}
I am trying to write a Http API in android. I am using a AsyncTask to run the calls to my web service.I am not interested in updating the UI, instead all I want is the data to use in my application logic. This is what I have so far:
public class DataManager{
public static String result;
public DataManager ()
{
}
public String get ()
{
User user = new User ();
user.execute("http://someuri/service/users/id/21001");
return user.getResult();
}
}
public class User extends AsyncTask <String,Void,String>{
private String result;
#Override
protected String doInBackground(String... arg0)
{
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet (arg0[0]);
try
{
HttpResponse response = client.execute (get);
if (response.getStatusLine().getStatusCode () == 200)
{
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity);
}
}
catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
this.result = result;
}
public String getResult ()
{
return result;
}
}
I want a typical call to be:
DataManager manager = new DataManager ();
String value = manager.get ();
But when I run this I get back null. What is causing this and how can I refactor this code to get the desired behavior.
The whole idea of a thread is that it runs concurrently. Basically, here's what you're doing:
User user = new User (); // Create User object
user.execute("http://someuri/service/users/id/21001"); // Start thread
return user.getResult(); // Return thread result
However, there is no time for the thread to run between "start" and "return result".
I would suggest using some kind of callback; first, make get() return void, and remove the return statement. Then, you pass in some object which implements YourCallback, and then call onCallback(result) from within onPostExecute().
Your calling code would then look like this:
DataManager x = new DataManager();
x.get(new YourCallback() {
public void onCallback(String result) {
// ...
}
});
There is a much fuller example in this fantastic answer.