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();
Related
I am trying to get data from a JSON file that was written in a PHP file which was stored in my online hosting server(00webhost.com). When I run my program it says unknown host. However, the address will give JSON formatted file.
I have all the permissions along with the internet permission in my AndroidManifest.xml file.
Activity Class :
public class Recmain extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> contactList;
TextView uid;
TextView name1;
TextView email1;
Button Btngetdata;
//URL to get JSON Array
private static String url = "http://tongue-tied-
papers.000webhostapp.com/data_fetch.php";
//JSON Node Names
private static final String TAG_USER = "user";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
JSONArray user = null;
private List<movie> movieList = new ArrayList<>();
private RecyclerView recyclerView;
private moviesadapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rmain);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent=getIntent();
String m=intent.getStringExtra("data");
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new moviesadapter(movieList);
RecyclerView.LayoutManager mLayoutManager = new
LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
prepareMovieData();
}
private void prepareMovieData(){
movie movie = new movie("Mad Max: Fury Road", "Action & Adventure",
"2015");
movieList.add(movie);
mAdapter.notifyDataSetChanged();
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(recmain.this,url,Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
JSONParser sh = new JSONParser();
// Making a request to url and getting response
String url = "https://tongue-tied-
papers.000webhostapp.com/data_fetch.php";
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("id");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
Toast.makeText(getApplicationContext(), id ,
Toast.LENGTH_LONG).show();
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat
for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
}
Adapter class:
public class JSONParser {
private static final String TAG = JSONParser.class.getSimpleName();
public JSONParser() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection)
url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new
InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
It says, unknown host.
Looks like the URL is not formatted correctly. I think there is a space between the two parts of the URL.
private static String url = "http://tongue-tied-papers.000webhostapp.com/data_fetch.php"
Please try with the URL above without any space between the tied- and papers. You have two separate URL declaration, one at the beginning of the class and the other is in the doInBackground method. Please try changing both.
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>
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".
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;
}
}
I'm implementing json_web services in my Android application. I want to send the json data on jsonwebservices which is created in Java. When I run the application data does not send from the Android and does not show any error and also does not show any type of exception.
How can I identify whether my data is sent or not?
Here is my Activity Code:
public class Login extends Activity
{
Button btnLogin;
EditText etextUsername , etextPassword;
String strUserName , strPassWord ;
ProgressDialog pDialog;
JSONObject jObject ;
SharedPreferences.Editor editor;
SharedPreferences sharedPref1;
String str_Device_IP_Address=null;
JSONArray user = null;
String pref_filename = "IP_ADDRESS";
static final String KEY_REQUEST_ID = "RequestId";
static final String KEY_REQUEST_CODE = "RequestCode";
static final String KEY_CHANNEL_ID = "ChannelId";
static final String KEY_IP_ADDRESS="IPAddress";
static final String KEY_USERNAME="UserId";
static final String KEY_PASSWORD="Password";
static final String KEY_REQUEST="Request";
static final String KEY_VENDOR_ID="VendorId";
String RequestId="77777";
String RequestCode="001";
String stringChannelId="MobileApp";
String strIpAddress = null;
private String textToEncrypt = "Hi, this is a test to check its gone work or not.";
String encrypted = "MzA3RDBCMjMxMjQzNzcxREUxMUYxNjg1NzgwOTU1MjU1M0FDOUZEN0M3Q0JGQ0Q5MTI2NEIyNTE2"
+ "OTQwQTc3NjM2QTBCRDFDMUEyNkUwRjlDMzQwN0U0MEI0NDg2M0JBMDU1OThCNTI1NTZCMEFGNjk1NjJFNzZBMUE0NzM4NTQ=";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
final Context context = getApplicationContext();
connectWithHttpGet_IpAddress();
etextUsername = (EditText)findViewById(R.id.edittext_username);
etextPassword = (EditText)findViewById(R.id.edittext_password);
btnLogin=(Button)findViewById(R.id.button_Login);
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if (!isOnline())
{
showNoConnectionDialog(Login.this);
}
else
{
connectWithHttpGet_LoginData();
}
}
});
}
private void connectWithHttpGet_LoginData()
{
class GetJSONParse extends AsyncTask<String, Integer, JSONObject>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
str_Device_IP_Address=sharedPref1.getString("ip_address", "a\n");
System.out.println("strCode in Gsk_Demo ="+str_Device_IP_Address);
strUserName = etextUsername.getText().toString().trim();
strPassWord = etextPassword.getText().toString().trim();
pDialog = new ProgressDialog(Login.this);
pDialog.setIndeterminate(true);
pDialog.setCancelable(true);
pDialog.show();
System.out.println("Progress Dialog!!!!!!!!!!!!!!!!!!!!!!!");
}
#Override
protected JSONObject doInBackground(String... args)
{
String strUrl = "http://test.xxxxxx.com/cms/json/w2iWS";
JSONParser jParser = new JSONParser();
Log.e("DoinBackground !!!!!","Method");
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(strUrl);
String jsonString=json.toString();
Log.e("jsonString in DoinBackground !!!!!","Method" + jsonString);
return json;
}
#Override
protected void onPostExecute(JSONObject json)
{
pDialog.dismiss();
try
{
// Getting JSON Array
user = json.getJSONArray( KEY_REQUEST_ID );
JSONObject jsonObject = user.getJSONObject(0);
jsonObject.put(KEY_REQUEST_CODE, RequestCode);
jsonObject.put(KEY_CHANNEL_ID, stringChannelId);
jsonObject.put(KEY_IP_ADDRESS, str_Device_IP_Address);
jsonObject.put(KEY_USERNAME, strUserName);
jsonObject.put(KEY_PASSWORD, strPassWord);
String encrypted1 = EncodeDecodeAES.encrypt(jsonObject.toString(), textToEncrypt);
System.out.println("encrypted1 =" + encrypted1);
JSONObject inner = new JSONObject();
inner.put(KEY_REQUEST, encrypted1);
inner.put(KEY_VENDOR_ID, "1");
String decrypted = EncodeDecodeAES.decrypt(jsonObject.toString(), encrypted);
System.out.println("decrypted =" + decrypted);
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
GetJSONParse getjsonparse = new GetJSONParse();
getjsonparse.execute();
}
// Get Ip Address
private void connectWithHttpGet_IpAddress() {
class httpGetAsynchTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpClient httpClient = new DefaultHttpClient();
String url = "http://api.externalip.net/ip";
Log.e("!!STRING URL DATE DETAIL", "" + url);
HttpGet httpGet = new HttpGet(url);
Log.e("", "" + httpGet);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
Log.e("HTTP.RESPONSE.DATE.DTAIL", "" + httpResponse);
System.out.println("HTTPRESPONSE");
InputStream inpustream = httpResponse.getEntity()
.getContent();
InputStreamReader inputstreamreader = new InputStreamReader(
inpustream);
BufferedReader bufferedreader = new BufferedReader(
inputstreamreader);
StringBuilder stringbuilder = new StringBuilder();
Log.e("", "" + stringbuilder);
String strbuffer = null;
while ((strbuffer = bufferedreader.readLine()) != null)
{
stringbuilder.append(strbuffer);
}
String strResponse = stringbuilder.toString();
/****************** Code For Shared Preferences **************************************/
sharedPref1 = getSharedPreferences(pref_filename, 0);
editor = sharedPref1.edit();
editor.putString("ip_address", strResponse);
Log.e("Returning value of doInBackground REsponse:" ,strResponse);
System.out.println("IPADDRESS IN DOIN BACKGRAOUND");
editor.commit();
/***************** Code For Shared Preferences **************************************/
}
catch (ClientProtocolException cpe) {
cpe.printStackTrace();
Log.e("Exception generates caz of httpResponse :", "-"
+ cpe);
}
catch (IOException ioe) {
ioe.printStackTrace();
Log.e("Second exception generates caz of httpResponse :",
"-" + ioe);
}
return null;
}
}
httpGetAsynchTask httpGetAsyncTask = new httpGetAsynchTask();
httpGetAsyncTask.execute();
}
public static void showNoConnectionDialog(final Login login)
{
AlertDialog.Builder builder = new AlertDialog.Builder(login);
builder.setCancelable(true);
builder.setMessage(R.string.no_connection);
builder.setTitle(R.string.no_connection_title);
builder.setPositiveButton(R.string.settings_button_text, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
login.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
});
builder.setNegativeButton(R.string.cancel_button_text, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
return;
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
#Override
public void onCancel(DialogInterface dialog) {
return;
}
});
builder.show();
}
public boolean isOnline()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected())
{
return true;
}
else
{
return false;
}
}
}
Asynctask is not invoked
JSONParse jp =new JSONParse();
jp.execute(params);
http://developer.android.com/reference/android/os/AsyncTask.html
public final AsyncTask<Params, Progress, Result> execute (Params... params)
Executes the task with the specified parameters.
You had no invoked asynctask before
GetJSONParse get = new GetJSONParse();
get.execute(params);
And you said i can't see the log message in doInbackground. i just ran your code and i can see the log