Description: In OnRespose method i can see data received from froecast.io in log but when i am passing "response.body().string()" i.e. data from forecast.io as argument(string) to method getCurrentDetails then Method is receiving null and JSONObject is throwing null pointer Exception.
Tried: handle exception through multiple catch block.
double latitude = -122.423;
double longitude = 37.8267;
String apiKey = "cac63237c81f5312b496ed8cce991b40";
String forecastURL = "https://api.forecast.io/forecast/"+apiKey+"/"+longitude+","+latitude+"";
if(isNetworkAvailable()) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(forecastURL).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
}
#Override
public void onResponse(Response response) throws IOException {
try {
Log.v(TAG, response.body().string());
if (response.isSuccessful()) {
mCurrentWeather = getCurrentDetails(response.body().string());
} else {
alertUserAboutProblem();
}
} catch (IOException e) {
Log.e(TAG, "Exception Caught: ", e);
}
catch(JSONException e){
Log.e(TAG,"Exception Caught: ", e);
}
}
});
Log.e(TAG, "Program is still running");
}
else{
Toast.makeText(MainActivity.this,"Network_Unavaliable",Toast.LENGTH_LONG).show();
}
}
private CurrentWeather getCurrentDetails(String string) throws JSONException {
------>>>>> JSONObject jsonObject = new JSONObject(string);
String timezone = jsonObject.getString("timezone");
JSONObject currently =jsonObject.getJSONObject("currently");
CurrentWeather currentWeather = new CurrentWeather();
currentWeather.setHumidity(currently.getDouble("humidity"));
currentWeather.setIcon(currently.getString("icon"));
currentWeather.setSummary(currently.getString("summary"));
currentWeather.setTemperature(currently.getDouble("temperature"));
currentWeather.setTime(currently.getLong("time"));
currentWeather.setPrecipIntensity(currently.getDouble("percipIntensity"));
currentWeather.setTimeZone(timezone);
Toast.makeText(MainActivity.this,String.valueOf(currently.getLong("time")),Toast.LENGTH_LONG).show();
// Log.d(TAG, String.valueOf(currentWeather.getTime()));
return currentWeather;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo coninfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if(coninfo!=null && coninfo.isConnected()){
isAvailable = true;
return isAvailable;
}
return false;
}
private void alertUserAboutProblem() {
AlertDialogFragment dialog =new AlertDialogFragment();
dialog.show(getFragmentManager(),TAG);
}
}
Try saving response.body().string() to a String variable and then passing it to getCurrentDetails.
Per the documentation: "the response body is a one-shot value that may be consumed only once".
Related
I try to only post my php script with this code but I have a Server Errorlike so
private static final String URL1 = "https://exp.com/appLoc.php";
private void User_Enter(){
StringRequest strRequest1 = new StringRequest(Request.Method.POST, URL1,
new Response.Listener<String>(){
#Override
public void onResponse(String response){
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams(){
Map<String, String> params1 = new HashMap<String, String> ();
params1.put ("location",la+","+lo);
params1.put ("licence",shpref.getString (Current_user,null));`like so`
params1.put ("main","enter");
return params1;
}
};
queue.add(strRequest1);
}
hi you may have error from server side to decode error what type of error it is use this
public void ShowResponse_Error(VolleyError error, Context context) {
if (error instanceof NetworkError) {
Toast.makeText(context,
context.getString(R.string.internet_error),
Toast.LENGTH_LONG).show();
} else if (error instanceof TimeoutError || error instanceof NoConnectionError) {
Toast.makeText(context,
context.getString(R.string.timeout_error),
Toast.LENGTH_LONG).show();
} else if (error instanceof AuthFailureError) {
Toast.makeText(context,
context.getString(R.string.auth_error),
Toast.LENGTH_LONG).show();
} else if (error instanceof ServerError) {
DecodeError(context, error);
}
}
private static void DecodeError(Context context, VolleyError error) {
NetworkResponse response = error.networkResponse;
try {
String res = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, "utf-8"));
// Now you can use any deserializer to make sense of data
JSONObject obj = new JSONObject(res);
Toast.makeText(context,
obj.getString("message"),
Toast.LENGTH_LONG).show();
} catch (UnsupportedEncodingException e1) {
// Couldn't properly decode data to string
e1.printStackTrace();
} catch (JSONException e2) {
// returned data is not JSONObject?
e2.printStackTrace();
}
}
in String res you will get error.
The first URL returns a list of names and IDs of farmers markets:
https://search.ams.usda.gov/farmersmarkets/v1/data.svc/locSearch?lat=" + latitude + "&lng=" + longitude
Then, the ID from the above URL must be used to get further information from each farmers market:
"https://search.ams.usda.gov/farmersmarkets/v1/data.svc/mktDetail?id=" + id
I want to display the name of the farmers markets from the first URL, and then the address of each farmers market from the second URL. How can I do this so that it all proceeds in the correct order?
Here is my MainActivity:
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
private ListView mListView;
GPSTracker gps;
Context mContext;
String marketAddress;
ArrayList<String> marketAddressArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
mListView = (ListView) findViewById(R.id.list_view);
double latitude = 45.496481;
double longitude = -122.573462;
gps = new GPSTracker(mContext, MainActivity.this);
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
}
else {
gps.showSettingsAlert();
}
final String marketUrl = "https://search.ams.usda.gov/farmersmarkets/v1/data.svc/locSearch?lat=" + latitude + "&lng=" + longitude;
Log.d(TAG, String.valueOf(latitude));
Log.d(TAG, String.valueOf(longitude));
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(marketUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
e.printStackTrace();
Log.d(TAG, "failure");
}
#Override
public void onResponse(Response response) throws IOException {
try {
final String jsonData = response.body().string();
Log.v(TAG, "THIS IS MY JSONDATA " + jsonData);
if (response.isSuccessful()) {
Log.d(TAG, marketUrl);
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
getCurrentDetails(jsonData);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Log.v(TAG, jsonData);
}
}
catch (IOException e) {
Log.e(TAG, "Exception caught: ", e);
}
}
});
Log.d(TAG, "Main UI code is running!");
}
private void getCurrentDetails(String jsonData) throws JSONException {
JSONObject usdaJSON = new JSONObject(jsonData);
JSONArray resultsJSON = usdaJSON.getJSONArray("results");
Market[] markets = new Market[resultsJSON.length()];
for(int i = 0; i < resultsJSON.length(); i++){
final JSONObject marketJSON = resultsJSON.getJSONObject(i);
String marketname = marketJSON.getString("marketname");
String id = marketJSON.getString("id");
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://search.ams.usda.gov/farmersmarkets/v1/data.svc/mktDetail?id=" + id)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
e.printStackTrace();
Log.d(TAG, "failure");
}
#Override
public void onResponse(Response response) throws IOException {
try {
final String marketDetailsJsonData = response.body().string();
Log.v(TAG, "THIS IS MY JSONDATA " + marketDetailsJsonData);
if (response.isSuccessful()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONObject detailsJSON = new JSONObject(marketDetailsJsonData);
JSONObject marketDetailsJSON = detailsJSON.getJSONObject("marketdetails");
marketAddress = marketDetailsJSON.getString("Address");
marketAddressArrayList.add(marketAddress);
//marketAddressArrayList.get(0);
//updateMarketAddress(); call this method for each market found - it will run 20 times if there are 20 markets
Log.d(TAG, "this is marketadress"+ marketAddress);
} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG, "broken");
}
}
});
}
}
catch (IOException e) {
Log.e(TAG, "Exception caught: ", e);
}
}
});
Log.d(TAG, "outside of the loop"+ marketname);
Market market = new Market(marketname, id, marketAddress);
markets[i] = market;
//markets[i].setAddress(marketAddressArrayList.get(i));
}
MarketAdapter adapter = new MarketAdapter(this, markets);
mListView.setAdapter(adapter);
for(int i = 0; i < resultsJSON.length(); i++) {
Log.d(TAG, markets[i].getMarketname());
Log.d(TAG, markets[i].getId());
// Log.d(TAG, markets[i].getMarketAddress());
}
}
}
First, extract out all the JSON parsing (for example, use Retrofit instead of OkHTTP) and UI updating to a separate method.
Then, hit the first URL, from that onResponse, hit the second URL.
Basically, what you are doing now,
if (response.isSuccessful()) {
Log.d(TAG, marketUrl);
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
getCurrentDetails(jsonData); // Call the second URL
But it doesn't need to be on the UI thread if you aren't updating the UI
Your for loop at the end must be within the second onResponse body, where the adapter/list would be populated.
Also, MarketAdapter should probably use List<Market> instead of ArrayList<String>
I have two activities, When I will move from activity A to B, B keeps restarting or "refreshing", when i go back from B to A, it also keeps restarting. The code is very big, here I am posting area where I think problem causes :
Thread t = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
deviceStatus();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.start();
this is deviceStatus();
public void deviceStatus(){
try {
RequestQueue requestQueue = Volley.newRequestQueue(InActivate.this);
String URL = "http://gickuwait-dev.com/electionapi/api/DeviceStatus";
JSONObject jsonBody = new JSONObject();
jsonBody.put("device_PK", device_ID2);
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.equals("true")){
Intent intent = new Intent(InActivate.this, Vote.class);
startActivity(intent);
finish();
}else if(response.equals("false")) {
}
// Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString;
String json = null;
try {
json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
responseString = String.valueOf(json).trim();
ArrayList<DeviceStatusResponse> list = new ArrayList<DeviceStatusResponse>();
Type listType = new TypeToken<List<DeviceStatusResponse>>() {}.getType();
list = new Gson().fromJson(responseString, listType);
device_Status = list.get(0).getIsActive().toString();
// Toast.makeText(getApplicationContext(), ""+device_Status+" null ", Toast.LENGTH_LONG).show();
return Response.success(device_Status, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
in Activity B, i have the same code to check the device status from the database, any help would be appreciated
You can use Handle to check the repeated task.
private Handler delayHandler = new Handler();
private Runnable runnable = new Runnable() {
#Override
public void run() {
deviceStatus();
driverDelayHandler.postDelayed(runnable, 1000);
}
};
Don't forgot to cancel on onStop method.
delayHandler.removeCallbacks(runnable);
This is the error i'm getting!
exception caught:
org.json.JSONException: Value com.squareup.okhttp.internal.http.RealResponseBody#42b1af18 of type java.lang.String cannot be converted to JSONObject
Main Activity
public class Main_Activity extends Activity {
public static final String TAG = Main_Activity.class.getSimpleName();
private CurrentWeather mCurrentWeather;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_);
double latitude = 37.8267;
double longitude = -122.423;
String apiKey = "26351d54df6d07aff2086c471da36d36";
String forecastURL = "https://api.forecast.io/forecast/" + apiKey + "/" + latitude + "," + longitude;
if (isNetworkAvailable()) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(forecastURL)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
}
#Override
public void onResponse(Response response) throws IOException {
String jsonData = response.body().toString();
Log.e(TAG, jsonData);
try {
if (response.isSuccessful()) {
mCurrentWeather = getCurrentDetails(jsonData);
} else {
alertUserAboutError();
}
}
catch (JSONException e){
Log.e(TAG, "exception caught: ", e);
}
}
});
} else {
Toast.makeText(this, getString(R.string.network_isUnavailable), Toast.LENGTH_LONG).show();
}
Log.e(TAG, "Main_Activity is running!");
}
private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("{timezone}");
Log.i(TAG, "From json: " + timezone);
return new CurrentWeather();
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
Boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()){
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment mDialog = new AlertDialogFragment();
mDialog.show(getFragmentManager(), "error_dialog");
}
}
Everything seems to be fine. Except in the below line
String jsonData = response.body().toString();
Replace the above line with the following
String jsonData = response.body().string();
I have a class as shown below. It is in a .java file called NQRequestHandler.java and I want to call this from an Activity.java. But I'm having problems with the AsyncTask method. When I run it in the Activity.java file it returns a null
value when I try to log the value of Globals.PUBLIC_KEY from the Activity.
Log.v("RESULT", "Public KEY JSON from OnStart" + Globals.PUBLIC_KEY);
public class NQRequestHandler {
private static NQRequestHandler instance;
public static final String TAG = NQRequestHandler.class.getSimpleName();
private Context mContext;
public NQRequestHandler(Context context) {
mContext = context;
}
public static synchronized NQRequestHandler getInstance(Context context) {
if (instance == null)
instance = new NQRequestHandler(context);
return instance;
}
public class requestHandler extends AsyncTask<String, Void, JSONArray> {
RequestListener requestListener;
public JSONArray requestResult;
public requestHandler() {
}
public void setRequestListener(RequestListener requestListener) {
this.requestListener = requestListener;
}
#Override
protected JSONArray doInBackground(String... params) {
try {
String url = "http://www.someurl.com";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> urlParameters = requestHandlerHelper(params);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(urlParameters);
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8"));
post.setEntity(entity);
HttpResponse response = client.execute(post);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
Reader reader = new InputStreamReader(response.getEntity().getContent());
int contentLength = (int) response.getEntity().getContentLength();
Log.v(TAG, "Content Length DATA" + contentLength);
char[] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
JSONArray jsonResponse = new JSONArray(responseData);
return jsonResponse;
} catch (ClientProtocolException e) {
Log.i(TAG, "ClientProtocolException: ", e);
} catch (UnsupportedEncodingException e) {
Log.i(TAG, "UnsupportedEncodingException: ", e);
} catch (IOException e) {
Log.i(TAG, "IOException: ", e);
} catch (JSONException e) {
Log.i(TAG, "JSONException: ", e);
}
return null;
}
#Override
protected void onPostExecute(JSONArray results) {
if (results != null) {
requestListener.onRequestSuccess(results);
} else {
requestListener.onRequestFailed();
}
}
}
public interface RequestListener {
JSONArray onRequestSuccess(JSONArray data);
void onRequestFailed();
}
public void NQRequest(String... params) {
if (isNetworkAvailable()) {
requestHandler handler = new requestHandler();
RequestListener listener = new RequestListener() {
#SuppressWarnings("unchecked")
#Override
public JSONArray onRequestSuccess(JSONArray data) {
//TODO: Switch set data here
Log.v(TAG, "JSON FROM NQRequest" + data);
Globals.PUBLIC_KEY = String.valueOf(data);
return data;
}
#Override
public void onRequestFailed() {
Toast.makeText(mContext, "Network is unavailable. Request failed", Toast.LENGTH_LONG).show();
}
};
handler.setRequestListener(listener);
handler.execute(params);
} else {
Toast.makeText(mContext, "Network is unavailable", Toast.LENGTH_LONG).show();
}
}
private static List<NameValuePair> requestHandlerHelper(String... params) {
//Declare URL Parameter values
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
String[] requestActionArray = Globals.REQUEST_ACTION_ID;
int actionSwitch = -1;
String[] requestActionHeaders = null;
//Find URL Parameter Action Switch
for (int i = 0; i < requestActionArray.length; i++) {
if (requestActionArray[i].equalsIgnoreCase(params[params.length - 1])) {
actionSwitch = i;
}
}
//Set Action Switch ID Parameters
requestActionHeaders = NQActionHeader(actionSwitch);
//Set URL Parameters
for (int i = 0; i < requestActionHeaders.length; i++) {
urlParameters.add(new BasicNameValuePair(requestActionHeaders[i], params[i]));
}
return urlParameters;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager =
(ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected() ? true : false;
}
private static String[] NQActionHeader(int actionSwitch) {
/* some code goes here */
}
}
In the Activity class looks like this:
public class Application extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
String message = "Hello World from Android";
Context mContext = getBaseContext();
NQRequestHandler.requestHandler handler = new NQRequestHandler.requestHandler();
NQRequestHandler requestHandler = NQRequestHandler.getInstance(mContext);
requestHandler.NQRequest(message, "sendPublicKey");
Log.v("RESULT", "Public KEY JSON from OnStart" + Globals.PUBLIC_KEY);
//Start Activity
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The call to NQRequest in the Activity initiates the call to AsyncTask in the Activity. Any help with this? How do I implement a callback in the Activity.java to get method from OnRequestSuccess(); in the NQRequest()? Note: I'm trying to call the method in Activity.java in other multiple Activity.java files
i modified the structure for your reference.
Modified of requestHandler :-
//**** e.g.
class requestHandler extends AsyncTask<Object, Void, JSONArray> {
// define a caller
String requester;
Application caller;
YourEachActivityClass1 caller1;
//create a Constructor for caller;
public requestHandler (Application caller) {
// TODO Auto-generated constructor stub
this.caller = caller;
}
public requestHandler (YourEachActivityClass1 caller1) {
// TODO Auto-generated constructor stub
this.caller1 = caller1;
}
///&& method doInBackground
#Override
protected JSONArray doInBackground(Object... params) {
.....
//your process is here
//custom your returning jsonarray
try {
Context context = (Context) params[0];
Log.i(TAG, "context :"+context.getClass().getSimpleName());
requester = (Integer) params[1];
String message = (String) params[2];
String public= (String) params[3]
String url = "http://www.someurl.com";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> urlParameters = requestHandlerHelper(params);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(urlParameters);
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8"));
post.setEntity(entity);
HttpResponse response = client.execute(post);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
Reader reader = new InputStreamReader(response.getEntity().getContent());
int contentLength = (int) response.getEntity().getContentLength();
Log.v(TAG, "Content Length DATA" + contentLength);
char[] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
JSONArray jsonResponse = new JSONArray(responseData);
Globals.PUBLIC_KEY = String.valueOf(jsonResponse);
return jsonResponse;
} catch (ClientProtocolException e) {
Log.i(TAG, "ClientProtocolException: ", e);
} catch (UnsupportedEncodingException e) {
Log.i(TAG, "UnsupportedEncodingException: ", e);
} catch (IOException e) {
Log.i(TAG, "IOException: ", e);
} catch (JSONException e) {
Log.i(TAG, "JSONException: ", e);
}
return null;
}
////&& return JSONArray back to ur activity class here by pass in caller
protected void onPostExecute(JSONArray jsonarray) {
if(requester.equals("IM_Application"))
caller.onBackgroundTaskCompleted(jsonarray);
else if(requester.equals("IM_ACTIVITY_1"))
caller1.onBackgroundTaskCompleted(jsonarray);
}
}
Application.class get ur json object:-
public class Application extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
String message = "Hello World from Android";
new requestHandler(this).execute(getActivity(), "IM_Application", message, "sendPublicKey");
} catch (Exception e) {
e.printStackTrace();
}
}
//your returning result
public void onBackgroundTaskCompleted(JSONArray jsonarray) {
Log.i("TAG", jsonarray:"+jsonarray);
if(jsonarray!=null){
//process your jsonarray to get the Globals.PUBLIC_KEY)here
Log.v("onBackgroundTaskCompleted", "Public KEY JSON from OnStart" + Globals.PUBLIC_KEY);
//Start Activity
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}else{
Toast.makeText(mContext, "Network is unavailable. Request failed", Toast.LENGTH_LONG).show();
}
}
}
Gd Luck :)
The log from OnStart should return a null value for Globals.PUBLIC_KEY. You have just set an asynchronous task to run to set that value. It has not run yet by the time that log statement executes. You should receive the log input from the
Log.v(TAG, "JSON FROM NQRequest" + data);
call. That will mostly happen after your activity has finished onCreate, as it is an asynchronous call.
Fixed it works now.
public class HQHandler extends AsyncTask<String, Void, JSONArray> {
public static final String TAG = HQHandler.class.getSimpleName();
private static HQHandler instance;
RequestListener requestListener;
JSONArray requestResult;
Context mContext;
public HQHandler(Context context) {
this.mContext = context;
}
public static synchronized HQHandler getInstance(Context context) {
if (instance == null)
instance = new HQHandler(context);
return instance;
}
public void setRequestListener(RequestListener requestListener) {
this.requestListener = requestListener;
}
public JSONArray getRequestResult() {
return this.requestResult;
}
#Override
protected JSONArray doInBackground(String... params) {
try {
String url = "http://www.someurl.com";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> urlParameters = requestHandlerHelper(params);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(urlParameters);
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8"));
post.setEntity(entity);
HttpResponse response = client.execute(post);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
Reader reader = new InputStreamReader(response.getEntity().getContent());
int contentLength = (int) response.getEntity().getContentLength();
Log.v(TAG, "Content Length DATA" + contentLength);
char[] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
JSONArray jsonResponse = new JSONArray(responseData);
return jsonResponse;
} catch (ClientProtocolException e) {
Log.i(TAG, "ClientProtocolException: ", e);
} catch (UnsupportedEncodingException e) {
Log.i(TAG, "UnsupportedEncodingException: ", e);
} catch (IOException e) {
Log.i(TAG, "IOException: ", e);
} catch (JSONException e) {
Log.i(TAG, "JSONException: ", e);
}
return null;
}
#Override
protected void onPostExecute(JSONArray results) {
if (results != null) {
requestListener.onRequestSuccess(results);
} else {
requestListener.onRequestFailed();
}
}
public interface RequestListener {
JSONArray onRequestSuccess(JSONArray data);
void onRequestFailed();
}
public JSONArray HQRequest(String... params) throws ExecutionException, InterruptedException, JSONException {
JSONArray result;
if (!isNetworkAvailable()) {
Toast.makeText(mContext, "Network is unavailable", Toast.LENGTH_LONG).show();
return null;
}
HQHandler handler = new HQHandler(this.mContext);
RequestListener listen = new RequestListener() {
#SuppressWarnings("unchecked")
#Override
public JSONArray onRequestSuccess(JSONArray data) {
return data;
}
#Override
public void onRequestFailed() {
Toast.makeText(mContext, "Network is unavailable. Request failed", Toast.LENGTH_LONG).show();
}
};
handler.setRequestListener(listen);
result = this.requestResult = handler.execute(params).get();
return result;
}
}