I'm trying to get url links of images from json response, save it to string[] using ArrayList and then display the images in gridview as shown in this site. My json looks like this:
I fetched the links using volley but I'm not getting the links properly. I checked the content of ArrayList using Toast and it shows the images inside [[]] like this:
That's why the images are not getting downloaded. I get 6 blank views in list.
MainActivity:
public class MainActivity extends AppCompatActivity {
String[] IMGS={};
ArrayList<String> sal = new ArrayList<String>();
ListView listView;
public static final String KEY_USERID = "user_id";
private static final String REGISTER_URL = "http://example.com/Services.php?action=fetchUserLog";
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerUser();
listView = (ListView)findViewById(R.id.list);
}
///////////////////////////////////////// Volley Method Starts //////////////////////////////////////////////////////////////////
private void registerUser(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
try {
JSONObject jObj = new JSONObject(response);
String status = jObj.getString("status");
Toast.makeText(MainActivity.this, status, Toast.LENGTH_LONG).show();
// Now check status value
if (status.equals("0")) {
Toast.makeText(MainActivity.this, "There was some error! Please try again.", Toast.LENGTH_LONG).show();
}else if(status.equals("1")){
// Toast.makeText(getActivity(), "Information saved successfully", Toast.LENGTH_LONG).show();
JSONArray result = jObj.getJSONArray("results");
for(int i = 0 ; i < result.length() ; i++){
JSONObject json_data = result.getJSONObject(i);
sal.add(json_data.getString("images"));
//Toast.makeText(MainActivity.this, sal+"", Toast.LENGTH_LONG).show();
IMGS = sal.toArray(new String[sal.size()]);
listView.setAdapter(new ImageListAdapter(MainActivity.this, IMGS));
}
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(MainActivity.this, errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(MainActivity.this, "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_USERID, "21");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
///////////////////////////////////////// Volley Method Ends ////////////////////////////////////////////////////////////////////
}
Related
public class Login extends AppCompatActivity {
private static String LOGIN_URL = "http://172.26.154.132:75";
private EditText username;
private EditText password;
private Button buttonLogin;
private ProgressBar loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = (EditText) findViewById(R.id.input_email1);
password = (EditText) findViewById(R.id.input_password);
buttonLogin = (Button) findViewById(R.id.btn_login);
loading = findViewById(R.id.loading);
buttonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mEmail = username.getText().toString().trim();
String mPass = password.getText().toString().trim();
if(!mEmail.isEmpty() || !mPass.isEmpty()){
Login1(mEmail, mPass);
} else {
username.setError("Please insert email");
password.setError("Please insert password");
}
}
});
}
private void Login1(final String username, final String password) {
loading.setVisibility(View.VISIBLE);
buttonLogin.setVisibility(View.GONE);
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("data");
JSONArray jsonArray = jsonObject.getJSONArray("data");
if (success.equals("data")) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
Intent intent = new Intent(Login.this, MainActivity.class);
startActivity(intent);
loading.setVisibility(View.GONE);
}
}
} catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
buttonLogin.setVisibility(View.VISIBLE);
Toast.makeText(Login.this, "error" + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.setVisibility(View.GONE);
buttonLogin.setVisibility(View.VISIBLE);
Toast.makeText(Login.this, "error" + error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
The response:
{
"status": true,
"message": "User login successful.",
"data": [
{
"sno": "165",
"username": "khushboo.iit#gmail.com",
"user_id_generate": "khushbu#Paswan2018782",
"password": "25f9e794323b453885f5181f1b624d0b",
"is_verified": "1",
"hash": "",
"user_type": "icb_user",
"user_role": "admin"
}
]
}
If your API successfully return data then the problem is JSON parsing. JSON data not parsed successfully. Because "data" contains an array not a single String value.
Try this
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.getBoolean("status");
JSONArray jsonArray = jsonObject.getJSONArray("data");
if (success) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
Intent intent = new Intent(Login.this, MainActivity.class);
startActivity(intent);
loading.setVisibility(View.GONE);
}
}
} catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
buttonLogin.setVisibility(View.VISIBLE);
Toast.makeText(Login.this, "error" + e.toString(), Toast.LENGTH_SHORT).show();
}
I didnt understood question properly but i think i know what you meant.
As there are two functions one is for success and one is for failure you can handle cases like this..
Use JSONObjectRequest instead of string request, It will return you a JSONObject string instead of a string response. Or You can convert the string into a JSONObject like this
JSONObject response = new JSONObject(response)
and then you can parse the jsonObject like this.
if(respose.optString("status")==true)
//success
else
//failed
If you want to print the error msg which is coming from server... do it like this:
error.networkResponse.statusCode
error.networkResponse.message
I wanna upadate recyclerview child item when itself clicked.It takes the data from server and updates it self. kindly provide any solution for this scenario.Here i have tried as i know but it is not updating.
myHolder.upvote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
SQLiteHandler db = new SQLiteHandler(context);
HashMap<String, String> user = db.getUserDetails();
String tag_string_req = "req_login";
final String uid = user.get("uid");
Log.d("hello", uid);
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.Upvote, new Response.Listener<String>() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
String upvote_no = jObj.getString("upcount");
String text = "Upvoted " + upvote_no;
((TextView) v).setText(text);
//Log.d("resp", upvote);
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(context,
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(context, "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(context,
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<>();
params.put("qries_user_id", uid);
params.put("qries_answer_id", answered_id);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
});
In the above code i am trying to taking response from Json and updating to self child item as ((TextView) v).setText(text); but it is not updating.Thanks in Advance!
Try to cast your clicked view in TextView
myHolder.upvote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((TextView) v).setText("something");
}
});
I get the error no value for city.
I'm new to Android. I was unable to pass the spinner data using PHP URL, volley method. And in my XML I'm using the spinner and text views city, id and pass the city list through spinner URL.
Here is my activity:
private void spinnerapi(){
sprCoun = (Spinner) findViewById(R.id.spinner);
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String serverURL = "server url";
final StringRequest getRequest = new StringRequest(Request.Method.POST, serverURL,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("officerResponse", response);
try {
JSONObject jsonObject = new JSONObject(response);
String str_status = jsonObject.getString("status");
String str_message = jsonObject.getString("message");
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjectGuest = jsonArray.getJSONObject(i);
city_name = jsonObjectGuest.getString("cityname");
city_id = jsonObjectGuest.getString("cityid");
listarraylist.add(new CityModel(city_name));
}
sprCoun.setAdapter(new ArrayAdapter<String>
(RegistrationActivity.this, android.R.layout.simple_spinner_dropdown_item, list));
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "" + e, Toast.LENGTH_LONG).show();
}
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
// Toast.makeText(context, "" + error, Toast.LENGTH_LONG).show();
Log.d("tyghj", String.valueOf(error));
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
queue.add(getRequest);
}
This question already has answers here:
JSON Array of strings (no objects), extracting data
(4 answers)
Closed 6 years ago.
its actually a simple code, cuz of lack of basic I still cant manage to handle this.
After I made a Post JSON Method on my own Api, I get the following response
[{"id":"2"}]
What I'm trying to achieve is that I would like to get the value of this "id" which is "2".
I've tried the following code in my private void method
private void getUserID() {
StringRequest stringRequest = new StringRequest(Method.POST,Constants.GET_USER_ID,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
try {
JSONObject jsonRootObject = new JSONObject(strJson);
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = Integer.parseInt(jsonObject.optString("id").toString());
String idUser = jsonObject.optString("id").toString();
}
output.setText(idUser);
} catch (JSONException e) {e.printStackTrace();}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put(Constants.KEY_A, username);
map.put(Constants.KEY_B, password);
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
I get it from here.
It's a bit of waste, because I only have one list object in my array, and I thinks for loop is not really important in here.
replace your try block with following
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String idUser = jsonObject.getString("id");
Log.e("id is: ", idUser);
}
Try this way you will get
private void makeJsonArrayRequest() {
showpDialog();
JsonArrayRequest req = new JsonArrayRequest( delprourl,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("ress", response.toString());
// Parsing json
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
System.out.println("person" + person);
//get your id here
String id = person.getString("id");
Log.e("id: ", id);
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
// notifying list adapter about data changes
// so that it renders the list view with updated data
//adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("ErrorVolley", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
MyApplication.getInstance().addToReqQueue(req, "jreq");
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
I have an obstacle by changing the data string into a jsonobject, is his org.json.JSONException script error: Value
This coding I am trying
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String username = inputUser.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (username.trim().length() > 0 && password.trim().length() > 0) {
Map<String,String> params = new HashMap<>();
params.put("username", inputUser.getText().toString());
params.put("password", inputPassword.getText().toString());
sendPostRequest(params);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Silahkan Masukan Username dan Password!", Toast.LENGTH_LONG)
.show();
}
}
});
public void sendPostRequest(Map<String, String> params) {
showDialog();
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://www.chris-chris.webege.com/login.php";
mCustomRequest = new CustomRequest(Request.Method.POST,
url, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Intent intent = new Intent(Login.this,
Coba.class);
startActivity(intent);
finish();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", error.getMessage());
hidepDialog();
Toast.makeText(Login.this, "Belum Terhubung Internet! ", Toast.LENGTH_SHORT).show();
}
});
mCustomRequest.setRetryPolicy(new DefaultRetryPolicy(Template.VolleyRetryPolicy.SOCKET_TIMEOUT,
Template.VolleyRetryPolicy.RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(mCustomRequest);
}
There are two conditions to convert a string to JSONObject :
1 . The string should be in proper Json format .
2 . Put code in try catch block .
Example:
String jsonString = "{"status":"1","message":"Login successfully","data":{"uid":"1","email":"baleshwar#gmail.com","password":"202cb962ac59075b964b07152d234b70","name":"","role":"1","gender":"","address":"","image":"","is_active":"0","last_login":"0000-00-00 00:00:00","device_id":"0","created_at":"2015-06-03 06:01:02","updated_at":"2015-06-03 11:01:02","location":"","dob":"0000-00-00","descriptions":""}}"
Now convert this string to JSONObject
try{
JSONObject jsonResponse = new JSONObject(result);
}catch(Exception e){
e.printStackTrace();
}
Try this,
If you call your service and try to paste that code inside your isSucsess part
JSONObject jObject = jsonObject.getJSONObject("jsonobjectname");
tvTitle.setText(jObject.getString("your string name"));