Related
This is my Java code:
public void imageUpload(final Context context, final String imagePath) {
final String requestBody;
JSONObject jsonUser = null;
JSONObject jsonAddress = null;
JSONObject jsonDriver = null;
JSONObject jsonImage = null;
String URL = SIGN_UP;
final String ConvertImage;
jsonUser = new JSONObject();
try {
jsonUser.put("first_name", "ABC");
jsonUser.put("last_name", "XYZ");
jsonUser.put("email", "yash#gmail.com");
jsonUser.put("phone", "9999900000");
jsonUser.put("password", "Yash#123");
jsonAddress = new JSONObject();
jsonAddress.put("address", "MUMBAI");
jsonAddress.put("city", "MUMBAI");
jsonAddress.put("state", "MH");
jsonAddress.put("zip", "369852");
jsonDriver = new JSONObject();
jsonDriver.put("middle_name", "GG");
jsonDriver.put("vehicle_type", "CAR");
jsonDriver.put("car_plate_number", "123456");
jsonDriver.put("car_brand", "BMW");
jsonDriver.put("making_year", "2011");
jsonDriver.put("date_of_birth", "2019-06-01");
jsonDriver.put("license_number", "12346579");
jsonDriver.put("license_state", "MH");
jsonDriver.put("social_security_number", "123456");
JSONObject jsonObjectFinal = new JSONObject();
jsonObjectFinal.put("user", jsonUser);
jsonObjectFinal.put("address", jsonAddress);
jsonObjectFinal.put("driver", jsonDriver);
} catch (JSONException e) {
e.printStackTrace();
}
SimpleMultiPartRequest smr = new SimpleMultiPartRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
try {
JSONObject jObj = new JSONObject(response);
String message = jObj.getString("message");
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "" + error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
/*params.put("user", jsonUser + "");
params.put("address", jsonAddress + "");
params.put("driver", jsonDriver + "");
Log.d("Param", "" + params + "***");*/
return params;
}
};
smr.addFile("license_image", imagePath);
smr.addMultipartParam("user", "text/plain", jsonUser + "");
smr.addMultipartParam("address", "text/plain", jsonAddress + "");
smr.addMultipartParam("driver", "text/plain", jsonDriver + "");
Log.d("Param", "" + smr.getMultipartParams() + "***");
MySingleton.getInstance(context).addToRequestQueue(smr);
}
The server shows:
data:->
[Object: null prototype] {
address:
'{"address":"SURAT","city":"SURAT","state":"GUJARAT","zip":"369852"}',
driver:
'{"middle_name":"GG","vehicle_type":"CAR","car_plate_number":"123456","car_brand":"BMW","making_year":"2011","date_of_birth":"2019-06-01","license_number":"12346579","license_state":"MH","social_security_number":"123456"}',
user:
'{"first_name":"YASH","last_name":"PANCHAL","email":"yash#gmail.com","phone":"8460277210","password":"Yash#123"}' }
files:-> [ { fieldname: 'license_image',
originalname: '1559197608373.jpg',
encoding: 'binary',
mimetype: 'application/octet-stream',
destination: 'C:\\Users\\Admin\\AppData\\Local\\Temp',
filename: 'license_image-m6i0vcx0-1559197611770.octet-stream',
path:
'C:\\Users\\Admin\\AppData\\Local\\Temp\\license_image-m6i0vcx0-1559197611770.octet-stream',
size: 53156 } ]
The files are sent perfectly but the JSON object is parsed as String, I want to send data like:
{
user:{
'first_name': 'yash',
'last_name': 'panchal'
},
address:{
...
},
driver:{
...
},
licence_image: [file]
}
In Android I have to pass request in JSON object or array including files.
If I try to parse the image via bitmap, the server returns undefined and if I try with pas as String it's working fine but when passing JSON data as above it results in sending object data as a single String.
Have a look at this multipart request with parameter's to a particular server and parsing its response as json :
private void saveProfileAccount() {
// loading or check internet connection or something...
// ... then
String url = "http://www.angga-ari.com/api/something/awesome";
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
String resultResponse = new String(response.data);
try {
JSONObject result = new JSONObject(resultResponse);
String status = result.getString("status");
String message = result.getString("message");
if (status.equals(Constant.REQUEST_SUCCESS)) {
// tell everybody you have succed upload image and post strings
Log.i("Messsage", message);
} else {
Log.i("Unexpected", message);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
String errorMessage = "Unknown error";
if (networkResponse == null) {
if (error.getClass().equals(TimeoutError.class)) {
errorMessage = "Request timeout";
} else if (error.getClass().equals(NoConnectionError.class)) {
errorMessage = "Failed to connect server";
}
} else {
String result = new String(networkResponse.data);
try {
JSONObject response = new JSONObject(result);
String status = response.getString("status");
String message = response.getString("message");
Log.e("Error Status", status);
Log.e("Error Message", message);
if (networkResponse.statusCode == 404) {
errorMessage = "Resource not found";
} else if (networkResponse.statusCode == 401) {
errorMessage = message+" Please login again";
} else if (networkResponse.statusCode == 400) {
errorMessage = message+ " Check your inputs";
} else if (networkResponse.statusCode == 500) {
errorMessage = message+" Something is getting wrong";
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.i("Error", errorMessage);
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("api_token", "gh659gjhvdyudo973823tt9gvjf7i6ric75r76");
params.put("name", mNameInput.getText().toString());
params.put("location", mLocationInput.getText().toString());
params.put("about", mAvatarInput.getText().toString());
params.put("contact", mContactInput.getText().toString());
return params;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
// file name could found file base or direct access from real path
// for now just get bitmap data from ImageView
params.put("avatar", new DataPart("file_avatar.jpg", AppHelper.getFileDataFromDrawable(getBaseContext(), mAvatarImage.getDrawable()), "image/jpeg"));
params.put("cover", new DataPart("file_cover.jpg", AppHelper.getFileDataFromDrawable(getBaseContext(), mCoverImage.getDrawable()), "image/jpeg"));
return params;
}
};
VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);
}
This question already has answers here:
org.json.JSONException: End of input at character 0 of
(2 answers)
Closed 4 years ago.
When I try to retrieve a JSON object from an API, it causes an error. I'm using JSONObjectRequest to get the result.
This is my activity method:
private void execute(final Context context) {
String url = UrlManager.getUrl(context, R.string.signup_url);
User user = User.getInstance();
try {
url += "&name=" + mFirstName + "&last=" + mLastName + "&mob=" + mMobile +
"&email=" + mEmail +
"&pass=" + UrlManager.prepareUrlPart(mPassword);
} catch (Exception e) {
e.printStackTrace();
}
final ProgressDialog pDialog;
pDialog = new ProgressDialog(context);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
Response.Listener < JSONObject > listener = new Response.Listener < JSONObject > () {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject userObj = new JSONObject();
userObj = response; //response.getJSONObject("UserInfo");
userInfo = new UserInfo();
userInfo.LoadItem(context, (JSONObject) userObj);
String state = response.getString("State");
if (state == "1") {
// Load user data from json and save them into local database
// User user = User.getInstance();
// user.loadFromJSon(response);
/// user.saveUser();
onResult(true);
} else {
onResult(false);
}
} catch (Exception e) {
Log.d("Error", e.getMessage());
e.printStackTrace();
}
pDialog.dismiss();
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
};
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, null, listener, errorListener);
MyApplication.getInstance().addToRequestQueue(request);
}
I've assured that my JSON is non-empty. Here's a sample JSON result:
{"UserId":60,"UserName":"09111","Password":"123","Email":"m#m.com","Mobile":"09111111111","NationalId":"0000000000","FirstName":"mm","LastName":"mm","FatherName":"","Birthday":"1990/10/11","State":"1"}
This is the error in question:
org.json.JSONException: End of input at character 0 of
private void execute(final Context context)
{
String url = UrlManager.getUrl(context, R.string.signup_url);
User user = User.getInstance();
try {
url += "&name=" + mFirstName + "&last=" + mLastName + "&mob=" + mMobile +
"&email=" + mEmail+
"&pass=" + UrlManager.prepareUrlPart(mPassword);
} catch (Exception e) {
e.printStackTrace();
}
final ProgressDialog pDialog;
pDialog = new ProgressDialog(context);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
try
{
JSONObject userObj = response;
userInfo = new UserInfo();
userInfo.LoadItem(context,
userObj);
String state = userObj.getString("State");
if (state .equals("1")) {
// Load user data from json and save them into local database
// User user = User.getInstance();
// user.loadFromJSon(response);
/// user.saveUser();
onResult(true);
} else {
onResult(false);
}
}
catch (Exception e)
{
Log.d("Error", e.getMessage());
e.printStackTrace();
}
pDialog.dismiss();
}
};
Response.ErrorListener errorListener = new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
};
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url,null, listener, errorListener);
MyApplication.getInstance().addToRequestQueue(request);
}
I have used the volley library to get the API response. Initially when am calling the API the error response is showing exactly from the server. but when i again call the API means i am getting error response is null.
Kindly help me to do this.
Here is my code
public void requestString(final String requestName,
final String webserviceUrl,
final Map<Object, Object> requestParams, final int webMethod,
final boolean getCache) {
LogUtils.i("Sending Request", webserviceUrl);
StringRequest stringRequest = new StringRequest(webMethod,
webserviceUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
LogUtils.i("Response", response);
mRequestCompletedListener.onRequestCompleted(
requestName, true, response, null);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String errorResponse = null;
if (getCache) {
final Cache cache = AppController.getInstance()
.getRequestQueue().getCache();
final Entry entry = cache.get(webserviceUrl);
if (entry.data != null) {
try {
errorResponse = new String(entry.data, "UTF-8");
mRequestCompletedListener
.onRequestCompleted(requestName,
true, errorResponse, null);
return;
} catch (UnsupportedEncodingException e) {
LogUtils.e(TAG, e);
}
} else {
LogUtils.e(TAG, requestName
+ " Cache does not exist");
}
}
try {
VolleyError responseError = new VolleyError(
new String(error.networkResponse.data));
LogUtils.i("ErrorResponse", responseError.getMessage());
try {
if (responseError != null) {
final JSONObject responseJson = new JSONObject(responseError.getMessage());
// Show Alert Information
errorResponse = responseJson.getString(AppConstants.MESSAGE);
}
} catch (Exception e) {
errorResponse = "Unknown";
}
} catch (Exception e) {
LogUtils.e(TAG, e);
}
mRequestCompletedListener.onRequestCompleted(
requestName, false, null,
errorResponse);
}
})
stringRequest.setTag(requestName);
// Adding String request to request queue
AppController.getInstance().addToRequestQueue(stringRequest);
}
Here am passing the Params:
AppController.getInstance().requestApi(mVolleyRequest, REQUEST_NAME, PATH
+ API, Request.Method.POST, HTTP_POST, Request.Priority.HIGH
, false, out.toString().trim(), true);
In my android app, I am sending a volley POST request and it's not working. Rather it is sending empty parameters.
If I enter the url (https://blogurl.com/wp-json/wp/v2/comments?post=20081&author_name=Ozuf&author_email=myemail#my.com&content=This_is_a_sampe_comment) in postman and send a POST request it yields the desired result.
And the code generated by Postman looks like this for JAVA OKHttp:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://blogurl.com/wp-json/wp/v2/comments?post=20081&author_name=Ozuf&author_email=myemail#my.com&content=This_is_a_sampe_comment")
.post(null)
.addHeader("cache-control", "no-cache")
.addHeader("postman-token", "23f2c2587-e9eb-5446-3d73-a1a1a6814683")
.build();
Response response = client.newCall(request).execute();
This is the code I am using to send the POST request:
public void submitComment() {
final String comment = commentContent.getText().toString().trim();
final String name = commentName.getText().toString().trim();
final String email = commentEmail.getText().toString().trim();
Log.d(TAG, "submitComment called");
if (allFieldsAreValid()) {
Log.d(TAG, "All fields are valid");
final String postComment = "https://blogurl.com/wp-json/wp/v2/comments?";
final PostingComment postingComment = PostingComment.newInstance();
postingComment.show(getFragmentManager(), "fragmentDialog");
JsonObjectRequest postDetails = new JsonObjectRequest(Method.POST, postComment, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
parseResponse(response);
postingComment.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse for getPost called");
VolleyLog.d(TAG, "Error: " + error.getMessage());
postingComment.dismiss();
if (sthWrongAlert != null) {
sthWrongAlert.show();
}
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("post", comtUrl);
params.put("author_name", name);
params.put("author_email", email);
params.put("content", comment);
return params;
}
};
int retrytimes = 10;
RetryPolicy policy = new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, retrytimes, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
postDetails.setRetryPolicy(policy);
//Creating requestqueue
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//Adding request queue
requestQueue.add(postDetails);
Log.d(TAG, "Data sent is " + comment + name + email);
} else {
Log.d(TAG, "All fields are not valid");
}
}
And Like I said before, the request goes true but the parameters are not sent along with it.
EDIT
After applying djodjo answer
public void submitComment() {
String comment = null;
try {
comment = URLEncoder.encode(commentContent.getText().toString().trim(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String name = null;
try {
name = URLEncoder.encode(commentName.getText().toString().trim(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String email = null;
try {
email = URLEncoder.encode(commentEmail.getText().toString().trim(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.d(TAG, "submitComment called");
if (allFieldsAreValid()) {
Log.d(TAG, "All fields are valid");
final String postComment = "https://blogurl.com/wp-json/wp/v2/comments?post="+comtUrl+"&content="+comment+"&author_name="+name+"&author_email="+email;
final PostingComment postingComment = PostingComment.newInstance();
postingComment.show(getFragmentManager(), "fragmentDialog");
JsonObjectRequest postDetails = new JsonObjectRequest(Method.POST, postComment, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
parseResponse(response);
postingComment.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse for getPost called");
VolleyLog.d(TAG, "Error: " + error.getMessage());
postingComment.dismiss();
if (sthWrongAlert != null) {
sthWrongAlert.show();
}
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
};
int retrytimes = 10;
RetryPolicy policy = new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, retrytimes, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
postDetails.setRetryPolicy(policy);
//Creating requestqueue
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//Adding request queue
requestQueue.add(postDetails);
Log.d(TAG, "Data sent is " + comment + name + email);
} else {
Log.d(TAG, "All fields are not valid");
}
}
After applying his solution, that's how my codes looks like. But I am constantly getting error 409.
06-20 19:13:26.405 25586-27084/com.jozuf.blog E/Volley: [6168] BasicNetwork.performRequest: Unexpected response code 409 for https://blog.url/wp-json/wp/v2/comments?post=20081content=Yyggggbbhhgggggg&author_nameRrrauthor_emailgf%40ff.com
After the debugging in chat, the issue found was that it is a POST request but the parameters are still being sent in the request url.
In your case sending a POST response will make the param to go in the body as a multipart form which needs to be fixed. Update you code with below
public void submitComment() {
String comment = null;
try {
comment = URLEncoder.encode(commentContent.getText().toString().trim(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String name = null;
try {
name = URLEncoder.encode(commentName.getText().toString().trim(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String email = null;
try {
email = URLEncoder.encode(commentEmail.getText().toString().trim(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.d(TAG, "submitComment called");
if (allFieldsAreValid()) {
Log.d(TAG, "All fields are valid");
final String postComment = "https://blogurl.com/wp-json/wp/v2/comments?post="+comtUrl+"&content="+comment+"&author_name="+name+"&author_email="+email;
final PostingComment postingComment = PostingComment.newInstance();
postingComment.show(getFragmentManager(), "fragmentDialog");
JsonObjectRequest postDetails = new JsonObjectRequest(Method.POST, postComment, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
parseResponse(response);
postingComment.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse for getPost called");
VolleyLog.d(TAG, "Error: " + error.getMessage());
postingComment.dismiss();
if (sthWrongAlert != null) {
sthWrongAlert.show();
}
}
});
int retrytimes = 10;
RetryPolicy policy = new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, retrytimes, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
postDetails.setRetryPolicy(policy);
//Creating requestqueue
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//Adding request queue
requestQueue.add(postDetails);
Log.d(TAG, "Data sent is " + comment + name + email);
} else {
Log.d(TAG, "All fields are not valid");
}
}
The duplicate issue is explained in this thread
Just change the request to have this retry policy and it will work
request.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
getParams() are not called for JsonRequests.
What you can do is just append to
postComment the extra params. for example:
final String comment = URLEncoder.encode(commentContent.getText().toString().trim(), "UTF-8");
final String name = URLEncoder.encode(commentName.getText().toString().trim(), "UTF-8");
final String email = URLEncoder.encode(commentEmail.getText().toString().trim(), "UTF-8");
final String postComment = "https://blogurl.com/wp-json/wp/v2/comments?comment="+comment+"&name="+name+"&email="+email;
You can send the parameters as JSONObject like this:
JSONObject params = new JSONObject("{\"post\":\"" + comtUrl + "\"," +
...
+ "}"
and in JsonObjectRequest you pass it as the third parameter.. you will not need getBodyContentType and getParams anymore
I am making multiple Volley StringRequests.
The requestfriendlist method fetches a list of profiles related to "Naruto". The requestimagelink method fetches Images for each profile it got in the previous method result.However the reponse (imagelink) I am getting is not in order from the requestimagelink method is not in order.
For Example -
Request[1,2,3,4]
Response[2,1,4,3] or any other order.
Please help me fix this issue.
Attaching Code Snippet
protected void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomImageAdapter(this, imageList);
listView.setAdapter(adapter);
requestfriendlist("Naruto");
}
private void requestfriendlist (String profilename)
{
String uri = String.format(Config.URL_REQUEST_FRIENDS + "?current_user=%1$s", profilename);
Log.d(TAG + "uri", uri);
StringRequest strReq = new StringRequest(
Request.Method.GET,
uri,
new Response.Listener<String>()
{
#Override
public void onResponse (String response)
{
try
{
JSONObject responseObj = new JSONObject(response);
Log.d(TAG + "friends", response);
JSONArray jResult = responseObj.getJSONArray("req_users");
Toast.makeText(MainActivity.this, jResult.toString(), Toast.LENGTH_SHORT).show();
for(int i = 0; i < jResult.length(); i++)
{
JSONObject jresponse = jResult.getJSONObject(i);
String profile = jresponse.getString("userid");
friendlist.add(profile);
}
for(int i = 0; i < friendlist.size(); i++)
requestimagelink(friendlist.get(i));
}
catch(JSONException e)
{
Log.d(TAG, "error" + e.getMessage());
Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse (VolleyError error)
{
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
);
MyApplication.getInstance().addToRequestQueue(strReq);
}
private void requestimagelink (final String profilename)
{
String uri = String.format(Config.URL_REQUEST_IMAGE + "?userid=%1$s", profilename);
Toast.makeText(MainActivity.this, uri, Toast.LENGTH_SHORT).show();
Log.d(TAG, "uri" + uri);
StringRequest strReq = new StringRequest(
Request.Method.GET,
uri,
new Response.Listener<String>()
{
//response from the server
#Override
public void onResponse (String response)
{
try
{
JSONObject responseObj = new JSONObject(response);
((TextView) findViewById(R.id.tvprofilejson)).setText(response);
Log.d(TAG, response);
JSONArray jResult = responseObj.getJSONArray("photos");
for(int i = 0; i < jResult.length(); i++)
{
JSONObject jresponse = jResult.getJSONObject(i);
ImageClass img = new ImageClass();
img.setThumbnailUrl(jresponse.getString("name"));
img.setTitle(profilename);
imageList.add(img);
//imagelinks.add(jresponse.getString("name"));
adapter.notifyDataSetChanged();
}
}
catch(JSONException e)
{
Log.d(TAG, "error" + e.getMessage());
Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse (VolleyError error)
{
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
);
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq);
}
Here is how to link your profiles to their images using a hashMap:
ArrayList<String> friendlist = new ArrayList<String>();
/**
Keeps the profiles' images. Later in your arrayAdapter, where you want show thumbnail image, you must
get corresponding ImageClass from of profile with profileName. If the result is null means that the image
is not loaded yet, otherwise you can use the ImageClass object to retreive profile's image.
*/
HashMap<String, ImageClass> profile_img_Hash = new HashMap<String, ImageClass>();
protected void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomImageAdapter(this, imageList);
listView.setAdapter(adapter);
requestfriendlist("Naruto");
}
private void requestfriendlist (String profilename)
{
String uri = String.format(Config.URL_REQUEST_FRIENDS + "?current_user=%1$s", profilename);
Log.d(TAG + "uri", uri);
StringRequest strReq = new StringRequest(
Request.Method.GET,
uri,
new Response.Listener<String>()
{
#Override
public void onResponse (String response)
{
try
{
JSONObject responseObj = new JSONObject(response);
Log.d(TAG + "friends", response);
JSONArray jResult = responseObj.getJSONArray("req_users");
Toast.makeText(MainActivity.this, jResult.toString(), Toast.LENGTH_SHORT).show();
for(int i = 0; i < jResult.length(); i++)
{
JSONObject jresponse = jResult.getJSONObject(i);
String profile = jresponse.getString("userid");
friendlist.add(profile);
}
for(int i = 0; i < friendlist.size(); i++)
requestimagelink(friendlist.get(i));
}
catch(JSONException e)
{
Log.d(TAG, "error" + e.getMessage());
Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse (VolleyError error)
{
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
);
MyApplication.getInstance().addToRequestQueue(strReq);
}
private void requestimagelink (final String profilename)
{
//This snippet will prevent re-downloading
if(profile_img_Hash.get(profilename) != null) {
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged(); //Optional. Not neccessary..!
}
});
return; //Because this profile's image is loaded.
}
String uri = String.format(Config.URL_REQUEST_IMAGE + "?userid=%1$s", profilename);
Toast.makeText(MainActivity.this, uri, Toast.LENGTH_SHORT).show();
Log.d(TAG, "uri" + uri);
StringRequest strReq = new StringRequest(
Request.Method.GET,
uri,
new Response.Listener<String>()
{
//response from the server
#Override
public void onResponse (String response)
{
try
{
JSONObject responseObj = new JSONObject(response);
((TextView) findViewById(R.id.tvprofilejson)).setText(response);
Log.d(TAG, response);
JSONArray jResult = responseObj.getJSONArray("photos");
for(int i = 0; i < jResult.length(); i++)
{
JSONObject jresponse = jResult.getJSONObject(i);
ImageClass img = new ImageClass();
img.setThumbnailUrl(jresponse.getString("name"));
img.setTitle(profilename);
imageList.add(img);
//imagelinks.add(jresponse.getString("name"));
//Before notifying the adapter we have to put the img into our hash map.
profile_img_Hash.put(profilename, img);
//Remember, in you getView(..) method of your adapter, you have to get image from
// profile_img_Hash by profileName as key. If the returned result was null do nothing
// If the returned value was not null you can use the ImageClass to provide profile's
// image. :)
adapter.notifyDataSetChanged();
}
}
catch(JSONException e)
{
Log.d(TAG, "error" + e.getMessage());
Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse (VolleyError error)
{
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
);
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq);
}
Keep in mind, in your arrayAdapter's getView(...) method you must load profile's image right from profile_img_Hash with profile name as key like this:
ImageClass img = profile_img_Hash.get(profilename);
if(img != null){
//row's imageView.setBitmap(img.getBitmap());
}
Hope this helps.