This is my JSON,
[{
"album_id": "71",
"user_id": "38",
"category_name": "Gallery 1",
"album_image": "../images/album/gallery1rapport3871.jpg",
"org_image_name": "Love-Couple-3.jpg",
"date": "16-10-2016",
"status": "0"
}, {
"album_id": "73",
"user_id": "38",
"category_name": "Gallery 1",
"album_image": "../images/album/gallery1rapport3873.jpeg",
"org_image_name": "t1.daumcdn.net.jpeg",
"date": "16-10-2016",
"status": "0"
}]
I am tring to fetch all the org_image_name values. But I am only getting one value when I display it using a Toast.
Here is my code. Please help me.
public class Album_Display extends FragmentActivity {
GridView grid1;
CustomGrid_Album adapter;
private ProgressDialog pDialog;
String Uid,Disp;
public String category;
public String selected;
public static String imagename;
Button Alb_sel;
public static TextView cart_count,disp;
ArrayList<Item_album> gridArray = new ArrayList<Item_album>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.album_display);
grid1 = (GridView) findViewById(R.id.gridView2);
Uid = getIntent().getStringExtra("id");
Disp = getIntent().getStringExtra("disp");
disp = (TextView) findViewById(R.id.top_Album_text);
disp.setText(Disp);
Datas.Uid=Uid;
Alb_sel=(Button)findViewById(R.id.album_to_select);
pDialog = new ProgressDialog(Album_Display.this);
pDialog.setMessage("Loading...");
pDialog.show();
final RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConfig.URL_Gallery1,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
} catch (JSONException e1) {
e1.printStackTrace();
}
int i=0;
for (i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
category = obj.getString("category_name");
selected = obj.getString("album_id");
imagename = obj.getString("org_image_name");
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(Album_Display.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
pDialog.dismiss();
grid1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Album_Display.this, Display.class);
intent.putExtra("count", xl);
intent.putExtra("pos", position);
startActivity(intent);
}
});
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
};
queue.add(stringRequest);
}
public void back(View view){
finish();
}
public void upload_img(View view){
Intent in = new Intent(Album_Display.this, Image_Upload.class);
startActivity(in);
}
public void select(View view){
Toast.makeText(getApplication(), imagename, Toast.LENGTH_LONG).show();
Intent in=new Intent(Album_Display.this,Album_Select.class);
in.putExtra("category_name", category);
in.putExtra("album_id", selected);
in.putExtra("org_image_name", imagename);
startActivity(in);
}
}
Look at the value of "org_image_name" property. The JSON response as itself is returning a String value instead of an Array. First I think it should represent the response like following,
"org_image_name":["imgOne.jpg", "imgTwojpg"],
"date": "16-10-2016",
"status": "0"
Then you comes to a point where you need to parse it as a String array.
Related
server data
android data
I am passing arraylist of srid of all element and post to server using volley request.enter image description here
here is the code
public class AttendenceShowStdList extends AppCompatActivity {
ActivityAttendenceShowStdListBinding AttendenceShowStdList;
ArrayList<AttStdListModel> userlist = new ArrayList<>();
ArrayList<AllStdListsrIdAdmIdModel> list= new ArrayList<>();
ArrayList<AllStdListModel> stdlist = new ArrayList<>();
AttStdListAdapter adapter;
private DatePickerDialog datePickerDialog;
private String date,clid,sectionId,yrId,instId,usid,usType,attdate;
SharedPreferences sharedPreferences_teach;//staff shareprefferece for profile fetch
private static final String SHARED_PREF_NAME_TEACH="myprefteach";
private static final String Key_USID_TEACH = "techusid";
private static final String Key_INSTID_TEACH = "techinstid";
private static final String Key_USTYPE_TEACH = "techustype";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AttendenceShowStdList= ActivityAttendenceShowStdListBinding.inflate(getLayoutInflater());
setContentView(AttendenceShowStdList.getRoot());
sharedPreferences_teach =getSharedPreferences(SHARED_PREF_NAME_TEACH, Context.MODE_PRIVATE);
instId=sharedPreferences_teach.getString(Key_INSTID_TEACH,null);
usid=sharedPreferences_teach.getString(Key_USID_TEACH,null);
usType=sharedPreferences_teach.getString(Key_USTYPE_TEACH,null);
//getting data from TakeAttendenceAdapter cardview
clid=getIntent().getExtras().getString("ClassId");
sectionId=getIntent().getExtras().getString("sectionId");
Log.d("cliddd",clid);
yrId=getIntent().getExtras().getString("YearId");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
date = sdf.format(new Date());
Log.d("dttt",date);
userlist = (ArrayList<AttStdListModel>) getModel(false);
adapter = new AttStdListAdapter(this,userlist);
AttendenceShowStdList.rvstdlist.setAdapter(adapter);
AttendenceShowStdList.rvstdlist.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
// recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
// recyclerView.setHasFixedSize(true);
getData();
//toolbar
setSupportActionBar(AttendenceShowStdList.toolbar);
Objects.requireNonNull(getSupportActionBar()).setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
AttendenceShowStdList.submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitAttendence();
// Intent intent = new Intent(AttendenceShowStdList.this,SubmitAttendenceActivity.class);
// startActivity(intent);
}
});
}
private List<AttStdListModel> getModel(boolean isSelect){
List<AttStdListModel> list = new ArrayList<>();
for(int i = 0; i < list.size(); i++){
AttStdListModel model = new AttStdListModel();
model.setSelected(isSelect);
// model.setStud_name(String.valueOf(list.get(i)));
model.setAdmi_id(String.valueOf(list.get(i)));
list.add(model);
}
return list;
}
private void getData() {
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String url1="https://comzent.in/wonderschoolerp/apis/teacher/get_studteachers_att.php";
StringRequest request = new StringRequest(Request.Method.POST, url1, new com.android.volley.Response.Listener<String>() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onResponse(String response) {
// Toast.makeText(getContext(), "Data added to API", Toast.LENGTH_SHORT).show();
try {
JSONObject respObj = new JSONObject(response);
JSONArray jsonArray5=respObj.getJSONArray("studatt_details");
Log.d("std details",jsonArray5.toString());
for(int i=0;i<jsonArray5.length();i++){
JSONObject jsonObject=jsonArray5.getJSONObject(i);
String sr_id=jsonObject.optString("sr_id");
String admi_id=jsonObject.optString("admi_id");
String stud_name=jsonObject.optString("stud_name");
String stud_phone=jsonObject.optString("stud_phone");
String stud_email=jsonObject.optString("stud_email");
String attd_status=jsonObject.optString("attd_status");
String attd_reason=jsonObject.optString("attd_reason");
userlist.add(new AttStdListModel(sr_id,admi_id,stud_name,stud_phone,stud_email,
attd_status,attd_reason));
Log.d("s", String.valueOf(userlist));
list.add(new AllStdListsrIdAdmIdModel(sr_id,admi_id,stud_name,stud_phone,stud_email,
attd_status,attd_reason));
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter=new AttStdListAdapter(getApplicationContext(),userlist);
AttendenceShowStdList.rvstdlist.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Fail to get response = " + error, Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("get_studattd","1");
params.put("us_id",usid);
params.put("inst_id",instId);
params.put("class_id",clid);
params.put("sec_id",sectionId);
params.put("ay_id",yrId);
params.put("stud_attend_date",date);
return params;
}
};
queue.add(request);
}
//submit attendence
private void submitAttendence() {
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String url1="https://comzent.in/wonderschoolerp/apis/teacher/take_studteacher_att.php";
StringRequest request = new StringRequest(Request.Method.POST, url1, new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Toast.makeText(getContext(), "Data added to API", Toast.LENGTH_SHORT).show();
try {
JSONObject respObj = new JSONObject(response);
String msg=respObj.getString("message");
Toast.makeText(AttendenceShowStdList.this, msg, Toast.LENGTH_LONG).show();
Log.d("response msg",msg);
if(msg.equals("Attendance Generated Successfully..!")){
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Fail to get response = " + error, Toast.LENGTH_LONG).show();
Log.d("error msg", String.valueOf(error));
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
ArrayList<String> allstdsrid = new ArrayList<String>();
for(int i=0; i < list.size(); i++) {
allstdsrid.add(String.valueOf(list.get(i).getSr_id()));
}
params.put("sr_id", String.valueOf(allstdsrid));
Log.d("params", String.valueOf(params));
Log.d("allstudentsrid", String.valueOf(allstdsrid));
ArrayList<String> allstdadmid = new ArrayList<String>();
for(int i=0; i < list.size(); i++) {
allstdadmid.add(list.get(i).getAdmi_id());
params.put("admission_id", String.valueOf(allstdadmid));
}
Log.d("allstudentsadmid", String.valueOf(allstdadmid));
///selected student list
ArrayList<String> attstd = new ArrayList<String>();
for (int i = 0; i < AttStdListAdapter.userlist.size(); i++) {
if (AttStdListAdapter.userlist.get(i).getSelected()) {
attstd.add(AttStdListAdapter.userlist.get(i).getAdmi_id());
}
}
params.put("student_attend_submit","1");
params.put("class_id",clid);
params.put("sec_id",sectionId);
params.put("ay_id",yrId);
params.put("att_status", String.valueOf(attstd));
Log.d("params", String.valueOf(params));
params.put("stud_attend_date",date);
params.put("inst_id",instId);
params.put("us_id",usid);
params.put("us_type",usType);
return params;
}
};
queue.add(request);
}
//toolbar back to home
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId()==android.R.id.home){
finish();
}
return super.onOptionsItemSelected(item);
}
}
After submitting attendance, values of array of srid and admid retrive at server correctly ,problem is that only first record's srid and admid sets to '0' value.There is no problem when same Api is fetch on postman.
This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
I can parse json from a url in this way and my json looks like this;
[
{"rank":1,"title":"The Shawshank Redemption"},
{"rank":2,"title":"The Godfather"},
{"rank":3,"title":"The Godfather: Part II"},
{"rank":4,"title":"The Dark Knight"}
]
This is my android code and it works perfect;
public class MainActivity extends AppCompatActivity {
private ListView listView;
private SwipeListAdapter adapter;
private List<Movie> movieList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
movieList = new ArrayList<>();
adapter = new SwipeListAdapter(this, movieList);
listView.setAdapter(adapter);
runOnUiThread(new Runnable() {
#Override
public void run() {
fetchMovies();
};
});
}
private void fetchMovies() {
String url = "http://www.url.com/test.json";
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length() > 0) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
int rank = movieObj.getInt("rank");
String title = movieObj.getString("title");
Movie m = new Movie(rank, title);
movieList.add(0, m);
} catch (JSONException e) {
}
}
adapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
MyApplication.getInstance().addToRequestQueue(req);
}
}
I want to parse this json but I couldn't parse this json and I have no idea.
{
"level":[
{
"server":[
{"rank":1,"title":"The Shawshank Redemption"},
{"rank":2,"title":"The Godfather"},
{"rank":3,"title":"The Godfather: Part II"},
{"rank":4,"title":"The Dark Knight"}
]
}
]
}
How Can I do that?
Thank you.
I would strongly suggest to move towards Gson.
Here is the code for fetchMovies if you don't want to make the change:
private void fetchMovies() {
String url = "http://www.url.com/test.json";
JsonObjectRequest req = new JsonObjectRequest(url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray level = response.getJSONArray("level");
JSONObject item = level.getJSONObject(0);
JSONArray server = item.getJSONArray("server");
for (int i = 0; i < server.length(); i++) {
try {
JSONObject movieObj = server.getJSONObject(i);
int rank = movieObj.getInt("rank");
String title = movieObj.getString("title");
Movie m = new Movie(rank, title);
movieList.add(0, m);
} catch (JSONException e) {
}
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
MyApplication.getInstance().addToRequestQueue(req);
}
I am using json volley to for getting information from google api.I know how to display text in listview but dont know how to display images because they are in string form i really dont know how to convert that string into image and display in listview . here is my code
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ListView lst_1;
Button btn_one;
String url;
ArrayList<CostumAdapter> contactList;
private ProgressDialog progress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main);
contactList = new ArrayList<>();
lst_1 = (ListView) findViewById(R.id.lst_1);
btn_one = (Button) findViewById(R.id.btn_1);
btn_one.setOnClickListener(this);
}
public void Progress() {
progress = new ProgressDialog(this);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setMessage("Loading");
progress.show();
}
private void jsonfunction() {
Progress();
url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?" +
"location=-33.8670522,151.1957362&" +
"radius=500&" +
"type=restaurant&" +
"key=AIzaSyAG5Fndg4wPzs81FNv5-Ycl7GDlAdqeIaI" +
"&sensor=true";
Log.e("url", url);
final StringRequest stringrequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("response", response);
try {
JSONObject jsonobj = new JSONObject(response);
JSONArray jsonArray = jsonobj.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
JSONArray jsonArray2 = object.getJSONArray("photos");
for (int a = 0; a < jsonArray2.length(); a++) {
JSONObject object2 = jsonArray2.getJSONObject(a);
contactList.add(new CostumAdapter(
jsonArray.getJSONObject(i).getString("name"),
object2.getString("photo_reference")
));
}
}
Log.e("response in a", String.valueOf(contactList));
} catch (JSONException e) {
Toast.makeText(MainActivity.this, "error in jason", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
function();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(MainActivity.this, "error in ErrorListener", Toast.LENGTH_LONG).show();
}
});
singalton.getinstance(MainActivity.this).addtorequestque(stringrequest);
}
public void function() {
CustomListAdapter adapter = new CustomListAdapter(getApplicationContext(), R.layout.custumlistview, contactList);
lst_1.setAdapter(adapter);
}
#Override
public void onClick(View v) {
jsonfunction();
}
}
I've 2 APIs and two spinners: one for state's list and another for city's list. In some cases the city list's JSONArray might be null. So I want to check in volley's JSON parsing if its null then set some default message in spinner. But its not showing the default message. Instead its showing the city list of the state which is by default set. Is there any solution for this?
// null city list
{
"citylist": []
}
// JSON for state list
{
"statelist": [
{
"state_id": "1",
"state_name": "West bengal"
},
{
"state_id": "3",
"state_name": "Himachal Pradesh"
},
{
"state_id": "4",
"state_name": "Maharashtra"
},
{
"state_id": "11",
"state_name": "Queensland"
}
]
}
public class MainActivity extends AppCompatActivity {
private static final String STATE = "http://example.com/ubooktoday/android/showstatebycountry";
private static final String CITY = "http://example.com/ubooktoday/android/showcitybystate";
Spinner spin1, spin2;
String stateid, cityid, zipid;
ArrayList<String> namelist, idlist;
ArrayAdapter<String> adapter;
HashMap<String,String> spinnerMap1, spinnerMap2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spin1=(Spinner)findViewById(R.id.spin1);
spin2=(Spinner)findViewById(R.id.spin2);
namelist = new ArrayList<String>();
idlist = new ArrayList<String>();
loadstate();
spin1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String statename = spin1.getSelectedItem().toString();
stateid = spinnerMap1.get(statename);
//Toast.makeText(getApplicationContext(), stateid, Toast.LENGTH_SHORT).show();
loadcity();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
spin2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String cityname = spin2.getSelectedItem().toString();
cityid = spinnerMap2.get(cityname);
Toast.makeText(getApplicationContext(), cityid, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void loadstate() {
if(namelist!=null )namelist.clear();
if(idlist!=null )idlist.clear();
StringRequest stringRequest = new StringRequest(Request.Method.POST, STATE,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
JSONArray jsonArray = jObj.getJSONArray("statelist");
for(int i=0; i<jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
namelist.add(obj.getString("state_name"));
idlist.add(obj.getString("state_id"));
String[] spinnerArray = new String[idlist.size()];
spinnerMap1 = new HashMap<String, String>();
for (int j = 0; j < idlist.size(); j++)
{
spinnerMap1.put(namelist.get(j),idlist.get(j));
spinnerArray[j] = namelist.get(j);
}
adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_spinner_item, spinnerArray);
spin1.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("country_id", "2");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
private void loadcity() {
if(namelist!=null )namelist.clear();
if(idlist!=null )idlist.clear();
StringRequest stringRequest = new StringRequest(Request.Method.POST, CITY,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
JSONArray jsonArray = jObj.getJSONArray("citylist");
if(jsonArray.equals("null")){
namelist.add("No Items");
adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_spinner_item, namelist);
spin2.setAdapter(adapter);
}else{
for(int i=0; i<jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
namelist.add(obj.getString("city_name"));
idlist.add(obj.getString("city_id"));
String[] spinnerArray = new String[idlist.size()];
spinnerMap2 = new HashMap<String, String>();
for (int j = 0; j < idlist.size(); j++)
{
spinnerMap2.put(namelist.get(j),idlist.get(j));
spinnerArray[j] = namelist.get(j);
}
adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_spinner_item, spinnerArray);
spin2.setAdapter(adapter);
}
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("state_id", stateid);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}
Use below code for checking json array condition,
if(jsonArray == null || jsonArray.equals("null") || jsonArray.length <= 0)
{
namelist.add("No Items");
adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_spinner_item, namelist);
spin2.setAdapter(adapter);
}
I have two images in JSONArray. First is an image and other is thumbnail of a video. The thumbnail is showing but the image does not appears. I'm unable to understand what's the problem. I would be pleased to have any help to properly fetch the json.
public class MainActivity extends AppCompatActivity {
private GridView mGridView;
private GridItem newItem;
private GridViewAdapter mGridAdapter;
private ArrayList<GridItem> mGridData;
public static final String KEY_USERID = "user_id";
private static final String REGISTER_URL = "http://xxx.xxx.xxx.xxx:8001/api/userlog/fetch/";
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGridView = (GridView)findViewById(R.id.gridView);
registerUser();
mGridData = new ArrayList<>();
mGridAdapter = new GridViewAdapter(this, R.layout.profile_gridview_item, mGridData);
mGridView.setAdapter(mGridAdapter);
}
///////////////////////////////////////// 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) {
try {
JSONObject jObj = new JSONObject(response);
System.out.println(jObj);
String status = jObj.getString("status");
// Now check status value
if (status.equals("0")) {
Toast.makeText(getApplicationContext(), "There was some error! Please try again.", Toast.LENGTH_LONG).show();
}else if(status.equals("1")){
JSONArray result = jObj.getJSONArray("results");
for(int i = 0 ; i <result.length() ; i++){
JSONObject json_data = result.getJSONObject(i);
newItem = new GridItem();
String image = json_data.getString("log_file");
String date = json_data.getString("create_day");
String month = json_data.getString("create_month");
newItem.setImage(image);
newItem.setDate(date);
newItem.setMonth(month);
mGridData.add(newItem);
}
mGridAdapter.setGridData(mGridData);
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_USERID, "1");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
///////////////////////////////////////// Volley Method Ends ////////////////////////////////////////////////////////////////////
}