Not getting response from URL in gson +volley+recyclerview - android

i am making FriendManagementApp. I want to fetch response from the local host.I am using gson,volley,recyclerview but I am not getting response.
private void requestJsonObject() throws AuthFailureError
{
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://192.168.1.50:8080/*************/";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
// Log.d(TAG, "Response " + response);
GsonBuilder builder = new GsonBuilder();
Gson mGson = builder.create();
List<FriendsData> posts = new ArrayList<FriendsData>();
posts = Arrays.asList(mGson.fromJson(response, FriendsData[].class));
Log.i("MainActivity", posts.size() + " posts loaded.");
for (FriendsData data : posts) {
Log.i("MainActivity", data.getId() + ": " + data.getFirstname() + ": " + data.getLastname() + ":" + data.getContact());
adapter = new RecyclerViewAdapter(MainActivity.this, posts);
//recyclerView.setAdapter(adapter);
// recyclerView.getAdapter().addAll(posts);
// recyclerView.getAdapter().notifyDataSetChaged();
System.out.println(data.getId());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error " + error.getMessage());
System.out.print(error.getMessage());
}
});
queue.add(stringRequest);
}

If you are using emulator to connect to local machine use 10.0.2.2 IP address instead of 192.168.1.50. Check this link

I am assume that you installed LAMP server on your local machine.
You should open your local host's 8080 port for inbound rules.
Try to connect that url with your local browser.
If it is ok, put your LAMP server online. See Detail

Related

I want to access local server with port to get json as respose

I want to get json response from local server. I want to add port in that. how to add port while using volley in android
In main activity
{
String url = "192.2.3.1:80/data";
sendAndRequestResponse(url, new VolleyCallback(){
#Override
public void onSuccess(JSONObject result){
}
});
}
private void sendAndRequestResponse(final String url, final VolleyCallback callback) {
//RequestQueue initialized
mRequestQueue = Volley.newRequestQueue(MainActivity.this, new ProxyPort());
//String Request initialized
mStringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getApplicationContext(), "Response :" + response.toString(), Toast.LENGTH_LONG).show();//display the response on screen
Log.e("url", url);
Log.e("Response", response.toString());
try {
JSONObject obj = new JSONObject(response);
callback.onSuccess(obj);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("ERR", "Error :" + error.toString());
}
});
VolleyLog.DEBUG = true;
mRequestQueue.add(mStringRequest);
}
I want to add port in this url. I want to access local host using ip. How to achieve it

basic authentication server not working on jellybeans and kitkat

I am using basic authentic for http connection in app. App is working finr correctly on devices with higher versions. I have also searched for solution and It did not worked for me.
Here is my code for connection
public static String executeHttpPost(Activity activity, String url,
ArrayList<NameValuePair> postParameters) {
String value = "{\"status\":false,\"message\":\"Server Timeout, connection problem, Please try later\"}";
try {
final String basicAuth = "Basic " + Base64.encodeToString(
("abc" + ":" + "abcd").getBytes(), Base64.NO_WRAP);
networkConnection = new NetworkConnection();
if (networkConnection.isOnline(activity)) {
postParameters.add(new BasicNameValuePair("device_type","android"));
HttpClient client = getNewHttpClient();
HttpPost post = new HttpPost(url);
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParameters, "UTF-8");
post.setEntity(entity);
post.setHeader("Authorization",basicAuth);
post.setHeader("some-parameter","abc");
org.apache.http.HttpResponse result = client.execute(post);
value = EntityUtils.toString(result.getEntity());
}catch (Exception e){}
String s = "";
for (NameValuePair param : postParameters) {
s = s + param.getName() + " = " + param.getValue() + " ";
}
if (value != null) {
WebUrl.ShowLog("From " + url +" parameters "+s
+ " Response : " + value.trim());
return value.trim();
} else {
return value;
}
} else {
activity.startActivity(new Intent(activity, NoInternet.class));
activity.finish();
return "{\"status\":false,\"message\":\"\"}";
}
} catch (Exception e) {
e.printStackTrace();
return value;
}
}
This is the only link I found, but it didn't work for me
You should use Google Volley for the connections with the server. There are many ways to get connect, but using "Google Volley" in Android development is so simple, reliable and as it comes as a dependency it gets bundled with your package. So never worry about compatibility over many old and many current and upcoming Android versions.
I have used it 5 years ago and it was working on all major platforms. Very easy to program.
Have a look:
final TextView mTextView = (TextView) findViewById(R.id.text);
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
// Display the first 500 characters of the response string.
mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
mTextView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
How simple is it.

Occasionally, Volley fails to return a response from the server

