i get data from json to list view
for (int i = 0; i < following.length(); i++) {
JSONObject c = following.getJSONObject(i);
// Storing each json item in variable
String nama = c.getString(KEY_NAMA);
String instansi = c.getString(KEY_INSTANSI);
String status = c.getString(KEY_STATUS);
id_user = c.getString(KEY_ID_USER);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_NAMA, nama);
map.put(KEY_INSTANSI, instansi);
map.put(KEY_STATUS, status);
map.put(KEY_ID_USER, id_user);
// adding HashList to ArrayList
followingList.add(map);
}
and action if listview on click
list = (ListView) activity.findViewById(R.id.listView1);
// Getting adapter by passing xml data ArrayList
adapter1 = new LazyAdapter(activity, followingList);
list.setAdapter(adapter1);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent profil = new Intent(activity.getApplicationContext(),
ProfilFollower.class);
profil.putExtra("id_user", id_user);
profil.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
activity.startActivity(profil);
// Closing dashboard screen
activity.finish();
}
});
My question how to get id_user from list view to get if on click and send id_user parameter for intent
you can get id_user from followingList HashMap when user clicked on any ListView row as:
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
if(followingList.size()>0){
HashMap<String, String> selected_user_info=followingList.get(position);
String str_user_id=selected_user_info.get(KEY_ID_USER);
//... do your work here
}
}
You can use the below
In your onItemClick(params) methods
Intent profil = new Intent(ActivityName.this,
ProfilFollower.class);
profil.putExtra("id_user",
followingList.get(position).map.get(KEY_ID_USER).toString());
//map.get(KEY_ID_USER) where KEY_ID_USER is the key
Also declare
HashMap<String, String> map = new HashMap<String, String>();
before onCreate() inside the activity class
Also use this condiditon if(followingList.size()>=position) as ρяσѕρєя K suggested in his answer. To know why the condition is necessary check the comment's in ρяσѕρєя K's answer
Also check the link below and answer by commonsware. Use Activity context in place of getApplicationContext()
When to call activity context OR application context?
You can use Collection class to dispatch the values of the particular list row using values() of Collection class. And then you can convert it as ArrayList. Then you can access each value of your clicked list row.
Example code.
Collection<Object> str = followingList.get(position).values();
ArrayList<Object> al1 = new ArrayList<Object>(str);
String idUser = al1.get(id_user).toString(); // if your id_user has global access.
//Otherwise you could use something al1.get(0).toString() like this.
Intent profil = new Intent(ActivityName.this,
ProfilFollower.class);
profil.putExtra("id_user", idUser);
I hope this will help you.
Related
First of all, i am sorry because there is similar question that already been asked before. I've tried but it does not worked in my program. Hence, I need some help from you to help me to finish my program. Thank you.
Problem : my list cannot be click to go to next activity.
ListPending.java
public void getTable(String r) {
final ListView lv;
lv = (ListView) findViewById(R.id.lsApproval);
ArrayList<HashMap<String, String>> feedList= new ArrayList<HashMap<String, String>>();
try {
JSONArray jArray = new JSONArray(r);
JSONObject jInit = jArray.getJSONObject(0);
String valid = jInit.getString("valid");
String none="NO";
String empty="EMPTY";
TextView tv;
tv = (TextView)findViewById(R.id.tvNone);
if (valid.equals(none))
{
TextView tv1,tv2,tv3;
tv1 = (TextView)findViewById(R.id.tvSname);
tv2 = (TextView)findViewById(R.id.tvDest);
tv3 = (TextView)findViewById(R.id.tvDate);
tv.setText("\n\n\n\n\n\n" + "You do not have applicant under your approval" + "\n\n\n\n" );
tv1.setText("");
tv2.setText("");
tv3.setText("");
}
else if (valid.equals(empty))
{
TextView tv1,tv2,tv3;
tv1 = (TextView)findViewById(R.id.tvSname);
tv2 = (TextView)findViewById(R.id.tvDest);
tv3 = (TextView)findViewById(R.id.tvDate);
tv.setText("\n\n\n\n\n\n" + "No Pending List" + "\n\n\n\n" );
tv1.setText("");
tv2.setText("");
tv3.setText("");
}
else
{
String j=String.valueOf(jArray.length());
tv.setText("Have " +j+" applications need your approval");
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
String date = json.getString("dtfrom");
StringTokenizer tk = new StringTokenizer(date);
String dat = tk.nextToken(); // <--- yyyy-mm-dd
String staff = json.getString("staffname");
String dest = json.getString("destination");
HashMap<String, String> map = new HashMap<String, String>();
map.put("image", String.valueOf(R.mipmap.view));
map.put("staff", staff);
map.put("dest", dest);
map.put("date", dat);
feedList.add(map);
SimpleAdapter simpleAdapter = new SimpleAdapter(this, feedList, R.layout.list_pending,
new String[]{"staff", "dest","date","image"},
new int[]{R.id.tvStaff, R.id.tvDest, R.id.tvDate, R.id.ibView});
lv.setAdapter(simpleAdapter);
// React to user clicks on item
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
long id) {
Toast.makeText(ListPending.this, "try" , Toast.LENGTH_SHORT).show();
}
});
}
}
it successfully show the data from database but not clickable.
This kind of problem occur when another object on the list is either focusable or clickable. The solution is to:
Inspect your layout xml file and make sure that none of the views you are having on your list has its android:clickable set to true.
Avoid to use any clickable view like a button on your list, as this will make your list not clickable.
First of all find the views which are getting focus and not allow list to be focused and touch in all other views put
focusable=false and focusintouchMode=false in xml
and if it is still not allowing your listview to be clicked then can share your problem again.
Seem your view is not taking focus in listview.It's the issue of view when you click the list row, it is always the capture other view event. apply below property to your main layout in row file (list_pending.xml) and let me know whether its works or not?
android:descendantFocusability="blocksDescendants"
or programmatically
listView.setDescendantFocusability(ListView.FOCUS_BLOCK_DESCENDANTS);
hi can you help me how to display the next 10 data in json by click the next button. i have 50 data and i want to display first 10. Then when I click the next button, 11-20 will display in listview. Ill post my code below and i dont have any idea how to do it. Also when i click previous button it will go back to previous listview which is 1-10. Thanks!
doctordata = new ArrayList<Map<String, String>>();
try {
jsonObject = new JSONObject(d);
jsonArray = jsonObject.optJSONArray("Doctors");
int arraylength = jsonArray.length();
for (int i = 0; i < arraylength; i++) {
Map<String, String> doctormap = new HashMap<String, String>();
JSONObject jsonChildNode = jsonArray.getJSONObject(i);
doctor = jsonChildNode.optString("Name").toString();
specialty = jsonChildNode.optString("Specialty").toString();
doctormap.put("name", doctor);
doctormap.put("specialty", specialty);
doctordata.add(doctormap);
}
String[] from = {"name", "specialty"};
int[] views = {R.id.doctorlist_name, R.id.doctorlist_specialty,};
final SimpleAdapter myadapter = new SimpleAdapter(MainActivity.this, doctordata, R.layout.doctor_list, from, views);
list.setAdapter(myadapter);
} catch (JSONException e) {
e.printStackTrace();
}
Define a class called Doctors, with fields String name and String Specialty, and add the Doctors to a list that you can iterate or convert to Array.
class Doctors {
private final String specialty;
private final String name;
public Doctors (){
specialty= "Spe1";
name = "name";
}
}
public String convertToJson(){
Gson gson = new Gson();
return gson.toJson(this);
}
Ok, there are several ways to do what do you want to achieve. I will explain you how I would do it:
Firts, in the doctorData arraylist you have all the items (50 items) that you need to show.
Create a partialDoctorData arraylist and assing to it only the first 10 items from doctorData, ok? and add this new arraylist to the SimpleAdaper.
So you will need to do instead of your code:
final SimpleAdapter myadapter = new SimpleAdapter(MainActivity.this, **partialDoctorData**, R.layout.doctor_list, from, views);
list.setAdapter(myadapter);
So when the user click in the next button, you can clean the partialDoctorData content, add from the 11-20 items from the original doctorData arrayList and and and directly call to the
myadapter.notifyDataSetChanged();
(you don't have to repeat the step to create a new SimpleAdapter, only changing the values of the arraylist and calling to this method, the content of the list is going to be updated with the content of the partialDoctorData)
Try ;)
Try this one:
Android ListView with Load More Button
You can use pagination when 10 items will be loaded after that you will call agin api to get next 10 items
Trying to make a listview with data from JSON. phonelist decalred below hold the data parsed from the json.
ArrayList<HashMap<String, String>> phonelist = new ArrayList<HashMap<String, String>>();
I am doing this in onCreateView of the fragment
for (int i = 0; i < phone.length(); i++) {
try {
JSONObject c = phone.getJSONObject(i);
String phId = c.getString("ph_id");
String phNo = c.getString("ph_no");
HashMap<String, String> map = new HashMap<String, String>();
map.put("ph_id", phId);
map.put("ph_no", phNo);
phonelist.add(map);
} catch (JSONException e) {
e.printStackTrace();
}
}
ListView list = (ListView) rootView.findViewById(R.id.listview1);
ListAdapter adapter = new SimpleAdapter(getActivity(), phonelist,
R.layout.list_item_phone,
new String[]{"ph_id", "ph_no"}, new int[]{
R.id.txtPhoneID, R.id.txtPhoneNum});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//TODO
}
});
The phonelist is getting populated from json and here is its content
[{ph_id=1, ph_no=0120-2550000}, {ph_id=2, ph_no=1860-180-3474}, {ph_id=3, ph_no=0120-4698114}, {ph_id=4, ph_no=0361-2525256}, {ph_id=5, ph_no=033-2525368}, {ph_id=6, ph_no=011-25252525}, {ph_id=7, ph_no=0361-2525257}, {ph_id=8, ph_no=033-2525369}, {ph_id=9, ph_no=011-25252526}, {ph_id=10, ph_no=0361-2525258}, {ph_id=11, ph_no=033-2525370}, {ph_id=12, ph_no=011-25252527}]
For some reason though, only the first item shows up in the listview.
Edit:
Declaration of the phone variable
JSONArray phone = null;
And then I am getting its value onCreate like below
phone = ((JSonArrayParser) getArguments().getParcelable("phoneJsonArray")).getJsonArray();
phone.length is showing correct value (12)
HashMap is specified as key and value, based on webpage # Map. Search text for "put (K key, V value)" for reference. In your code:
map.put("ph_id", phId);
map.put("ph_no", phNo);
I can see only 2 keys are added into this map object, even though you added lots of data from JSON.
As a suggestion, instead of literal string "ph_id" as the key, you can have variable phId as key instead, and the value can be phNo. That can be one code design.
Maybe it's a good idea if you post the SimpleAdapter also, especially in getView().
I have a problem to retrieve the value of a spinner when I want to validate my insertion.
here is how I fill my spinner :
ArrayList<HashMap<String, String>> myArrayList;
myArrayList= new ArrayList<HashMap<String, String>>();
for (int i = 0; i < studentList.length(); i++) {
JSONObject c = studentList.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", id);
map.put("name", name);
myArrayList.add(map);
}
and after :
SpinnerAdapter studentAdapter = new SimpleAdapter(
MyActivity.this, myArrayList,
R.layout.student, new String[] { "id", "name"},
new int[] { R.id.id, R.id.name });
mySpinner.setAdapter(studentAdapter);
When I click on my button "OK", and I get the value of the spinner with
mySpinner.getSelectedItem().toString();
I get :
{id=2, name=Smith}
But i'm sure there is another method to retrieve only the name, but how? By getting the adapter with the spinner? It is my problem...
Thank you
The object the Spinner is giving you is a HashMap. Cast it as such, and then extract the value the way you normally would:
String studentName = ((HashMap)mySpinner.getSelectedItem()).get("name");
Another option: rather than using ArrayList<HashMap> to populate your Spinner, you may want to do it with ArrayList<Student> (assuming Student is a class you already have at your disposal). You can then cast the currently-selected object to Student and use it as you please:
String studentName = ((Student)mySpinner.getSelectedItem()).name;
i'm sure there is another method to retrieve only the name, but how?
You can use an OnItemSelectedListener which will always have the user's current choice:
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
// Do with name as you please
}
Or you could use the same technique with getSelectedView() to only get the name after your validation.
String data="{id=2, name=Smith}";//you retrieved
String array[]=data.split("name=");//split in values of '**id=2,** ' and '**Smith**'
String name=array[array.length-1]; //take last value
You will have 'Smith' in name variable. Not prefered but if no choice then use it
I've got a little problem, and i don't see it.
I retrieve Json data (the JSONArray) and i wanted to make a List of all the names in the JSONArray, something like this.
List list = new ArrayList<String>();
for(int i=0;i < data.length();i++){
list.add(data.getJSONObject(i).getString("names").toString());
}
And i wanted to take this list in an `ListView' so i did this :
ArrayList<String> test = history_share.list;
names_list = (String[]) test.toArray();
ArrayAdapter<String> adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, names_list);
setListAdapter(adapter);
(history_share is one of the method i created to take json data from an api .
Eclipse doesn't see any error, and me neither.
Can somebody help me please ?
Why do your methods have underscores in their names? Methods by convention begin with a lowercase letter. For example myMethod(). Class names begin with uppercase letters like MyClass. You should stick to that.
Also history_share is not a method the way you posted your code plus you won't be able to retrieve anything from a method by calling it that way.
A getter method just returns the defined member. I'm very surprised that Eclipse doesn't highlight that. Are you sure error checking is turned on?
Update: Naming your classes like already existing classes is generally a very bad idea and it gets even worse if you plan to use the original class somewhere or any class deriving that class. In the original Connection class I cant spot any static member called list which leads to the assumption that you've created your own Connection class. This doesn't have to be the problem here but it may raise problems in the future if you continue to do that.
for(int i=0;i < data.length();i++){
list.add(data.getJSONObject(i).getString("names").toString());
}
.getString("names") returns String, remove .toString()
Also,
ArrayAdapter<String> adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, names_list);
replace with
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, names_list);
You try this using ArrayList with Hashmap:
ArrayList<HashMap<String, String>> comunitylist = new ArrayList<HashMap<String, String>>();
String url =_url + _uid + uid;
JSONParstring jParser = new JSONParstring();
// getting JSON string from URL
String json = jParser.getJSONFromUrl(url,apikey);
Log.e("kPN", json);
try
{
JSONObject jobj = new JSONObject(json);
Log.e("kPN", json.toString());
System.out.print(json);
JSONArray comarray = jobj.getJSONArray(TAG_COMMU);
for(int i = 0; i <= comarray.length(); i++){
JSONObject c = comarray.getJSONObject(i);
Log.w("obj", c.toString());
JSONObject d = c.getJSONObject(TAG_PERSON);
Log.w("obj", d.toString());
String name =d.getString(TAG_NAME);
Log.w("name", name);
String nick =d.getString(TAG_NICK);
String home = d.getString(TAG_HOME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_NAME, name);
map.put(TAG_NICK, nick);
}
}
catch (JSONException ie)
{
}
list=(ListView)findViewById(R.id.list);
adapter=new Lazycommunity(this,listz);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#SuppressWarnings("unchecked")
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Having Trouble with this line, how to retrieve value???
HashMap<String, String> map2 = (HashMap<String, String>) list.getAdapter().getItem(position);
Intent in = new Intent(getApplicationContext(), Communityprofile.class);
in.putExtra(TAG_NAME, map2.get(TAG_NAME));
in.putExtra(TAG_IMG, map2.get(TAG_IMG));
startActivity(in);
}
});