I have created a restful web service using this tutorial http://www.tutecentral.com/restful-api-for-android-part-1/ after running this i got an auto generated java file which contains the following code.
public class RestAPI {
private final String urlString = "http://125.0.0.174/Handler1.ashx";
private static String convertStreamToUTF8String(InputStream stream) throws IOException {
String result = "";
StringBuilder sb = new StringBuilder();
try {
InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[4096];
int readedChars = 0;
while (readedChars != -1) {
readedChars = reader.read(buffer);
if (readedChars > 0)
sb.append(buffer, 0, readedChars);
}
result = sb.toString();
} catch (UnsupportedEncodingException e){
e.printStackTrace();
}
return result;
}
private String load(String contents) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(60000);
Log.e("load r2","load r2");
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter w = new OutputStreamWriter(conn.getOutputStream());
w.write(contents);
w.flush();
InputStream istream = conn.getInputStream();
String result = convertStreamToUTF8String(istream);
return result;
}
private Object mapObject(Object o) {
Object finalValue = null;
if (o.getClass() == String.class) {
finalValue = o;
}
else if (Number.class.isInstance(o)) {
finalValue = String.valueOf(o);
} else if (Date.class.isInstance(o)) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss", new Locale("en", "USA"));
finalValue = sdf.format((Date)o);
}
else if (Collection.class.isInstance(o)) {
Collection<?> col = (Collection<?>) o;
JSONArray jarray = new JSONArray();
for (Object item : col) {
jarray.put(mapObject(item));
}
finalValue = jarray;
} else {
Map<String, Object> map = new HashMap<String, Object>();
Method[] methods = o.getClass().getMethods();
for (Method method : methods) {
if (method.getDeclaringClass() == o.getClass()
&& method.getModifiers() == Modifier.PUBLIC
&& method.getName().startsWith("get")) {
String key = method.getName().substring(3);
try {
Object obj = method.invoke(o, null);
Object value = mapObject(obj);
map.put(key, value);
finalValue = new JSONObject(map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return finalValue;
}
public JSONObject GetDoctors(String Terr_Code) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface","RestAPI");
o.put("method", "GetDoctors");
p.put("Terr_Code",mapObject(Terr_Code));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
public JSONObject GetUserDetail(String IMEINO) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface","RestAPI");
o.put("method", "GetUserDetail");
p.put("IMEINO",mapObject(IMEINO));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
}
I'm calling this class in async task and everything is working good but I want to use it through volley as async task is slow.
this class has only one url I don't understand how to call this url for individual methods I tried the below code but I'm getting bad url exception. Please show me how access the methods of rest api with separate urls.
public void requestJSON() {
String tag_json_obj = "json_obj_req";
final ProgressDialog pDialog = new ProgressDialog(context);
pDialog.setMessage("Loading...");
pDialog.show();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, null,
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
RestAPI restAPI = new RestAPI();
response = restAPI.GetDoctors(terrcode);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
display.setText(response.toString());
pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
display.setText(error.toString());
pDialog.hide();
}
});
// Adding request to request queue
VolleySingleton.getInstance().addToRequestQueue(jsonObjReq,
tag_json_obj);
}
Use Volley as VolleyService :
public class VolleyService {
private static VolleyService instance;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private VolleyService(Context context) {
requestQueue = Volley.newRequestQueue(context);
imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url,bitmap);
}
});
}
public static VolleyService getInstance(Context context) {
if (instance == null) {
synchronized(VolleyService.class) {
if (instance == null) {
instance = new VolleyService(context);
}
}
}
return instance;
}
public RequestQueue getRequestQueue() {
return requestQueue;
}
public ImageLoader getImageLoader() {
return imageLoader;
}
}
Then use your VolleyService in Activity or Fragment as this :
RequestQueue queue = VolleyService.getInstance(this.getContext()).getRequestQueue();
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// we got the response, now our job is to handle it
try {
//Here you parse your JSON - best approach is to use GSON for deserialization
getJsonFromResponse(response);
} catch (RemoteException | OperationApplicationException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//something happened, treat the error.
Log.e("Error", error.toString());
}
});
queue.add(request);
Related
How can i return the status code of my api?
i know that the status code is generating in the parseNetworkResponse but i am using the parseNetworkResponse for the saving of cache, how can i still return the status code? is there other way to do this by using volley?
here is my code.
int status_code = 0;
public void loadAnnouncement(){
final Constant WebConfig = new Constant();
RequestQueue queue = Volley.newRequestQueue(getContext());
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, WebConfig.url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
try {
JSONArray details = response.getJSONArray("data");
for (int i=0; i<details.length(); i++) {
JSONObject object = details.getJSONObject(i);
announcementList.add(new AnnouncementModel(
object.getInt("a"),
object.getString("b"),
object.getString("c"),
object.getString("d"),
object.getString("e"),
object.getString("f")
));
//creating adapter object and setting it to recyclerview
adapter = new AnnouncementAdapter(getActivity(), announcementList);
announcementRecyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
//This is for Headers If You Needed
#Override
public Map< String, String > getHeaders() throws AuthFailureError {
Map < String, String > params = new HashMap< String, String >();
params.put("Content-Type", "application/x-www-form-urlencoded");
params.put("X-API-KEY", WebConfig.test);
params.put("Authorization", WebConfig.test1);
return params;
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(response);
if (cacheEntry == null) {
cacheEntry = new Cache.Entry();
}
final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background
final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely
long now = System.currentTimeMillis();
final long softExpire = now + cacheHitButRefreshed;
final long ttl = now + cacheExpired;
cacheEntry.data = response.data;
cacheEntry.softTtl = softExpire;
cacheEntry.ttl = ttl;
String headerValue;
headerValue = response.headers.get("Date");
if (headerValue != null) {
cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
}
headerValue = response.headers.get("Last-Modified");
if (headerValue != null) {
cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue);
}
cacheEntry.responseHeaders = response.headers;
final String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString), cacheEntry);
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException e) {
return Response.error(new ParseError(e));
}
}
#Override
protected void deliverResponse(JSONObject response) {
super.deliverResponse(response);
}
#Override
public void deliverError(VolleyError error) {
super.deliverError(error);
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
return super.parseNetworkError(volleyError);
}
};
queue.add(getRequest);
}
this is working, but i still need to return the status_code of it.
any help would be really appreciated.
I am trying to return an ArrayList from an AsyncTask. But in main activity i am not able to get the returned arraylist. I want to know the way to call the asynctask so that i can get the returned arraylist.
This is the AsyncTask -
public class GetBannerDB extends AsyncTask<Void, Void, ArrayList<String>> {
GetBannerDB() {
}
#Override
protected ArrayList<String> doInBackground(Void... params) {
InputStream is = null;
ArrayList<String> bannerList = new ArrayList<String>();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("data", "data"));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("url to fetch data");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
serverResult = sb.toString().trim();
try {
String sResult = serverResult.substring(0, 7);
if (sResult.equalsIgnoreCase("success")) {
// Creating user login session
// Use user real data
String[] temp = serverResult.split("\\^");
String banner_image = temp[1];
String banner_redirect = temp[2];
bannerList.add(banner_image);
bannerList.add(banner_redirect);
} else {
}
} catch (NullPointerException ex) {
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bannerList;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
super.onPostExecute(result);
mBannerTask = null;
}
}
In MainActivity, i am calling the output as --
ArrayList<String> adDetails = new ArrayList<>();
mBannerTask = new GetBannerDB();
adDetails = mBannerTask.execute();
But here i am getting error - Incompatible types.
Where m i going wrong pls guide.
Ashok as per your answer, i have done the following changes --
OnDataListener.java (As interface)
public interface OnDataListener {
void setData(ArrayList<String> result);
}
In MainActivity.java -
public class PushAds implements OnDataListener{
String serverResult = null;
private GetBannerDB mBannerTask = null;
ArrayList<String> adDetails = new ArrayList<>();
public void displayAds()
{
mBannerTask = new GetBannerDB(new OnDataListener {
public void setData(ArrayList<String> result){
adDetails = result;
}
});
mBannerTask.execute();
}
......
}
But its giving error.
public interface OnDataListner{
void setData(ArrayList<String> result);
}
and
public class GetBannerDB extends AsyncTask<Void, Void, ArrayList<String>> {
public OnDataListner dataListner;
GetBannerDB(OnDataListner dataListner) {
this.dataListner = dataListner;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
super.onPostExecute(result);
dataListner.setData(result);
}
}
finally
ArrayList<String> adDetails = new ArrayList<>();
mBannerTask = new GetBannerDB(new OnDataListner{
#Overrid
public void setData(ArrayList<String> result){
adDetails = result;
//do something
}
});
mBannerTask.execute();
I'm doing an App that scrapes a website an get some images, that works fine, I created an ThreadPoolExecutor and some callable but when I try to get the results from a Callable that I created I'm unnable to, it goes to the ExecutionException.
This is the Scraper Class:
public class ImageScraper implements Callable<String>{
Context context = null;
public Logo logoActivity;
Document[] doc = new Document[1];
List<ImageObject> imageList = new ArrayList<ImageObject>();
int pagAnterior;
String url;
int pag;
public ImageScraper(Logo act, String url, int pag, int pagAnterior) {
this.logoActivity = act;
this.url = url;
this.pag = pag;
this.pagAnterior = pagAnterior;
context = act.getApplication();
}
#Override
public String call() throws Exception {
getResponse(url,pag);
getImages(doc[0]);
Log.i("listaaa", "listaa : "+imageList.size());
String something = "got something";
return something;
}
public void getImages(Document docfinal) {
Log.i("Documento1", "documento1 : "+docfinal);
Elements entradas = docfinal.select("img[src]");
Elements titulo = doc[0].select("title");
String tituloPagina = titulo.text();
String urlImage = "";
if(!tituloPagina.toLowerCase().contains("page "+pagAnterior)) {
for (Element elem : entradas) {
if (elem.attr("abs:src").toLowerCase().contains("mfiles")) {
urlImage = elem.attr("abs:src").replace("thumb-", "");
Log.i("GridVerticalFragment", "Pillando url: " + urlImage);
ImageObject image = new ImageObject(urlImage);
Log.i("GridVerticalFragment", "Url Pillada: " + image.getUrl());
imageList.add(image);
}
}
}
Log.i("Logo", "Lista2: "+imageList.size());
}
public void getResponse(String urlRoot, int pagina) {
Log.i("GridVerticalLayaout", "Pagina: "+pagina);
String url;
String urlFinal = "";
if(pagina==0){
url = urlRoot;
urlFinal = url;
}else{
url = urlRoot.concat("?page="+Integer.toString(pagina));
urlFinal = url;
}
RequestQueue rq = Volley.newRequestQueue(context);
Log.i("GridVerticalLayaout", "fuuck: "+url);
Log.i("GridVerticalLayaout", "lool: "+urlFinal);
StringRequest stringRequest = new StringRequest(Request.Method.GET, urlFinal,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Do something with the response
doc[0] = Jsoup.parse(response);
getImages(doc[0]);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
Log.e("ERROR", "Error occurred ", error);
}
});
rq.add(stringRequest );
}
}
And this is the main class:
public class Logo extends AppCompatActivity {
public List<ImageObject> GlobalImageList = new ArrayList<ImageObject>() ;
Document[] doc = new Document[1];
String url;
int pagAnterior = 0;
int i = 0;
Context context = null;
public ThreadPoolExecutor executor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logo);
getSupportActionBar().hide();
Collection<Callable<String>> callableList = new ArrayList<>();
context = getApplication();
int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
executor = new ThreadPoolExecutor(
NUMBER_OF_CORES*2,
NUMBER_OF_CORES*2,
60L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>()
);
while(i<4){
callableList.add(new ImageScraper(this,"www.google.es,i,i-1););
i++;
}
List<Future<String>> result = null;
try {
result = executor.invokeAll(callableList);
} catch (InterruptedException e) {
Log.i("Fallo", "Fallo");
e.printStackTrace();
}
for (Future a : result) {
String SingleImageList = null;
try {
SingleImageList = (String) a.get();
Log.i("Single", "Single"+SingleImageList);
} catch (InterruptedException e) {
Log.i("Fallo3", "Fallo3");
e.printStackTrace();
} catch (ExecutionException e) {
Log.i("Fallo2", "Fallo2");
e.printStackTrace();
}
}
}
}
This doesn't return anything but the scraper do his job,( the getImages() and getResponse() do the job and updates the list , instead if in this part of the code in MainClass:
while(i<4){
callableList.add(new ImageScraper(this,"www.google.es,i,i-1););
i++;
}
If I change that for this( the class is not called the callable is created in the class), it works, the string is returned:
while(i<4){
callableList.add(new Callable<String>() {
public String call() throws Exception {
return "haha";
}
});
i++;
}
Someone can help me with this? I've been reading a lot and according to what I've read, what I have in the Scraper class is fine, but I still don't get it.
Sorry for the bad english, Im trying to :), I don't want to return an string I want to return an ArrayList, im returning a string in the code because thought it was a problem for returning ArrayList, but it seems like that is not that, and again, Thanks!
Please check this line of code
while(i<4){
callableList.add(new ImageScraper(this,"www.google.es,i,i-1););
i++;
}
You are not closing the double quotes!
Instead, try this code
while(i<4){
callableList.add(new ImageScraper(this,"www.google.es",i,i-1););
i++;
}
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 have successfully created a rest web service and it returns jsonarray which has two fields
id and city from data base.
My resr web service is
#GET
#Path("city")
#Produces("application/json")
public String getJson() {
PropertyPojo propojo=null;
ArrayList cityList = new ArrayList();
JSONArray list = new JSONArray();
Map m1 = new LinkedHashMap();
List l1 = new LinkedList();
String jsonString = null;
try{
cityList=PDao.CityList();
Iterator it=cityList.iterator();
while(it.hasNext())
{
propojo=(PropertyPojo)it.next();
m1.put(propojo.getKeyid(),propojo.getKeyvalue());
}
}catch(Exception e){
}
l1.add(m1);
jsonString = JSONValue.toJSONString(l1);
return jsonString;
}
I just need to put these values into a spinner...
My android code is
public class MainActivity extends Activity {
Spinner spinner;
private static final String SERVICE_URL = "http://192.168.1.6:8080/eSava_RestWeb/webresources/service";
private static final String TAG = "AndroidRESTClientActivity";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinner = (Spinner) findViewById(R.id.city);
}
public void retrieveSampleData(View vw) {
String sampleURL = SERVICE_URL + "/city";
WebServiceTask wst = new WebServiceTask(WebServiceTask.GET_TASK,
this, "GETting data...");
wst.execute(new String[] { sampleURL });
}
#SuppressLint("NewApi")
public void handleResponse(String response) {
try {
// JSONObject jso = new JSONObject(response);
JSONArray json = new JSONArray(response);
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray) json;
if (jsonArray != null) {
int len = jsonArray.length();
for (int i = 0; i < len; i++) {
list.add(jsonArray.get(i).toString());
}
}
Spinner s = (Spinner) findViewById(R.id.city);
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, list);
s.setAdapter(adapter);
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
private class WebServiceTask extends AsyncTask<String, Integer, String> {
public static final int POST_TASK = 1;
public static final int GET_TASK = 2;
private static final String TAG = "WebServiceTask";
// connection timeout, in milliseconds (waiting to connect)
private static final int CONN_TIMEOUT = 3000;
// socket timeout, in milliseconds (waiting for data)
private static final int SOCKET_TIMEOUT = 5000;
private int taskType = GET_TASK;
private Context mContext = null;
private String processMessage = "Processing...";
private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
private ProgressDialog pDlg = null;
public WebServiceTask(int taskType, Context mContext,
String processMessage) {
this.taskType = taskType;
this.mContext = mContext;
this.processMessage = processMessage;
}
public void addNameValuePair(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
private void showProgressDialog() {
pDlg = new ProgressDialog(mContext);
pDlg.setMessage(processMessage);
pDlg.setProgressDrawable(mContext.getWallpaper());
pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDlg.setCancelable(false);
pDlg.show();
}
#Override
protected void onPreExecute() {
showProgressDialog();
}
protected String doInBackground(String... urls) {
String url = urls[0];
String result = "";
HttpResponse response = doResponse(url);
if (response == null) {
return result;
} else {
try {
result = inputStreamToString(response.getEntity()
.getContent());
} catch (IllegalStateException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return result;
}
#Override
protected void onPostExecute(String response) {
JSONArray jsArray;
// jsArray = new JSONArray(response);
handleResponse(response);
pDlg.dismiss();
}
// Establish connection and socket (data retrieval) timeouts
private HttpParams getHttpParams() {
HttpParams htpp = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
return htpp;
}
private HttpResponse doResponse(String url) {
// Use our connection and data timeouts as parameters for our
// DefaultHttpClient
HttpClient httpclient = new DefaultHttpClient(getHttpParams());
HttpResponse response = null;
try {
switch (taskType) {
case POST_TASK:
HttpPost httppost = new HttpPost(url);
// Add parameters
httppost.setEntity(new UrlEncodedFormEntity(params));
response = httpclient.execute(httppost);
break;
case GET_TASK:
HttpGet httpget = new HttpGet(url);
response = httpclient.execute(httpget);
break;
}
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
return response;
}
private String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(
new InputStreamReader(is));
try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
// Return full string
return total.toString();
}
}
}
Its better to create Model class and then you can parse the response with gson.
For example,
Imagine that you have your response with two strings Name and Mail. Create a model with two strings.
public class Sample{
public Sample()
{
}
#SerializedName("Name")//if needed
String name;
#SerializedName("Email")//if needed
String email;
public void set(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void set(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
}
Then parse your response with gson.
Sample sample = gson.fromJson(jsonRes.toString(), Sample.class);
Then you can access the members of the object sample. Change the Sample class as you needed(with the array of strings and int. You can use ArrayList instead of Array)
String[] city= {};
String[] id= {};
JSONArray jsonDetailsObj = json.getJSONArray("cityList");
JSONObject jsonLoop = null;
int noOfPoints = jsonDetailsObj.length();
city= new String[noOfPoints];
id= new String[noOfPoints];
for (int i=0 ; i < noOfPoints ; i++)
{
jsonLoop=jsonDetailsObj.getJSONObject(i);
city [i] = jsonLoop.getString("CityName");
id[i] = jsonLoop.getString("ID");
}