I have two Android apps that communicate with a Web server using Volley calls: one app waits for the other to post a short message. Most of the time this works fine: the waiting app gets the response from the posting app. However, every 5 or so times, the response is sent by the first app but the second one never gets a response. Here is the relevant code:
Posting code:
private synchronized void setGameProgress(String user_id, int pos, String letter, String accessToken) {
String url = "";
RequestQueue queue = Volley.newRequestQueue(activity);
try {
activity.runOnUiThread(new Runnable() {
public void run() {
spinner.setVisibility(View.VISIBLE);
}
});
url = "https://www.chiaramail.com:443/GameServer/GameServer?user_ID=" + URLEncoder.encode(user_id, "UTF-8") + "&token=" + URLEncoder.encode(accessToken, "UTF-8") + "&cmd=" + URLEncoder.encode("SETGAME PROGRESS ", "UTF-8") + "&parms=" + URLEncoder.encode(user_id + " " + pos + " " + letter, "UTF-8");
} catch (UnsupportedEncodingException e) {
Toast.makeText(activity, getString(R.string.error_updating_progress) + e.getMessage(), Toast.LENGTH_LONG).show();
spinner.setVisibility(View.INVISIBLE);
}
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (!response.startsWith("42 ")) {
queue_builder.setMessage(getString(R.string.error_updating_progress) + " " + response);
queue_alert = queue_builder.create();
queue_alert.show();
}
spinner.setVisibility(View.INVISIBLE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
volleyError = error;
Toast.makeText(activity, getString(R.string.error_updating_progress) + volleyError.getMessage(), Toast.LENGTH_LONG).show();
spinner.setVisibility(View.INVISIBLE);
}
});
queue.add(stringRequest);
}
Wait code:
private synchronized void getGameProgress(final String user_id, final String accessToken) {
String url = "";
RequestQueue queue = Volley.newRequestQueue(activity);
try {
url = "https://www.chiaramail.com:443/GameServer/GameServer?user_ID=" + URLEncoder.encode(user_id, "UTF-8") + "&token=" + URLEncoder.encode(accessToken, "UTF-8") + "&cmd=" + URLEncoder.encode("GETGAME PROGRESS ", "UTF-8") + "&parms=" + URLEncoder.encode(user_id, "UTF-8");
} catch (UnsupportedEncodingException e) {
Toast.makeText(activity, getString(R.string.error_getting_progress) + e.getMessage(), Toast.LENGTH_LONG).show();
}
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.startsWith("43 ")) {
StringTokenizer st = new StringTokenizer(response.substring(3));
String position = st.nextToken();
String letter = st.nextToken();
updateTheirProgress(Integer.valueOf(position), letter);
getGameProgress(opponent_ID, AccessToken.getCurrentAccessToken().getToken());
} else {
queue_builder.setMessage(getString(R.string.error_getting_progress) + " " + response);
queue_alert = queue_builder.create();
queue_alert.show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
volleyError = error;
Toast.makeText(activity, getString(R.string.error_getting_progress) + volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
});
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000, 5,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(stringRequest);
}
I know that the server is processing the requests from the server log:
10212211883390475 2017-11-26, 17:57:40 42
10212211883390475 2017-11-26, 17:57:40 43 4 s
I've spent several days on this and other than a Volley bug, I can't see what the problem is. Any thoughts?
The problem was due to the Apache server timing out after five minutes. The problem was resolved when I changed the timeout setting in Apache to -1 (infinite timeout).

Using Android Volley with ASP .NET Web API

I am trying to retrieve a resource from my asp .net restful service from an android client.
I have a MessagesController which has the method GetMessages:
[Authorize]
public IQueryable<Message> GetMessages()
{
return db.Messages;
}
To access this I have sent a request to /token and have obtained a key which I use from the client application to access the resource.
The trouble I have is that the client is receiving a 302 http error when trying to access the resource.
This is the method in the android client:
public void setAllSendersAndAllMessages()
{
String url = "Messages/GetMessages";
showpDialog();
String Url = baseUrl + url;
JsonArrayRequest req = new JsonArrayRequest(Url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
allSenders = new String[response.length()];
allMessages = new String[response.length()];
for (int i = 0; i < response.length(); i++) {
JSONObject message = (JSONObject) response.get(i);
allSenders[i] = message.getString("sender");
allMessages[i] = message.getString("messageContent");
}
setInitialViews();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(context,error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "bearer "+ token);
return headers;
}
};
mRequestQueue.add(req);
}
I am overriding the getHeaders() method to send the authorization token to the service. This key and header works perfectly when using 'Postman' but fails in the android client for some unknown reason.
If anyone can offer some advice it would be greatly appreciated!
HTTP 302 is URL error, URL must be like :
http://server/WepApi/api/orders
Server : Your IIS server Name , or Your server IP address

Volley Offline Working

Ways to implement volley json response cache.I tried the following way to get response from volley.i get the response correctly.I dont know how to store these json values into volley cache
StringRequest strReq = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("mainresp$$$"+response);
Log.d("Volley Request Success", response.toString());
result=response;
callback.onSuccess(result);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("volley request Error",
"Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
Together with my comments, you have already read my answer at the following question:
Android Setup Volley to use from Cache
I have just tested with POST request, as the following code:
CacheRequest cacheRequest = new CacheRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
try {
final String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
// Check if it is JSONObject or JSONArray
Object json = new JSONTokener(jsonString).nextValue();
JSONObject jsonObject = new JSONObject();
if (json instanceof JSONObject) {
jsonObject = (JSONObject) json;
} else if (json instanceof JSONArray) {
jsonObject.put("success", json);
} else {
String message = "{\"error\":\"Unknown Error\",\"code\":\"failed\"}";
jsonObject = new JSONObject(message);
}
textView.setText(jsonObject.toString(5));
} catch (UnsupportedEncodingException | JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something...
}
});
My sample Asp.Net Web API code as the following:
// POST api/<controller>
public IHttpActionResult Post()
{
string jsonString = "[" +
"{" +
"name: \"Person 1\"," +
"age: 30," +
"type: \"POST\"," +
"}," +
"{" +
"name: \"Person 2\"," +
"age: 20," +
"type: \"POST\"," +
"}," +
"{" +
"name: \"Person 3\"," +
"age: 40," +
"type: \"POST\"," +
"}" +
"]";
JArray jsonObj = JArray.Parse(jsonString);
return Ok(jsonObj);
}
Here is the result screenshot

Categories

Resources