Final object losing attribute value after function call - java

I am trying to properly handle Volley responses in my Android application, which loads some items from a database. Volley functions are encapsulated in the WebRequester class:
public class WebRequester extends Application {
public static final String TAG = WebRequester.class.getSimpleName();
private RequestQueue mRequestQueue;
private static WebRequester mInstance;
public WebRequester() {
mInstance = this;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public static synchronized WebRequester getInstance() {
return mInstance;
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
/* ... */
}
Another class, ItemsController, centralizes the requests to be created. In order to get the response code, I created a nested class, VolleyCallback, and set its attribute responseCode inside an overriden parseNetworkResponse() call:
public class FeedItemsController extends Application {
private String URL_GET_FEED_ITEMS = /* My URL */;
private static final String TAG = FeedItemsController.class.getSimpleName();
private ArrayList<FeedItem> feedItems;
public class VolleyRequestCallback {
public int responseCode;
public int getResponseCode() {
return responseCode;
}
public void setResponseCode(int responseCode) {
this.responseCode = responseCode;
}
}
public void loadItems() {
final VolleyRequestCallback callback = new VolleyRequestCallback();
if (feedItems == null) {
feedItems = new ArrayList<>();
Cache cache = WebRequester.getInstance().getRequestQueue().getCache();
Cache.Entry entry = cache.get(URL_GET_FEED_ITEMS);
if (entry != null) {
try {
String data = new String(entry.data, "UTF-8");
parseJsonFeed(new JSONObject(data));
} catch (JSONException | IOException e) {
e.printStackTrace();
}
}
else {
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET, URL_GET_FEED_ITEMS, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
parseJsonFeed(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}
) {
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
callback.setResponseCode(response.statusCode);
System.out.println("Code 1 = " + response.statusCode);
return super.parseNetworkResponse(response);
}
};
WebRequester.getInstance().addToRequestQueue(jsonReq);
}
}
System.out.println("Code 2 = " + callback.getResponseCode());
}
/* ... */
}
Then method loadItems() is called from another class. The issue is - when it enters the parseNetworkResponse() method, the resultCode is correctly set to, let's say, 200. However, when I try to reuse it outside the request overriding, it's 0 again:
Code 1 = 200
Code 2 = 0
It might be a bad implementation of a response handling, but my main question is why is the object attribute changed?
Thanks in advance

It turned out to be a not exciting bug. The call to parseNetworkResponse is asynchronous, meaning that when the first print is performed, the server had not responded yet.

Related

How to implement a new Dialog error in Android Studo (JAVA)

