can anyone suggest that how to create expandable list-view with Json data, i want to parse json data in my expandable list view, plss suggest how can i create
This is exactly what you looking for,you can parse and display data to ExpandableListview
See this : http://www.tutorialsbuzz.com/2015/02/android-expandable-listview-json-http.html
public class MainActivity extends Activity {
String url = "http://api.tutorialsbuzz.com/cricketworldcup2015/cricket.json";
ProgressDialog PD;
private ExpandListAdapter ExpAdapter;
private ExpandableListView ExpandList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ExpandList = (ExpandableListView) findViewById(R.id.exp_list);
PD = new ProgressDialog(this);
PD.setMessage("Loading.....");
PD.setCancelable(false);
makejsonobjreq();
}
private void makejsonobjreq() {
PD.show();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, url,
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
ArrayList<Group> list = new ArrayList<Group>();
ArrayList<Child> ch_list;
try {
Iterator<String> key = response.keys();
while (key.hasNext()) {
String k = key.next();
Group gru = new Group();
gru.setName(k);
ch_list = new ArrayList<Child>();
JSONArray ja = response.getJSONArray(k);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = ja.getJSONObject(i);
Child ch = new Child();
ch.setName(jo.getString("name"));
ch.setImage(jo.getString("flag"));
ch_list.add(ch);
} // for loop end
gru.setItems(ch_list);
list.add(gru);
} // while loop end
ExpAdapter = new ExpandListAdapter(
MainActivity.this, list);
ExpandList.setAdapter(ExpAdapter);
PD.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
PD.dismiss();
}
});
MyApplication.getInstance().addToReqQueue(jsonObjReq, "jreq");
}
}
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'm using volley for web services. So, when I run the app each time it doesn't show anything in the list. But when I use debug, sometimes I got the list correctly. So here is the code.
It's like it insert the listItem on Listview before getting the data from json , i tried to put a wait() before the adapter but android studio don't accept it .
Is there anyone who had similar problem ?
public class listedeal_res extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listedeal_res);
Button ajouter=(Button) findViewById(R.id.ajouetres);
Intent i =getIntent();
final ListView maListView = (ListView) findViewById(R.id.liste_deal_res);
final int idres=i.getIntExtra("idres",0);
final boolean b =true;
ajouter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(listedeal_res.this,AjouterDeal.class);
intent.putExtra("idres",idres);
listedeal_res.this.startActivity(intent);
}
});
final ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>();
final HashMap<String, String> map;
map = new HashMap<String, String>();
Response.Listener<String> resp=new Response.Listener<String>()
{
#Override
public void onResponse (String response) {
try {
JSONArray jsonResponse = new JSONArray(response);
int i=0;
while (jsonResponse.getJSONArray(i)!=null)
{
while (jsonResponse.getJSONArray(i)!=null)
{
map.put("Nom",jsonResponse.getJSONArray(i).getString(2));
map.put("Restraurant",jsonResponse.getJSONArray(i).getString(0));
map.put("description",jsonResponse.getJSONArray(i).getString(1));
listItem.add(map);
i++;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
drinkeat.drinkandeat.javas.liste_deal_res_req liste_deal_res_req= new liste_deal_res_req(idres+"",resp);
RequestQueue queue= Volley.newRequestQueue(listedeal_res.this);
queue.add(liste_deal_res_req );
SimpleAdapter mSchedule = new SimpleAdapter (this.getBaseContext(), listItem, R.layout.row_deal_user,
new String[] {"Nom", "Restraurant", "description"}, new int[] {R.id.titlerow, R.id.resteaurantnaamerow, R.id.descriptionrow});
maListView.setAdapter(mSchedule);
}
}
Add notifydatasetchange method to your adapter like below
public void onResponse (String response) {
try {
JSONArray jsonResponse = new JSONArray(response);
int i=0;
while (jsonResponse.getJSONArray(i)!=null)
{
while (jsonResponse.getJSONArray(i)!=null)
{
map.put("Nom",jsonResponse.getJSONArray(i).getString(2));
map.put("Restraurant",jsonResponse.getJSONArray(i).getString(0));
map.put("description",jsonResponse.getJSONArray(i).getString(1));
listItem.add(map);
i++;
}
}
mSchedule.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
My data comes dynamically in an array of textviews and I am entering some data in edit texts beside that.
All the data comes in the listview.
what I need to do is I need to transfer all the data in the text views as well as edittexts to another screen on a button click.
How will I achieve that?
Here is my code:
public class S1 extends ListActivity implements OnClickListener {
private ProgressDialog pDialog;
ListView lv;
Button b;
String arry1[], category_main;
int i,key = 0;
private static String url = "http://ashapurasoftech.com/train/test.json";
private static final String TAG_a = "menu",TAG_Name = "Name",TAG_Cat = "Category";
JSONArray items = null;
ArrayList<HashMap<String, String>> itemList;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.table1);
lv =getListView();
category_main = "";
new Getitems().execute(category_main);
b =(Button) findViewById(R.id.start);
b.setOnClickListener(this);
itemList = new ArrayList<HashMap<String, String>>();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_Name, name);
startActivity(in);
}
});
}
#Override
public void onClick(View arg0) {
switch(arg0.getId()){
case R.id.start: try {
onbuttonclick();
} catch (JSONException e) {
e.printStackTrace();
}
break;
}
}
private void onbuttonclick() throws JSONException {
Set<String> arry = new HashSet<String>();
for(int k=0;k<items.length();k++)
{
JSONObject c = items.getJSONObject(k);
String category = c.getString(TAG_Cat);
arry.add(category);
}
arry1 = arry.toArray(new String[arry.size()]);
TableRow[] tr = new TableRow[arry1.length];
TextView[] tx = new TextView[arry1.length];
TableLayout tl = (TableLayout) findViewById(R.id.tablelayout1);
for (i = 0; i < arry1.length; i++) {
final String cat = arry1[i].toString();
tx[i] = new TextView(S1.this);
tx[i].setLayoutParams(new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tx[i].setText(cat);
tr[i] = new TableRow(S1.this);
tr[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tr[i].addView(tx[i],new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tl.addView(tr[i],new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tx[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
category_main = cat;
if (key==0)
{
key=1;
lv.setVisibility(View.VISIBLE);
}
else if(key==1)
{
key=0;
lv.setVisibility(View.GONE);
}
new Getitems().execute(category_main);
}
});
}
b.setVisibility(View.GONE);
}
private class Getitems extends AsyncTask<Void, Void, Void> {
String cat12 = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(S1.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.show();
}
public void execute(String categorymain) {
cat12 = categorymain;
execute();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
items = jsonObj.getJSONArray(TAG_a);
for (i = 0; i < items.length(); i++) {
final JSONObject c = items.getJSONObject(i); String cate12 = c.getString(TAG_Cat);
String name = c.getString(TAG_Name);
final HashMap<String, String> item = new HashMap<String, String>();
if(cat12.equalsIgnoreCase(cate12))
{
item.put(TAG_Name,name);
itemList.add(item);
}
}
}
catch (JSONException e) {
e.printStackTrace();
} finally {
}}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(
S1.this, itemList,
R.layout.textview, new String[] {TAG_Name},new int[] { R.id.name});
setListAdapter(adapter);
}
}
}