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);
Related
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().
Since my ListView is in a ScrollView and there is a complex layout above the ListView I had to set that layout to be the header of the ListView. This made things work wonderfully, except one thing: When the ListView has no items, the header does not show up. This header is basically the base of the whole layout, the ListView includes only comments written by users.
I checked solutions like this and this and this and others but I still don't know what to do.
This is how I set the header for the ListView:
lv = (ListView) findViewById(R.id.bucket_profile_lv);
LayoutInflater inflater=getLayoutInflater();
header = inflater.inflate(R.layout.bucket_profile_header,null,false);
lv.addHeaderView(header);
When I am downloading the data for the header, it has nothing to do with the adapter of the ListView. I refer to them as
num_added = response.getString("NUM_ADDED");
tv_num_added.setText(String.valueOf(num_added));
where
tv_num_added = (TextView) header.findViewById(R.id.bucket_profile_bucket_no_added);
When I am downloading the comments, I put the result (username, photo, comment etc.) in arrays and link them to an adapter:
if (response.length() > 10) {
try {
jArray = new JSONArray(response);
for(int i=0;i<jArray.length();i++){
JSONArray innerJsonArray = jArray.getJSONArray(i);
for(int j=0;j<innerJsonArray.length();j++){
JSONObject jsonObject = innerJsonArray.getJSONObject(j);
arr_tips_id.add(jsonObject.getString("COMMENTID"));
arr_tips_userid.add(jsonObject.getString("ID"));
arr_tips_username.add(jsonObject.getString("USERNAME"));
arr_tips_userphoto.add(jsonObject.getString("PHOTO"));
arr_tips_fbuserid.add(jsonObject.getString("FB_USERID"));
arr_tips_imagetype.add(jsonObject.getString("IMAGE_TYPE"));
arr_tips_twuserid.add(jsonObject.getString("TW_USERID"));
arr_tips_twphoto.add(jsonObject.getString("TW_PHOTO"));
arr_tips_tips.add(jsonObject.getString("COMMENT"));
arr_tips_date.add(jsonObject.getString("TIMEDIFF"));
myadapter = new MyAdapter(BucketProfileActivity.this, arr_tips_id, arr_tips_userid, arr_tips_username, arr_tips_userphoto, arr_tips_fbuserid, arr_tips_imagetype, arr_tips_twuserid, arr_tips_twphoto, arr_tips_tips, arr_tips_date);
lv.setAdapter(myadapter);
lv.setVisibility(View.VISIBLE);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
/*Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss:SSS");
String strDate = sdf.format(c.getTime());
Toast.makeText(BucketProfileActivity.this, "3 -- " + strDate + "", Toast.LENGTH_LONG).show();*/
} else {
Toast.makeText(BucketProfileActivity.this, "No comments, how to show header?", Toast.LENGTH_SHORT).show();
lv.setVisibility(View.VISIBLE);
}
In my adapter I have overriden isEmpty() but it didn't help:
#Override
public boolean isEmpty() {
return false;
}
Please help.
Don't use addHeaderView. Instead make the header as a separate item
<LinearLayout
...
android:orientation="vertical">
<include layout="#layout/bucket_profile_header" />
<ListView
.....
/>
</LinearLayout>
Initialize your adapter once, for example when you inflate your views in onCreate() or onCreateView() and also set your adapter to your listview (after you added your headerView).
In your JSON iteration loop do something like this:
myadapter.addItem(arr_tips_date);
In your adapter you have to create this method, which adds your data item to its internal adapter collection and call notifyDataSetChanged().
Then it should work just fine.
I am parsing JSON into a textview and i need some help trying to put that into a listview instead. I know this might be very easy for some, but my main focus of confusion is that in a textview, you are setting the text using the setText function. I am also new to android, so I don't have this basic down yet, but I appreciate any help in advance, thank you.
public void onClick(View arg0) {
TextView tv1 = (TextView) findViewById(R.id.textView1);
TextView tv2 = (TextView) findViewById(R.id.textView2);
try {
String buildings = getJSON("http://iam.colum.edu/portfolio/api/course?json=True");
//JSONObject jsonObject = new JSONObject(buildings);
JSONArray queryArray = new JSONArray(buildings);
//queryArray = queryArray.getJSONArray(0);
List<String> list = new ArrayList<String>();
for (int i=0; i<queryArray.length(); i++) {
list.add( queryArray.getString(i) );
}
String finaltext="";
StringBuilder sb = new StringBuilder();
for (int i=0; i<queryArray.length(); i++) {
// chain each string, separated with a new line
sb.append(queryArray.getString(i) + "\n");
}
// display the content on textview
tv1.setText(sb.toString());
//tv1.setText(arr[0]);
} catch (Exception e) {
e.printStackTrace();
Log.d("JSONError", e.toString());
}
}});
Basically you add your ListView in your layout file, and then in the code you set an Adapter on the ListView, which holds the data. And then all the magic is going to be done for you.
Please read
http://developer.android.com/guide/topics/ui/layout/listview.html
http://developer.android.com/guide/topics/ui/declaring-layout.html#AdapterViews
So in your case it would look something like this:
ListView listView = (ListView) findViewById(R.id.listview);
...
JSONArray queryArray = new JSONArray(buildings);
//queryArray = queryArray.getJSONArray(0);
ArrayList<String> list = new ArrayList<String>();
for (int i=0; i<queryArray.length(); i++) {
list.add( queryArray.getString(i) );
}
ArrayAdapter adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
This will take the content of your list and create one ListView item for each entry. The text is set to the layout file android.R.layout.simple_list_item_1 which is provided by android.
If you change the content of the ArrayAdapter (and thus the ListView) you have to call adapter.notifyDataSetChanged() to inform the system that the content has changed.
To change the layout, or add an Adapter for other data sources, please refer to the documentation.
I am feeding a ListView from a database in this way (nothing special), except
COL_TXT_TRANSL2 contains html formatting:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
mCurrBookID = extras.getString("BookID");
mCurrChapterNum = extras.getString("ChapterNum");
mCurrChapterTitle = extras.getString("ChapterTitle");
mGitaDB= Central.mDB;
this.setTitle(mCurrChapterNum+"."+mCurrChapterTitle);
setContentView(R.layout.chapterdisplay);
//set chapter intro
TextView tvIntro=(TextView) findViewById(R.id.textIntro);
tvIntro.setText(Html.fromHtml(extras.getString("ChapterIntro")));
try {
String[] columns = new String[] { mGitaDB.COL_TXT_TEXT_NUM, mGitaDB.COL_TXT_TRANSL2 };
int[] to = new int[] { R.id.number_entry, R.id.title_entry };
mCursor=mGitaDB.GetGitaTexts(mCurrBookID, mCurrChapterNum);
mAdapter = new SimpleCursorAdapter(this,
R.layout.textslist_row, mCursor, columns, to);
setListAdapter(mAdapter);
}
catch (Exception e) {
String err="Error: " + e.getMessage();
Toast toast = Toast.makeText(Central.context, err, 15000);
toast.show();
}
}
Now the problem is that the text displayed in this ListView has HTML formatting.
How can I make listview display this HTML formatting? Currently it is displayed as a plain text with all tags.
Assuming the HTML is fairly simple you can run it through this method: http://developer.android.com/reference/android/text/Html.html#fromHtml(java.lang.String) The resulting Spannable can be sent to a TextView in the ListView. Beware the fromHtml method is very slow and may slow down scrolling, you might want to cache the Spannables.
Define a CharSequence ArrayList, include all the elements from your database to be displayed in this arraylist as HTML. Include a personal TextView layout for the individual entities of the listView, and display the Charsequence in the list. I had made use of the following code for my app:
List<CharSequence> styledItems = new ArrayList<CharSequence>();
droidDB.open();
articles = droidDB.getAllArticleTitles(feed.feedId);
droidDB.close();
for (Article article : articles) {
styledItems.add(Html.fromHtml(article.title));
}
ArrayAdapter<CharSequence> notes =
new ArrayAdapter<CharSequence>(this, R.layout.feeds_row,styledItems);
setListAdapter(notes);
For the feeds_row.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#FFFFFF"/>
Hope this helps.
My problem was similar to yours. I was reading data from file in json format, where I have objects with id and text fields. text field is html. I have resolved problem this way:
ArrayList<MyObject> myObjectsList = new ArrayList<MyObject>();
ArrayList<HashMap<String, CharSequence>> tableElements = new ArrayList<HashMap<String, CharSequence>>();
String keyword = in.getStringExtra(TAG_KEYWORD);
InputStream is = this.getResources().openRawResource(R.raw.data);
JSONParser jParser = new JSONParser();
myObjectsList = jParser.searchForObjects(is, keyword);
for (MyObject element : myObjectsList)
{
String id = Integer.toString(element.id);
CharSequence text = Html.fromHtml(element.text);
// creating new HashMap
HashMap<String, CharSequence> map = new HashMap<String, CharSequence>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TEXT, text);
// adding HashList to ArrayList
tableElements.add(map);
}
ListAdapter adapter = new SimpleAdapter(this,tableElements,
R.layout.search_item,
new String[] { TAG_ID, TAG_TEXT.toString()}, new int[] {
R.id.exercise_id, R.id.text });
setListAdapter(adapter);