So I want to add a dialog message to my app. There already an option for other types of error's. I just want to add an error for when there's no mobile data and WiFi. It's an older app, so it's taking me a bit more to understand, but here's what I got.
So here is the status code for the errors. Not sure if the codes are random or not (I didn't make this project)
public class StatusCodeUtil {
public static final int AWS_GATEWAY_ERROR = 1;
public static final int URL_INVALID = 2;
public static final int INTERNAL_SERVER_ERROR = 14;
public static final int ENDPOINT_INFO_STORAGE_INCOMPLETE = 7;
public static final int NO_PERMISSION_GET_DEVICE_ID = 8;
public static final int INVALID_API_FUNCTION = 18;
public static final int INVALID_HTTP_STATUS_CODE = -1;
public static final int NO_NETWORK_ERROR = 3; <- This is the status code I want to work
}
Here is the Callback for the errors
public abstract class ApiCallBack<T> implements Callback<ApiResponse<T>> {
private ParabitSDKBeaconApplication application;
public ApiCallBack(ParabitSDKBeaconApplication application) {
this.application = application;
}
#Override
public void onResponse(Call<ApiResponse<T>> call, Response<ApiResponse<T>> response) {
Long roundTripTime = getRoundTripTime(response);
if (response.isSuccessful()) {
ApiResponse<T> responseBody = response.body();
onApiResponse(responseBody.getMessage(), response.code(), responseBody.getData());
} else {
/**
* error level 1 (HTTP client or gateway error)
* */
String errorBodyJson = getErrorBodyStr(response);
// can not user ApiResponse<T> to catch the json here
// will lead to exception: java.lang.AssertionError: illegal type variable reference
// no good way to solve this (Gson's problem)
ApiErrorResponse errorBody = GsonUtil.jsonStrToObject(errorBodyJson,
new TypeToken<ApiErrorResponse>(){});
if (errorBody.getMessage().equalsIgnoreCase("forbidden")) { // x-api-key invalid
if (getLogControlManager().isLog()) {
Log.e(PARABIT_SDK_LOG, "AWS Gateway Error: " + errorBody.getMessage());
}
onError(new ApiErrorCodeInfo(AWS_GATEWAY_ERROR, response.code(),
errorBody.getMessage()));
} else if (errorBody.getMessage().equalsIgnoreCase(
"missing authentication token")) {
if (getLogControlManager().isLog()) {
Log.e(PARABIT_SDK_LOG, "AWS Gateway Error: " + errorBody.getMessage());
}
onError(new ApiErrorCodeInfo(INVALID_API_FUNCTION, response.code(),
errorBody.getMessage()));
} else {
if (getLogControlManager().isLog()) {
Log.e(PARABIT_SDK_LOG, "Other Error Response: " + errorBody.getMessage());
}
// should never happen for now
onError(new ApiErrorCodeInfo(INTERNAL_SERVER_ERROR, response.code(),
errorBody.getMessage()));
}
}
}
#Override
public void onFailure(Call<ApiResponse<T>> call, Throwable t) {
/**
* error level 1 (HTTP client or gateway error)
* */
if (t instanceof UnknownHostException) { // host of end point is unknown
if (getLogControlManager().isLog()) {
Log.e(PARABIT_SDK_LOG, "onFailure: " + "UnknownHostException");
}
onError(new ApiErrorCodeInfo(URL_INVALID, t.getLocalizedMessage()));
} else {
if (getLogControlManager().isLog()) {
Log.e(PARABIT_SDK_LOG, "onFailure: " + t.getLocalizedMessage());
}
onError(new ApiErrorCodeInfo(INTERNAL_SERVER_ERROR,
t.getLocalizedMessage()));
}
}
public static<T> String getErrorBodyStr(Response<ApiResponse<T>> response) {
if (response.errorBody() == null) {
return "";
}
String errorBodyStr = "";
try {
errorBodyStr = response.errorBody().string();
} catch (IOException e) {
e.printStackTrace();
}
return errorBodyStr;
}
protected Long getRoundTripTime(Response response) {
Long roundTripTime = response.raw().sentRequestAtMillis()
- response.raw().receivedResponseAtMillis();
return roundTripTime;
}
// public abstract void onSuccess(String successMsg, List<T> data);
public abstract void onApiResponse(String ApiMsg, int httpStatusCode, List<T> data);
public abstract void onError(ApiErrorCodeInfo apiErrorCodeInfo);
protected LogControlManager getLogControlManager() {
return SdkApplicationInstance.getSdkLogControlManager(application);
}
}
The code in the Activity that controls which error is shown
loginViewModel.loginStatusInfo.observe(this, loginStatusInfo -> {
if (loginStatusInfo.getStatus() == API_SUCCESS_STATUS){
hideLoadingDialog();
startHomeActivity();
}else if (loginStatusInfo.getStatus() == INTERNAL_SERVER_ERROR) {
hideLoadingDialog();
loginErrorDialog(getString(R.string.fail_to_login_server_error));
}else if(loginStatusInfo.getStatus() == NO_NETWORK_ERROR){<- I added this else if
hideLoadingDialog();
loginErrorDialog(getString(R.string.network_require_msg));
}
else {
hideLoadingDialog();
loginErrorDialog(loginStatusInfo.getMessage());
}
});
Any help will be appreciated, Thank you.
So I actually called ConectivityManager on the loginViewModel.loginStatusInfo method and it worked.
loginViewModel.loginStatusInfo.observe(this, loginStatusInfo -> {
if (loginStatusInfo.getStatus() == API_SUCCESS_STATUS){
hideLoadingDialog();
startHomeActivity();
}else if (loginStatusInfo.getStatus() == INTERNAL_SERVER_ERROR) {
hideLoadingDialog();
loginErrorDialog(getString(R.string.fail_to_login_server_error));
}else if(ConnectivityManager.TYPE_MOBILE == 0){
hideLoadingDialog();
networkErrorDialog(getString(R.string.network_require_msg));
}
else {
hideLoadingDialog();
loginErrorDialog(loginStatusInfo.getMessage());
}
});

Best way to use retrofit response in several activies

I have a function searchForTrips() which sends an API request and fetch some response in following way.
private void searchForTrips(){
int departurePortId = PORT_ID_LIST.get(departurePort);
int returnPortId = PORT_ID_LIST.get(returnPort);
int pax= Integer.parseInt(noOfPassengers);
String departureDatePARSED = DEPARTURE_DATE_VALUES.get(departureDate);
String returnDatePARSED = RETURN_DATE_VALUES.get(departureDate);
Call<TripSearchResponse> call = apiService.searchAvailableTrips(TripType,departurePortId,returnPortId,departureDatePARSED,returnDatePARSED,pax);
call.enqueue(new Callback<TripSearchResponse>() {
#Override
public void onResponse(Call<TripSearchResponse> call, Response<TripSearchResponse> response) {
int statusCode = response.code();
switch(statusCode){
case 200:
default:
Snackbar.make(findViewById(android.R.id.content),"Error loading data. Network Error.", Snackbar.LENGTH_LONG).show();
break;
}
}
#Override
public void onFailure(Call<TripSearchResponse> call, Throwable t) {
Log.i(TAG, t.getMessage());
Snackbar.make(findViewById(android.R.id.content),"Error loading data. Network Error.", Snackbar.LENGTH_LONG).show();
}
});
}
The purpose is to make this callback function reusable so I can call it from several activities and get requested data as I need. What is the best way to implement this?
try this way, its dynamic way and easy to use:
Create Retforit Interface:
public interface ApiEndpointInterface {
#Headers("Content-Type: application/json")
#POST(Constants.SERVICE_SEARCH_TRIP)
Call<JsonObject> searchForTrip(#Body TripRequest objTripRequest);
}
Create Retrofit Class:
public class AppEndPoint {
private static Retrofit objRetrofit;
public static ApiEndpointInterface getClient() {
if (objRetrofit == null){
objRetrofit = new Retrofit.Builder()
.baseUrl(Constants.SERVER_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return objRetrofit.create(ApiEndpointInterface.class);
}
}
Create this helper Classes/Interfaces to hold web service callback:
public enum ResponseState {
SUCCESS,
FAILURE,
NO_CONNECTION
}
public enum RequestType {
SEARCH_FOR_TRIP // add name for each web service
}
public class Response {
public ResponseState state;
public boolean hasError;
public RequestType requestType;
public JsonObject result;
}
public interface RestRequestInterface {
void Response(Response response);
Context getContext();
}
public class ResponseHolder { used to hold the Json response could be changed as your response
#SerializedName("is_successful")
#Expose
private boolean isSuccessful;
#SerializedName("error_message")
#Expose
private String errorMessage;
public boolean isSuccessful() {
return isSuccessful;
}
public void setSuccessful(boolean successful) {
isSuccessful = successful;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
public class AppClient {
private static ApiEndpointInterface objApiEndpointInterface;
private static Response objResponse;
private static Call<JsonObject> objCall;
// implement new method like below for each new web service
public static void searchForTrip(TripRequest objTripRequest, RestRequestInterface objRestRequestInterface) {
objResponse = new Response();
objResponse.state = ResponseState.FAILURE;
objResponse.hasError = true;
objResponse.requestType = RequestType.SEARCH_FOR_TRIP; // set type of the service from helper interface
objApiEndpointInterface = AppEndPoint.getClient();
objCall = objApiEndpointInterface.searchForTrip(objTripRequest);
handleCallBack(objRestRequestInterface);
}
private static void handleCallBack(final RestRequestInterface objRestRequestInterface) {
objCall.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, retrofit2.Response<JsonObject> response) {
try {
ResponseHolder objResponseHolder = new Gson().fromJson(response.body(), ResponseHolder.class);
if (objResponseHolder.isSuccessful()) {
objResponse.state = ResponseState.SUCCESS;
objResponse.hasError = false;
objResponse.result = response.body();
} else {
objResponse.errorMessage = objResponseHolder.getErrorMessage();
}
objRestRequestInterface.Response(objResponse);
} catch (Exception objException) {
objResponse.errorMessage = objRestRequestInterface.getContext().getString(R.string.server_error);
objRestRequestInterface.Response(objResponse);
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable objThrowable) {
String errorMessage = "";
if (objThrowable instanceof IOException) {
errorMessage = objRestRequestInterface.getContext().getString(R.string.no_connection_error);
} else {
errorMessage = objRestRequestInterface.getContext().getString(R.string.server_error);
}
objResponse.errorMessage = errorMessage;
objRestRequestInterface.Response(objResponse);
}
});
}
}
then go to your activity of fragment and make the call like this:
public class MainActivity extends AppCompatActivity implements RestRequestInterface {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize ids
// prepare to call web service
// 1.Initialize your object to be sent over web service
TripRequest objTripRequest = new TripRequest();
objTripRequest.id = 1;
// 2.Show loader
// 3.Make the call
AppClient.searchForTrip(objTripRequest, this);
}
#Override
public void Response(Response response) {
// hide loader
try {
if (response.state == ResponseState.SUCCESS && !response.hasError) {
// check the type of web service
if (response.requestType == RequestType.SEARCH_FOR_TRIP) {
// acces the return here from response.result
}
} else {
String errorMsg = response.hasError ? response.errorMessage : getString(R.string.no_connection_error);
// show the error to the user
}
} catch (Exception objException) {
// show the error to the user
}
}
#Override
public Context getContext() {
// do not forgit set the context here
// if fragment replace with getAcitvity();
return this;
}
}

Whats the Best Practice to call a method out of a Callback-Response?

I'm using an asyncronus XML-RPC-Client (https://github.com/gturri/aXMLRPC) in my Project and wrote some methods using the asyncronous Callback-Methods of this Client like this this:
public void xmlRpcMethod(final Object callbackSync) {
XMLRPCCallback listener = new XMLRPCCallback() {
public void onResponse(long id, final Object result) {
// Do something
if (callbackSync != null) {
synchronized (callbackSync) {
callbackSync.notify();
}
}
}
public void onError(long id, final XMLRPCException error) {
// Do something
if (callbackSync != null) {
synchronized (callbackSync) {
callbackSync.notify();
}
}
}
public void onServerError(long id, final XMLRPCServerException error) {
Log.e(TAG, error.getMessage());
if (callbackSync != null) {
synchronized (callbackSync) {
callbackSync.notifyAll();
}
}
}
};
XMLRPCClient client = new XMLRPCClient("<url>");
long id = client.callAsync(listener, "<method>");
}
In other methods I like to call this method (here "xmlRpcMethod") and wait until it finished. I wrote methods like this:
public void testMethod(){
Object sync = new Object();
xmlRpcMethod(sync);
synchronized (sync){
try{
sync.wait();
}catch(Interrupted Exception e){
e.printStackTrace();
}
}
// Do something after xmlRcpFinished
}
But this way of waiting and synchronizing get's ugly when the projects grows larger and I need to wait for many requests to finish.
So is this the only possible / best way? Or does someone knows a better solution?
My first shot to create blocking RPC calls would be:
// Little helper class:
class RPCResult<T>{
private final T result;
private final Exception ex;
private final long id;
public RPCResult( long id, T result, Exception ex ){
// TODO set fields
}
// TODO getters
public boolean hasError(){ return null != this.ex; }
}
public Object xmlRpcMethod() {
final BlockingQueue<RPCResult> pipe = new ArrayBlockingQueue<RPCResult>(1);
XMLRPCCallback listener = new XMLRPCCallback() {
public void onResponse(long id, final Object result) {
// Do something
pipe.put( new RPCResult<Object>(id, result, null) );
}
public void onError(long id, final XMLRPCException error) {
// Do something
pipe.put( new RPCResult<Object>(id, null, error) );
}
public void onServerError(long id, final XMLRPCServerException error) {
Log.e(TAG, error.getMessage());
pipe.put(new RPCResult<Object>(id, null, error));
}
};
XMLRPCClient client = new XMLRPCClient("<url>");
long id = client.callAsync(listener, "<method>");
RPCResult result = pipe.take(); // blocks until there is an element available
// TODO: catch and handle InterruptedException!
if( result.hasError() ) throw result.getError(); // Relay Exceptions - do not swallow them!
return result.getResult();
}
Client:
public void testMethod(){
Object result = xmlRpcMethod(); // blocks until result is available or throws exception
}
Next step would be to make a strongly typed version public T xmlRpcMethod().

How to create a proper Volley Listener for cross class Volley method calling

I aim to call Volley from another class in, a very succinct, modular way ie:
VolleyListener newListener = new VolleyListener();
VolleySingleton.getsInstance().somePostRequestReturningString(getApplicationContext(), newListener);
JSONObject data = newListener.getResponse();
But am having allot of trouble getting the listener portion to work so as to be able to access the resulting data from a method such as
newListener.getResponse();
There are a few questions on this site that generally outline how to set up a volley call from another class, such as: Android Volley - How to isolate requests in another class. I have had success getting the method call to work, but to now get that data into the present class for usage has caused trouble.
I have the action within my VolleySingleton class as:
public void somePostRequestReturningString(final Context context,final VolleyListener<String> listener) {
final String URL = "http://httpbin.org/ip";
JsonObjectRequest set = new JsonObjectRequest(Request.Method.GET, URL, ((String) null),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
listener.outPut = response.toString();
//Toast.makeText(context, response.toString(), Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
mRequestQueue.add(set);
}
and within the listener class:
public class VolleyListener {
public static String outPut;
private static Response.Listener<String> createSuccessListener() {
return new Response.Listener<String>() {
#Override
public void onResponse(String response) {
outPut = response;
}
};
}
}
How can I configure this to work and allow Volley calls and data retrieval from another class, particularly how to build callbacks correctly?
For your requirement, I suggest you refer to my following solution, hope it's clear and helpful:
First is the interface:
public interface VolleyResponseListener {
void onError(String message);
void onResponse(Object response);
}
Then inside your helper class (I name it VolleyUtils class):
public static void makeJsonObjectRequest(Context context, String url, final VolleyResponseListener listener) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
listener.onResponse(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.onError(error.toString());
}
}) {
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
};
// Access the RequestQueue through singleton class.
VolleySingleton.getInstance(context).addToRequestQueue(jsonObjectRequest);
}
Then, inside your Activity classes, you can call like the following:
VolleyUtils.makeJsonObjectRequest(mContext, url, new VolleyResponseListener() {
#Override
public void onError(String message) {
}
#Override
public void onResponse(Object response) {
}
});
You can refer to the following questions for more information (as I told you yesterday):
Android: How to return async JSONObject from method using Volley?
POST Request Json file passing String and wait for the response Volley
Android/Java: how to delay return in a method
Volley excels at RPC-type operations used to populate a UI, such as
fetching a page of search results as structured data. It integrates
easily with any protocol and comes out of the box with support for raw
strings, images, and JSON. By providing built-in support for the
features you need, Volley frees you from writing boilerplate code and
allows you to concentrate on the logic that is specific to your app.
How to create Common GET/POST Method Using Volley .
Create a Application Class
The Application class in Android is the base class within an Android
app that contains all other components such as activities and services
public class MyApplication extends Application {
public static final String TAG = MyApplication.class
.getSimpleName();
private RequestQueue mRequestQueue;
private static MyApplication mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Make Sure you add this Manifest Section .
<application
.....
android:name=".MyApplication"
>
Now, You need to create Singleton Class .
Singleton Pattern says that just define a class that has only one
instance and provides a global point of access to it .
public class MySingleton
{
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private static Context mCtx;
private MySingleton(Context context)
{
mCtx = context;
mRequestQueue = getRequestQueue();
}
public static synchronized MySingleton getInstance(Context context)
{
if (mInstance == null)
{
mInstance = new MySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue()
{
if (mRequestQueue == null)
{
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req)
{
getRequestQueue().add(req);
}
}
Now Common Class
public class VolleyUtils {
public static void GET_METHOD(Context context, String url, final VolleyResponseListener listener)
{
// Initialize a new StringRequest
StringRequest stringRequest = new StringRequest(
Request.Method.GET,
url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
listener.onResponse(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.onError(error.toString());
}
})
{
};
// Access the RequestQueue through singleton class.
MySingleton.getInstance(context).addToRequestQueue(stringRequest);
}
public static void POST_METHOD(Context context, String url,final Map<String,String> getParams, final VolleyResponseListener listener)
{
// Initialize a new StringRequest
StringRequest stringRequest = new StringRequest(
Request.Method.POST,
url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
listener.onResponse(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.onError(error.toString());
}
})
{
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
getParams.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
// Access the RequestQueue through singleton class.
MySingleton.getInstance(context).addToRequestQueue(stringRequest);
}
}
Now You should create Interface .
A class implements an interface, thereby inheriting the abstract
methods of the interface .
/**
* Created by Intellij Amiyo on 10-06-2017.
* Please follow standard Java coding conventions.
* http://source.android.com/source/code-style.html
*/
public interface VolleyResponseListener {
void onError(String message);
void onResponse(Object response);
}
How To Call
public void _loadAPI()
{
//GET
String URL_GET = "";
VolleyUtils.GET_METHOD(MainActivity.this, URL_GET, new VolleyResponseListener() {
#Override
public void onError(String message) {
System.out.println("Error" + message);
}
#Override
public void onResponse(Object response) {
System.out.println("SUCCESS" + response);
}
});
//POST
String URL_POST=" ";
VolleyUtils.POST_METHOD(MainActivity.this, URL_POST,getParams(), new VolleyResponseListener() {
#Override
public void onError(String message) {
System.out.println("Error" + message);
}
#Override
public void onResponse(Object response) {
System.out.println("SUCCESS" + response);
}
});
}
public Map<String,String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("YOUR_KEY", "VALUE");
return params;
}
For demo you should Download Volley-Common-Method
If you followed the general example from Android Volley - How to isolate requests in another class, (including the stuff regarding the singleton stuff) and looking for the parsing part (or, how to actually use the objects you receive), then this is the (again very general) addition
say you have a Json object coming in, that looks somewhat like this :
{"users":
[{"username":"Jon Doe","userid":83},
{"username":"Jane Doe",userid":84}]}
and our User object would look something like this:
public class User
{
String username;
int userid;
public String getName()
{
return username;
}
public int getId()
{
return userid;
}
}
Important: When working with Gson (you will see later), the object
fields should be named according to params you get in the Json, this
sort of reflection is how the parsing works.
then, the request itself would look something like this
(note the listener callback returning a
List<User>
object back to the caller, you'll see later):
public class NetworkManager
{
//... other stuff
public void getUsers(final SomeCustomListener<List<User>> listener)
{
final String URL = "http://httpbin.org/ip";
StringRequest request = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
Log.d(TAG + ": ", "getUsers Response: " + response);
List<User> users = MyJsonParser.getListObjects(response, "$.users[*]", User.class);
if(null != users)
listener.getResult(users);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
if (null != error.networkResponse)
{
Log.d(TAG + ": ", "Error Response code: " + error.networkResponse.statusCode);
listener.getResult(null);
}
}
});
requestQueue.add(request);
// ... other stuff
}
what you would need now is that class to parse the Json string, namely the object list, in this example I use Gson (again - this is a general example, change and reorder stuff according to your needs, you could probably also optimize this some more - it's just for the explanation):
public class MyJsonParser
{
//... other stuff
public static <T> List<T> getListObjects(String json_text, String json_path, Class<T> c)
{
Gson gson = new Gson();
try
{
List<T> parsed_list = new ArrayList<>();
List<Object> nodes = JsonPath.read(json_text, json_path);
for (Object node : nodes)
{
parsed_list.add(gson.fromJson(node.toString(), c));
}
return (parsed_list);
}
catch (Exception e)
{
return (new ArrayList<>());
}
}
//... other stuff
}
So, after we have all this (and the following stuff from the pre-mentioned SO question), what you said you were looking for is the callback in your working code, well that can be achieved in a couple of ways:
A straight forward way:
just call the method and override it's callback right there, e.g:
public class SomeClass
{
private List<User> mUsers;
private void someMethod()
{
// ... method does some stuff
NetworkManager.getInstance().getUsers(new SomeCustomListener<List<User>>()
{
#Override
public void getResult(List<User> all_users)
{
if (null != allUsers)
{
mUsers = allUsers;
// ... do other stuff with our info
}
}
});
// ... method does some more stuff
}
}
Or, in an indirect way (considering the time, memory consumption, etc. ), you can save the info you got in the same Singelton (or another container), and create a get method for it, and just get the object later (looks more slick)
remember: fire the request before (considering the latency for the response), as the nature of these callbacks is to be dependent on the response which might be delayed.
It would then look like this:
private List<User> mUsers;
private void someMethod()
{
// ... method does some stuff
mUsers = NetworkManager.getInstance().getUsersObject();
// ... method does some more stuff
}
A different option entirely would be to consider using Retrofit, that does the parsing for you, uses annotations, and is supposedly a lot faster , that might be what you're looking for (for the streamlined look) - I would read up on benchmarks, especially since the new 2.0 version came out.
Hope this Helps (although somewhat late)! :)

The method getApplication() is undefined for the type (my class)

I am using a global variables "GlobalVariables" in a separated class and I am try to use it in the following code but it is always gives me the error :
The method getApplication() is undefined for the type UploadPicture
I tried the following but still have error:
((GlobalVariables) this.getApplication()).set_FileUploading(false);
The qustion was already asked here but unfortunatlly all the answors didn't work with me and gave me same error! any suggestion please?
public class UploadPicture extends AsyncTask<Void, Long, Boolean> {
private DropboxAPI<?> mApi;
private String mPath;
private File mFile;
private long mFileLen;
private UploadRequest mRequest;
private Context mContext;
private String mErrorMsg;
private File outFiles;
public UploadPicture(Context context, DropboxAPI<?> api, String dropboxPath, File file) {
mContext = context.getApplicationContext();
mFileLen = file.length();
mApi = api;
mPath = dropboxPath;
mFile = file;
}
#Override
protected Boolean doInBackground(Void... params) {
try {
FileInputStream fis = new FileInputStream(mFile);
String path = mPath + outFiles.getName();
mRequest = mApi.putFileOverwriteRequest(path, fis, mFile.length(),
new ProgressListener() {
#Override
public long progressInterval() {
return 500;
}
#Override
public void onProgress(long bytes, long total) {
//publishProgress(bytes);
}
}
);
if (mRequest != null) {
mRequest.upload();
((GlobalVariables) UploadPicture.this.getApplication()).set_FileUploading(false);
return true;
}
} catch (DropboxUnlinkedException e) {
// This session wasn't authenticated properly or user unlinked
mErrorMsg = "This app wasn't authenticated properly.";
} catch (DropboxFileSizeException e) {
// File size too big to upload via the API
mErrorMsg = "This file is too big to upload";
} catch (DropboxPartialFileException e) {
// We canceled the operation
mErrorMsg = "Upload canceled";
} catch (DropboxServerException e) {
// Server-side exception. These are examples of what could happen,
// but we don't do anything special with them here.
if (e.error == DropboxServerException._401_UNAUTHORIZED) {
// Unauthorized, so we should unlink them. You may want to
// automatically log the user out in this case.
} else if (e.error == DropboxServerException._403_FORBIDDEN) {
// Not allowed to access this
} else if (e.error == DropboxServerException._404_NOT_FOUND) {
// path not found (or if it was the thumbnail, can't be
// thumbnailed)
} else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) {
// user is over quota
} else {
// Something else
}
// This gets the Dropbox error, translated into the user's language
mErrorMsg = e.body.userError;
if (mErrorMsg == null) {
mErrorMsg = e.body.error;
}
} catch (DropboxIOException e) {
// Happens all the time, probably want to retry automatically.
mErrorMsg = "Network error. Try again.";
} catch (DropboxParseException e) {
// Probably due to Dropbox server restarting, should retry
mErrorMsg = "Dropbox error. Try again.";
} catch (DropboxException e) {
// Unknown error
mErrorMsg = "Unknown error. Try again.";
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return false;
}
}
Edit: I am adding now my "VariableGlobales" calss:
public class GlobalVariables extends Application {
private Boolean _IsIOIORunning=false;
private Boolean _FileUploading=false;
public Boolean get_IsIOIORunning()
{
return _IsIOIORunning;
}
public void set_IsIOIORunning(Boolean _IsIOIORunning)
{
this._IsIOIORunning = _IsIOIORunning;
}
public Boolean get_FileUploading()
{
return _FileUploading;
}
public void set_FileUploading(Boolean _FileUploading)
{
this._FileUploading = _FileUploading;
}
It's normal UploadPicture doesn't extend GlobalVariables but it extend AsyncTask.
That it's my "GlobalVariables "
public class AppInfo extends Application {
private static Context context;
private static String user;
public void onCreate(){
super.onCreate();
AppInfo.context = getApplicationContext();
user = null;
}
public static Context getAppContext() {return AppInfo.context;}
public static String getUser() {return user;}
public static void setUser(String user) {AppInfo.user = user;}
}
And I call it everywhere like that:
AppInfo.getUser();
Edit:
GlobalVariables should use static method and variables:
public class GlobalVariables extends Application {
private static Boolean _IsIOIORunning=false;
private static Boolean _FileUploading=false;
public static Boolean get_IsIOIORunning() {
return _IsIOIORunning;
}
public static void set_IsIOIORunning(Boolean _IsIOIORunning) {
GlobalVariables._IsIOIORunning = _IsIOIORunning;
}
public static Boolean get_FileUploading(){
return _FileUploading;
}
public static void set_FileUploading(Boolean _FileUploading){
GlobalVariables._FileUploading = _FileUploading;
}
}

Categories