I want to retrieve the data from particular website( "http://api.eventful.com/rest/events/search?app_key=42t54cX7RbrDFczc&location=singapore ),
however, I couldn't managed to retrieve it.
I think there is something wrong with my code but I not sure which part gone wrong.
Could anyone help me out?
This is my coding.
It contains of the spinner date filtering as well.
public class AndroidXMLParsingActivity extends ListActivity implements OnItemSelectedListener {
List<String> browseby = new ArrayList<String>();
Date d = new Date();
String[] dates = { "Today", "Tomorrow", "This Week",
};
ArrayList<String> browse = new ArrayList<String>();
ArrayList<String> mPostingData = new ArrayList<String>();
Spinner s1;
ListView listview;
CustomAdapter cus;
// All static variables
static final String URL = "http://api.eventful.com/rest/events/search?app_key=42t54cX7RbrDFczc&location=singapore";
// XML node keys
static final String KEY_EVENT = "event"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_START_TIME = "start_time";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_EVENT);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_START_TIME, parser.getValue(e, KEY_START_TIME));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item, new String[] { KEY_TITLE,KEY_START_TIME }, new int[] {
R.id.title,
R.id.startTime });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById(R.id.title))
.getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SingleMenuItemActivity.class);
in.putExtra(KEY_TITLE, title);
startActivity(in);
}
});
listview = (ListView) findViewById(R.id.listView1);
s1 = (Spinner) findViewById(R.id.spinner1);
for (int i = 0; i < browseby.size(); i++) {
browse.add(browseby.get(i));
}
// aa = new
// ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,Category);
s1.setOnItemSelectedListener(this);
mPostingData = browse;
for (int i = 0; i < mPostingData.size(); i++) {
if (mPostingData.size() > 0)
Log.i("Datas", mPostingData.get(i));
}
cus = new CustomAdapter(this, 0);
setListAdapter(cus);
ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, dates);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(aa);
}
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
// listview.setFilterText(Category[position]);
String Text = s1.getSelectedItem().toString();
cus.getFilter().filter(Text);
cus.notifyDataSetChanged();
}
public void onNothingSelected(AdapterView<?> parent) {
// listview.setFilterText("");
}
public void onListItemClick(ListView parent, View v, int position, long id) {
Toast.makeText(this, "You have selected " + mPostingData.get(position),
Toast.LENGTH_SHORT).show();
}
class CustomAdapter extends ArrayAdapter<String> {
public void setData(ArrayList<String> mPpst) {
mPostingData = mPpst;// contains class items data.
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected void publishResults(CharSequence constraint,
FilterResults start_time) {
if (start_time != null && start_time.count >= 0) {
setData((ArrayList<String>) start_time.values);
} else {
setData(browse);// set original values
}
notifyDataSetInvalidated();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
if(constraint=="Today") {
constraint = constraint.toString();
CharSequence s = DateFormat.format("yyyy-MM-dd ", d.getTime());
ArrayList<String> foundItems = new ArrayList<String>();
if (browse != null) {
for (int i = 0; i < browse.size(); i++) {
if (browse.get(i).contains(s)){
System.out.println("My datas" + browse.get(i));
foundItems.add(browse.get(i));
} else {
}
}
}
result.count = foundItems.size();// search results found
// return count
result.values = foundItems;// return values
} else {
result.count = -1;// no search results found
}
return result;
}
};
}
LayoutInflater mInflater;
public CustomAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mPostingData.size();
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder vh;
if (convertView == null) {
vh = new ViewHolder();
convertView = mInflater.inflate(R.layout.row, null);
vh.t1 = (TextView) convertView.findViewById(R.id.textView1);
convertView.setTag(vh);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
vh = (ViewHolder) convertView.getTag();
}
if (mPostingData.size() > 0)
vh.t1.setText(mPostingData.get(position));
return convertView;
}
}
static class ViewHolder {
TextView t1;
}
}
have you added this permission in your manifest file
<uses-permission
android:name="android.permission.INTERNET"
></uses-permission>
Related
I googled other solutions but coudn't find any whic is similar to my condition and at first i tried to get the contents of the text view and filter but was not successful please help. so here I have Created a listview which is inflated by three textviews which form like a table each textview is a column and data is added dynamically from the server. How Can filter contents based on the user search.
Here is the code Below.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private void showJSON2(String response){
String id="";
String name="";
String date_from="";
String date_to="";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(JSON_ARRAY2);
ListView listView = (ListView) findViewById(R.id.list_view);
list = new ArrayList<HashMap<String, String>>();
for (int i=0; i<result.length(); i++) {
JSONObject notice = result.getJSONObject(i);
id = notice.getString(KEY_ID);
name = notice.getString(KEY_NAME);
date_from = notice.getString(KEY_DATE_FROM);
date_to = notice.getString(KEY_DATE_TO);
HashMap<String, String> temp= new HashMap<String, String>();
temp.put(FIRST_COLUMN, id);
temp.put(SECOND_COLUMN, name);
temp.put(THIRD_COLUMN, date_from);
temp.put(FOURTH_COLUMN, date_to);
list.add(temp);
}
ListViewAdapters adapter = new ListViewAdapters(this, list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id)
{
int pos=position+1;
Toast.makeText(MainActivity.this, Integer.toString(pos)+" Clicked", Toast.LENGTH_SHORT).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
ListViewAdapters.java -
public class ListViewAdapters extends BaseAdapter{
public ListViewAdapters(Activity activity,ArrayList<HashMap<String, String>> list){
super();
this.activity=activity;
this.list=list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater=activity.getLayoutInflater();
if(convertView == null){
convertView=inflater.inflate(R.layout.colmn_row, null);
txtFirst=(TextView) convertView.findViewById(R.id.name);
txtSecond=(TextView) convertView.findViewById(R.id.gender);
txtThird=(TextView) convertView.findViewById(R.id.age);
txtFourth=(TextView) convertView.findViewById(R.id.status);
}
HashMap<String, String> map=list.get(position);
txtFirst.setText(map.get(FIRST_COLUMN));
txtSecond.setText(map.get(SECOND_COLUMN));
txtThird.setText(map.get(THIRD_COLUMN));
txtFourth.setText(map.get(FOURTH_COLUMN));
return convertView;
}
}
In MainActivity.java,
public class MainActivity extends AppCompatActivity {
ArrayList<HashMap<String, String>> list = new ArrayList<>();
ListViewAdapters adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_default);
adapter = new ListViewAdapters(this, list);
listView.setAdapter(adapter);
}
private void showJSON2(String response) {
...
list.clear();
...
list.add(temp);
...
// ListViewAdapters adapter = new ListViewAdapters(this, list);
// listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
...
}
}
In adapter class,
public class ListViewAdapters extends BaseAdapter {
ArrayList<HashMap<String, String>> origList = new ArrayList<>();
public ListViewAdapters(Activity activity,ArrayList<HashMap<String, String>> list) {
super();
this.activity=activity;
this.list=list;
this.origList=list;
}
...
void filter(String filterString) {
list = new ArrayList<>();
for (HashMap<String, String> item: origList) {
// use your own logic to filter
if (itemShouldBeAdded)
list.add(item); // add if item is inside filter
}
notifyDataSetChanged();
}
void cancelFilter() {
list = origList;
notifyDataSetChanged();
}
}
Now, to filter, call the function filter.
adapter.filter("some_string");
To cancel filter,
adapter.cancelFilter();
I am using this way to filter my list according to user's input.
private void setFilter(EditText et_search_bar, ArrayList<String> list, OnListUpdated onListUpdated) {
if (et_search_bar != null) {
TextWatcher textWatcher;
textWatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// filter your list from your input
if (!previousValue.equalsIgnoreCase(s.toString())) {
if (!TextUtils.isEmpty(s.toString())) {
previousValue = s.toString();
ArrayList<String> temp = new ArrayList<>();
for (String bookmarkBean : list) {
//or use .contains(text)
if (bookmarkBean.toLowerCase().contains(s.toString())) {
temp.add(bookmarkBean);
}
}
//update recyclerview
if (onListUpdated != null) {
onListUpdated.onListFiltered(temp);
}
} else onListUpdated.onListFiltered(filterBean);
}
}
};
et_search_bar.addTextChangedListener(textWatcher);
}
}
and
public interface OnListUpdated {
void onListFiltered(ArrayList<String> list);}
setFilter(et_search_bar, filterBean, new OnListUpdated() {
#Override
public void onListFiltered(ArrayList<String> list) {
// notify your adapter
}
});
Please any one help how to sort images by name.Here am sharing my code.please any one help.
Here am showing images with grid and list .How to sort images by name in grid and list view.Here am using menu by selecting sort by name and sort by size.
// Main Activity
public class MainActivity extends ActionBarActivity {
public RelativeLayout mainLayout;
View gridView,listView;
CountryAdapterList customListAdapter;
CountryAdapter cutomArrayAdapter;
public int swithNo=0;
public String[] country_Names;
public RelativeLayout relativeLayout;
public int[] country_Images = {R.drawable.banglades, R.drawable.bangladesh,
R.drawable.brazi, R.drawable.brazil, R.drawable.chin,
R.drawable.china, R.drawable.indi, R.drawable.india,
R.drawable.indonesi, R.drawable.indonesia, R.drawable.japa,
R.drawable.japan, R.drawable.nigeri, R.drawable.nigeria,
R.drawable.pakista, R.drawable.pakistan, R.drawable.russi,
R.drawable.russia, R.drawable.unitedstate,
R.drawable.unitedstates };
public String[] country_Name_Sort = { "Bangladesh A", "Pakistan",
"Brazil A", "Brazil", "China A","Bangladesh", "China", "India A", "India",
"Indonesia A", "Russia","Indonesia", "Japan A", "Japan", "Nigeria A",
"Nigeria", "Pakistan A", "Russia A",
"UnitesStates A", "UnitesStates" };
public float[] country_Image_size = {1.36f , 1.36f, 4.12f, 4.12f, 1.47f,
1.47f, 1.79f, 1.79f, 0.299f, 0.299f, 1.50f, 1.50f, 0.285f, 0.285f,
1.85f, 1.85f, 0.330f, 0.330f, 3.42f, 3.42f };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Creating a new RelativeLayout
relativeLayout = new RelativeLayout(this);
customListAdapter = new CountryAdapterList(getApplicationContext(),
country_Name_Sort, country_Image_size, country_Images);
cutomArrayAdapter=new CountryAdapter(getApplicationContext(), country_Name_Sort, country_Image_size, country_Images);
// Defining the RelativeLayout layout parameters.
// In this case I want to fill its parent
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT);
relativeLayout.setLayoutParams(rlp);
gridView = getLayoutInflater().inflate(R.layout.activity_deatails_grid,
null);
listView = getLayoutInflater().inflate(R.layout.activity_main_listview,
null);
setViewUpdate(swithNo);
((AdapterView<ListAdapter>) gridView).setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i=new Intent(getApplicationContext(),CountryDetailsScreen.class);
i.putExtra("Position", position);
i.putExtra("Country_Name", country_Name_Sort);
i.putExtra("Country_image", country_Images);
i.putExtra("Country_Image_size", country_Image_size);
startActivity(i);
}
});
((AdapterView<ListAdapter>) listView).setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Intent i=new Intent(getApplicationContext(),CountryDetailsScreen.class);
i.putExtra("Position", position);
i.putExtra("Country_Name", country_Name_Sort);
i.putExtra("Country_image", country_Images);
i.putExtra("Country_Image_size", country_Image_size);
startActivity(i);
}
});
}
private void sortAscending () {
List<String> sortedMonthsList = Arrays.asList(country_Name_Sort);
Collections.sort(sortedMonthsList);
country_Name_Sort = (String[]) sortedMonthsList.toArray();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
menu.add(1, 1, 0, "Grid View");
menu.add(1, 2, 1, "List View");
menu.add(2, 3, 2, "Sort By Name");
menu.add(2, 4, 3, "Sort By Size");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case 1:
Log.d("SwithNo", "One");
swithNo=0;
setViewUpdate(swithNo);
break;
case 2:
Log.d("SwithNo", "Two");
swithNo=1;
setViewUpdate(swithNo);
break;
case 3:
Log.d("SwithNo", "Three");
sortAscending();
for(int i=0;i<country_Name_Sort.length;i++)
{
Log.e("Assending ", " "+country_Name_Sort[i]);
}
((ListView) listView).setAdapter(customListAdapter);
listView.invalidate();
setViewUpdate(swithNo);
break;
case 4 : Log.d("Switch", "Four");
}
return true;
}
public void setViewUpdate(int k)
{
((GridView) gridView).setAdapter(cutomArrayAdapter);
((ListView) listView).setAdapter(customListAdapter);
relativeLayout.removeAllViews();
if(k==0)
{
relativeLayout.addView(gridView);
}
else
{
relativeLayout.addView(listView);
}
setContentView(relativeLayout);
}
}
class Country {
int imageId;
String countryName;
Country(int imageId, String countyName) {
this.imageId = imageId;
this.countryName = countyName;
}
}
class CountryAdapter extends BaseAdapter {
ArrayList<Country> list;
Context context;
String[] country_Name_Sort;
CountryAdapter(Context context,String[] country_Name_Sort,float[] country_Image_size,int[] country_Images) {
this.context = context;
this.country_Name_Sort=country_Name_Sort;
list = new ArrayList<Country>();
/*Resources resource = context.getResources();
String[] country_Names = resource.getStringArray(R.array.coutry_names);*/
for (int i = 0; i < country_Name_Sort.length; i++) {
Country country = new Country(country_Images[i], country_Name_Sort[i]);
list.add(country);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
class ViewHolder {
ImageView county_Image;
TextView country_Name;
ViewHolder(View v) {
county_Image = (ImageView) v.findViewById(R.id.imageView);
country_Name = (TextView) v.findViewById(R.id.countryName);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
View row = convertView;
if (row == null) {
LayoutInflater inflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflator.inflate(R.layout.single_item, parent, false);
viewHolder = new ViewHolder(row);
row.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) row.getTag();
}
Country cntry = list.get(position);
viewHolder.county_Image.setImageResource(cntry.imageId);
viewHolder.country_Name.setText(cntry.countryName);
return row;
}
}
class CountryAdapterList extends BaseAdapter {
ArrayList<Country> list;
Context context;
String[] country_Name_Sort;
int[] country_Images;
CountryAdapterList(Context context,String[] country_Name_Sort,float[] country_Image_size,int[] country_Images) {
this.context = context;
this.country_Name_Sort=country_Name_Sort;
this.country_Images=country_Images;
list = new ArrayList<Country>();
for (int i = 0; i < country_Name_Sort.length; i++) {
Country country = new Country(country_Images[i], country_Name_Sort[i]);
list.add(country);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
class ViewHolder {
ImageView county_Image;
TextView country_Name;
ViewHolder(View v) {
county_Image = (ImageView) v.findViewById(R.id.imageViewList);
country_Name = (TextView) v.findViewById(R.id.countryNameList);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
View row = convertView;
if (row == null) {
LayoutInflater inflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflator.inflate(R.layout.single_item_listview, parent, false);
viewHolder = new ViewHolder(row);
row.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) row.getTag();
}
Country cntry = list.get(position);
viewHolder.county_Image.setImageResource(cntry.imageId);
viewHolder.country_Name.setText(cntry.countryName);
return row;
}
}
you should implement Java's Comparator.
ListView list;
//fill list here.
Collections.sort(list, new Comparator<String>() {
public int compare(final String a, final String b) {
return a.compareTo(b));
}
});
you can compare objects too, using their properties.
public int compare(final LatLong a, final LatLong b) {
return a.latitude.compareTo(b.latitude));
}
By using array sorting you can sort your image names in your application
//String array
String[] strNames = new String[]{"John", "Alex", "Chris", "Williams", "Mark", "Bob"};
sort String array using sort method
Arrays.sort(strNames);
Output of above given Java Sort String Array example would be
String array sorted (case sensitive)
Alex
Bob
Chris
John
Mark
Williams
In the same way, before setting your array data to your lisyt view you can sort it by using Arrays.sort(strNames);
hope it helps
I know this question has been asked thousands of times but I couldn't find an answer for my case for some reason.
What I have is a thread that fetches data from a web services and populates a list with the info. Then I want to press a button and call the same thread to fetch some more data and add it to the list.
But when I call notifyDataSetChanged(), the list for some reason doesn't refresh. The data is in the adapter though...
Here's the code:
#Override
protected void onPostExecute(PropertyNotesParser result) {
this.progressDialog.dismiss();
ArrayList<PropertyNoteHistory> propertyNoteList = result.getAllTheNotes();
addNoteListItems(propertyNoteList);
Collections.sort(getNoteList());
ArrayList<String> titles = new ArrayList<String>();
ArrayList<String> subtitles = new ArrayList<String>();
DateHandler handleDate = new DateHandler();
DataResolve convert = new DataResolve();
for(Iterator<PropertyNoteHistory> i = getNoteList().iterator(); i.hasNext(); ) {
PropertyNoteHistory item = i.next();
PropertyNoteHistory.Note note = item.getNotes();
PropertyNoteHistory.Jobs jobs = item.getJobs();
// Default value is office in case the xml does not have the tag "job" associated with "note".
String service = "Office";
if(jobs != null){
service = convert.getServiceName(jobs.getServiceID());
}
titles.add(note.getTitle() + " (" + service + ")");
subtitles.add(handleDate.formatDate(note.getDate(), "dd MMM yyyy") + " Ref: " + note.getJobID());
}
if(getConnectionCount() == 0){
adapter = new SimpleListAdapter(getActivity(), titles, subtitles);
lv.setAdapter(adapter);
}
else {
adapter.addItem(titles, subtitles);
}
and my adapter:
public class SimpleListAdapter extends BaseAdapter {
private int count = 0;
private static LayoutInflater inflater = null;
private ArrayList<String> titles = new ArrayList<String>();
private ArrayList<String> subtitles = new ArrayList<String>();
private ArrayList<Integer> imageResource = new ArrayList<Integer>();
private boolean hasImage = false;
public SimpleListAdapter(Activity activity, ArrayList<String> titles,
ArrayList<String> subtitles, ArrayList<Integer> imageResource) {
count = titles.size();
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.titles = titles;
this.subtitles = subtitles;
this.imageResource = imageResource;
this.hasImage = true;
}
/**Constructor that creates an adapter with only a title and subtitle.
* #param activity The context.
* #param titles ArrayList with the titles of each list option.
* #param subtitles ArrayList with the subtitles of each list option. */
public SimpleListAdapter(Activity activity, ArrayList<String> titles,
ArrayList<String> subtitles) {
count = titles.size();
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.titles = titles;
this.subtitles = subtitles;
this.hasImage = false;
}
public void addItem(ArrayList<String> title, ArrayList<String> subtitle){
this.titles.addAll(title);
this.subtitles.addAll(subtitle);
notifyDataSetChanged();
}
#Override
public int getCount() {
return count;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null)
v = inflater.inflate(R.layout.layout_simple_list, null);
final ImageView icon = (ImageView) v.findViewById(R.id.icon);
final TextView title = (TextView) v.findViewById(R.id.title);
final TextView subtitle = (TextView) v.findViewById(R.id.subtitle);
title.setText(titles.get(position));
subtitle.setText(subtitles.get(position));
if (hasImage) {
icon.setImageResource(imageResource.get(position));
}
else {
icon.setVisibility(ImageView.GONE);
}
return v;
}
}
You will need to update your count variable too in addItem so that the all the rows are created when notifyDataSetChanged is called
I am trying to implement search option for my contact list that is being displayed with Contact images and contact name.
I have created a text box to input the search text.
contactnameadpater.java: extends base adapter.
which has the following code:
public class ContactNamesAdapter extends BaseAdapter implements Filterable
{
private Activity activity;
private ArrayList<HashMap<String, String>> originalData;
private ArrayList<HashMap<String, String>> filteredData;
private static LayoutInflater inflater=null;
public ContactNamesAdapter(Activity a, ArrayList<HashMap<String, String>> d)
{
activity = a;
originalData=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount()
{
return originalData.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.contacts_row, null);
ImageView profile = (ImageView)vi.findViewById(R.id.ContactImage);
Uri my_contact_Uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(originalData.get(position).get("id")));
InputStream photo_stream = ContactsContract.Contacts.openContactPhotoInputStream(ContactNamesAdapter.inflater.getContext().getContentResolver(),my_contact_Uri);
if(photo_stream != null)
{
BufferedInputStream buf =new BufferedInputStream(photo_stream);
Bitmap my_btmp = BitmapFactory.decodeStream(buf);
profile.setImageBitmap(my_btmp);
}
else
{
profile.setImageResource(R.drawable.no_pic);
}
TextView name = (TextView)vi.findViewById(R.id.name);
name.setText(originalData.get(position).get("name"));
return vi;
}
#Override
public Filter getFilter()
{
return new Filter()
{
private ArrayList<HashMap<String, String>> filteredResultsData;
#Override
protected FilterResults performFiltering(CharSequence charSequence)
{
FilterResults results = new FilterResults();
//If there's nothing to filter on, return the original data for your list
if(charSequence == null || charSequence.length() == 0)
{
results.values = originalData;
results.count = originalData.size();
}
else
{
ArrayList<HashMap<String,String>> filterResultsData = new ArrayList<HashMap<String,String>>();
for(HashMap<String,String> data : originalData)
{
if(originalData == filterResultsData )
{
filterResultsData.add(data);
}
}
results.values = filterResultsData;
results.count = filteredResultsData.size();
}
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults)
{
filteredData = (ArrayList<HashMap<String,String>>)filterResults.values;
notifyDataSetChanged();
}
};
}
contactname.java: extends an activity.
OnCreate:
DetailsList = new ArrayList<HashMap<String, String>>();
contactList = (ListView) findViewById(R.id.ContactNamelist);
profileImage = (ImageView) findViewById(R.id.ContactImage);
inputSearch = (EditText) findViewById(R.id.inputSearch);
getContactName();
contactList.setTextFilterEnabled(true);
inputSearch.addTextChangedListener(new TextWatcher()
{
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
adapter.getFilter().filter(cs.toString());
//adapter.getFilter().filter(cs);
Log.e("getfilter","getfilter");
contactList.setAdapter(adapter);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
}
});
}
and under getContactName():
public void getContactName()
{
final Uri uri = ContactsContract.Contacts.CONTENT_URI;
final String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.PHOTO_ID
};
String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '1'";
final String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
Cursor cur = getContentResolver().query(uri, projection, selection, null, sortOrder);
if (cur.getCount() > 0)
{
while (cur.moveToNext())
{
String Sid = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", name);
map.put("id", Sid);
DetailsList.add( map);
}
}
cur.close();
adapter = new ContactNamesAdapter(this, DetailsList);
// updating listview
contactList.setAdapter(adapter);
}
The problem is that I am not getting results after typing the text in search box. I am not sure where I am going wrong?
Let me know how to fix this?
Thanks!
You might want to look at this link.
Click Here to see Searchview
It is a good SearchView or use my SearchView below
Here is my search method on a listview
search.addTextChangedListener(new TextWatcher() { //search is a edittext object
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
textlength = search.getText().length(); //textlength is a global variable
filtered_text = new ArrayList<RowItem>(); //global array list
for (int i = 0; i < employee.length(); i++)
{
if(rowItems.get(i).getTitle().toString().toUpperCase().contains(search.getText().toString().toUpperCase())) //rowItem is an object of my holder class for Custom Adapter
{
//Adding image and names which match the search criteria
in filtered_text array list
String mDrawableName;
try {
mDrawableName = employee.getJSONObject(i).getString("image");
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
RowItem item = new RowItem(resID, rowItems.get(i).getTitle());
filtered_text.add(item);
} catch (JSONException e) {e.printStackTrace();}
}
}
adapter = new CustomBaseAdapter(YourClass.this, filtered_text);
listView.setAdapter(adapter);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
I am creating an android app the UI of my application is below given.
On clicking of submit button, I need the selected check box, value and id textview
example size is not checked, cc(radio button) is checked.
records are populated dynamically in list view, but I am not able to make it work.
Checkbox_ProducoptionActivity.java
public class MainActivity extends Activity implements OnItemClickListener {
ListView listview;
ArrayList<HashMap<String, String>> list_kategori ;
ProgressDialog pd;
ArrayAdapter<Model_checkbox> adapter;
List<String> idprdoptins = new ArrayList<String>();
List<Model_checkbox> nameprdoptn = new ArrayList<Model_checkbox>();
List<Model_checkbox> list = new ArrayList<Model_checkbox>();
Button btn_checkbox;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checkboxproduct_option);
listview = (ListView)findViewById(R.id.list);
btn_checkbox = (Button)findViewById(R.id.btn_productoption);
// TODO Auto-generated method stub
String id =CheckLogin();
if (id!=""){
loadproductoption(id);
}
btn_checkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
for (Model_checkbox m : list) {
Log.i("Stack1", m.toString());
}
Log.d("Stack1",String.valueOf(Model_checkbox.class));
Toast.makeText(getApplicationContext(), "ada",Toast.LENGTH_LONG).show();
}
});
}
public void loadproductoption(String id) {
listproduct task= new listproduct();
task.execute(id);
}
private class listproduct extends AsyncTask<String, Void, String>{
protected void onPreExecute(){
pd = new ProgressDialog(Checkbox_ProducoptionActivity.this);
pd.setMessage("Please wait..");
pd.setCancelable(false);
pd.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
JSONObject jsonResult = HttpClientCustom.getRequest(Konfigurasi.strUrl+"api-v1/proop?id_user="+ params[0]);
return jsonResult.toString();
}
protected void onPostExecute(String result){
JSONObject jsonResponse=null;
JSONArray jObject=null;
list_kategori = new ArrayList<HashMap<String, String>>();
try {
jsonResponse = new JSONObject(new String(result));
if(jsonResponse.getString("status").equals("SUCCESS")) {
if (!jsonResponse.getString("total").equals("0")){
jObject = jsonResponse.getJSONArray("resultset");
for (int i = 0; i < jObject.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("idprd", jObject.getJSONObject(i).getString("id"));
map.put("id_user", jObject.getJSONObject(i).getString("id_user"));
map.put("namepd", jObject.getJSONObject(i).getString("name"));
setListnama(jObject.getJSONObject(i).getString("name"));
list_kategori.add(map);
}
adapter = new Adapter_Checkboxproductoption(Checkbox_ProducoptionActivity.this, getModel());
listview.setAdapter(adapter);
}
pd.dismiss();
} else if (jsonResponse.getString("status").equals("FAILED")) {
pd.dismiss();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pd.dismiss();
}
private List<Model_checkbox> getModel() {
return nameprdoptn;
}
public void setListnama(String name) {
nameprdoptn.add(new Model_checkbox(name));
}
}
Model checkbox.java
// public class My modele {
public class Model_checkbox {
private String name;
private boolean selected;
//private boolean isCcOrIsTo;
public Model_checkbox(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
#Override
public String toString() {
String selectedString = selected ? "selected" : "not selected";
// String value = isCcOrIsTo ? "CC" : "To";
return name+" -> "+selectedString+ " with value ";
}
}
MyAdapter.java
// public class MyAdapter extends ArrayAdapter {
class ViewHolder {
protected TextView text;
protected CheckBox checkbox;
}
public class Adapter_Checkboxproductoption extends ArrayAdapter<Model_checkbox> {
private final List<Model_checkbox> list;
private final Activity context;
boolean checkAll_flag = false;
boolean checkItem_flag = false;
public Adapter_Checkboxproductoption(Activity context, List<Model_checkbox> list) {
super(context, R.layout.list_checkbox, list);
this.context = context;
this.list = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.list_checkbox, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.rowTextView);
viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.CheckBox01);
viewHolder.checkbox.setTag(position);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.text.setText(list.get(position).getName());
viewHolder.checkbox.setChecked(list.get(position).isSelected());
viewHolder.checkbox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
CheckBox checkbox = (CheckBox) v;
int getPosition = (Integer) checkbox.getTag();
list.get(getPosition).setSelected(checkbox.isChecked());
}
});
return convertView;
}
}
can't work in "Checkbox_ProducoptionActivity.java"
for (Model_checkbox m : list) {
Log.i("Stack1", m.toString());
Can any body help me in getting value and id of selected check box?
All you need to do is get/set the value of checked item in your adapter this way, I did in Cursor adapter you can update below code as per your need.
public class CursorAdapterList extends CursorAdapter {
private LayoutInflater inflater = null;
private DBAdapter db = null;
private Context ctx = null;
public CursorAdapterList(Context context, Cursor c, DBAdapter database) {
super(context, c);
ctx = context;
db = database;
inflater = LayoutInflater.from(context);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView tv = (TextView) view.findViewById(R.id.txtGameNameInList);
CheckBox favBox = (CheckBox) view.findViewById(R.id.favbuttonInList);
tv.setText(cursor.getString(1));
//here I am getting value of already checked boxes from db
String flag = cursor.getString(3);
if (flag.equals("true")) {
favBox.setChecked(true);
} else {
favBox.setChecked(false);
}
favBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout parentView = (LinearLayout) v.getParent();
TextView clickedText = (TextView) parentView
.findViewById(R.id.txtGameNameInList);
//here you can get the Item value what your selcted in your list
String name = clickedText.getText().toString();
if (((CheckBox) v).isChecked()) {
Toast.makeText(ctx, name + " is Marked as Favorite Game!!",
Toast.LENGTH_SHORT).show();
//below method will store selected item value in db
db.markAsFavorite(name, "true");
} else {
db.markAsFavorite(name, "false");
}
}
});
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return inflater.inflate(R.layout.list_row_custom, parent, false);
}
}
For my activity
public class Checkbox_ProducoptionActivity<country> extends Activity {
ListView list;
static Context mContext;
Button btnSave;
List<String> val = new ArrayList<String>();
ArrayList<HashMap<String, String>> list_kategori ;
ArrayList<String> stock_list = new ArrayList<String>();
ArrayList<String> stock2_list = new ArrayList<String>();
ProgressDialog pd;
EfficientAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checkboxproduct_option);
list = (ListView) findViewById(R.id.ListView01);
btnSave = (Button)findViewById(R.id.btnSave);
mContext = this;
final String id =CheckLogin();
if (id!=""){
loadproductoption(id);
}
btnSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences val_shared = getSharedPreferences("CHECKBOX_SHARED", MODE_WORLD_WRITEABLE);
SharedPreferences.Editor cleareditor=val_shared.edit();
cleareditor.clear();
cleareditor.commit();
for (int i = 0; i <list.getCount() ; i++) {
View vListSortOrder;
vListSortOrder=list.getChildAt(i);
try{
TextView textval= (TextView)vListSortOrder.findViewById(R.id.TextView01);
CheckBox ckc=(CheckBox)vListSortOrder.findViewById(R.id.chkbox1);
EditText edit=(EditText)vListSortOrder.findViewById(R.id.txtbox);
if (ckc.isChecked()){
edit.getText().toString();
String temp1 = textval.getText().toString();
Toast.makeText(getApplicationContext(), "fuck"+textval.getText().toString(), Toast.LENGTH_LONG).show();
val.add(temp1);
}
}catch (Exception e) {
// TODO: handle exception
}
}
SharedPreferences customer_ident = getSharedPreferences("CHECKBOX_SHARED", MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor=customer_ident.edit();
editor.putString("valuecheck", val.toString());
editor.commit();
// Toast.makeText(getApplicationContext(), "ada "+val, Toast.LENGTH_LONG).show();
Intent prdmenuact = new Intent(getApplicationContext(),CreateManageProductActivity.class);
prdmenuact.putExtra("idaction", "1");
startActivity(prdmenuact);
finish();
}
});
}
public void loadproductoption(String id) {
listproduct task= new listproduct();
task.execute(id);
}
private class listproduct extends AsyncTask<String, Void, String>{
protected void onPreExecute(){
pd = new ProgressDialog(Checkbox_ProducoptionActivity.this);
pd.setMessage("Please wait..");
pd.setCancelable(false);
pd.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
JSONObject jsonResult = HttpClientCustom.getRequest(Konfigurasi.strUrl+"api-v1/proop?id_user="+ params[0]);
return jsonResult.toString();
}
protected void onPostExecute(String result){
JSONObject jsonResponse=null;
JSONArray jObject=null;
list_kategori = new ArrayList<HashMap<String, String>>();
try {
jsonResponse = new JSONObject(new String(result));
if(jsonResponse.getString("status").equals("SUCCESS")) {
if (!jsonResponse.getString("total").equals("0")){
jObject = jsonResponse.getJSONArray("resultset");
for (int i = 0; i < jObject.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("idprd", jObject.getJSONObject(i).getString("id"));
map.put("id_user", jObject.getJSONObject(i).getString("id_user"));
map.put("namepd", jObject.getJSONObject(i).getString("name"));
list_kategori.add(map);
}
adapter = new EfficientAdapter(Checkbox_ProducoptionActivity.this,list_kategori );
list.setAdapter(adapter);
}
pd.dismiss();
} else if (jsonResponse.getString("status").equals("FAILED")) {
pd.dismiss();
}
} catch (JSONException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
pd.dismiss();
}
}
my adpater
public class EfficientAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private LayoutInflater inflater=null;
public ImageLoader imageLoader;
String priceprd ;
public EfficientAdapter (Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public EfficientAdapter(Runnable runnable,
ArrayList<HashMap<String, String>> list_kategori) {
// TODO Auto-generated constructor stub
}
public int getCount() {
//Log.d("country",String.valueOf(data.size()));
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_checkbox, parent,
false);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.TextView01);
holder.text2 = (TextView) convertView.findViewById(R.id.TextView02);
holder.txt = (EditText) convertView.findViewById(R.id.txtbox);
holder.cbox = (CheckBox) convertView.findViewById(R.id.chkbox1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText( data.get(position).get("idprd"));
holder.text2.setText(data.get(position).get("namepd"));
holder.txt.setText("");
holder.cbox.setChecked(false);
return convertView;
}
public class ViewHolder {
TextView text;
TextView text2;
EditText txt;
CheckBox cbox;
}
}
public String[] convert(List<String[]> list1) {
// TODO Auto-generated method stub
return null;
}
adapter to be replaced
and the model removed
so to check the value of just using ischecked
for (int i = 0; i <list.getCount() ; i++) {
View vListSortOrder;
vListSortOrder=list.getChildAt(i);
try{
TextView textval= (TextView)vListSortOrder.findViewById(R.id.TextView01);
CheckBox ckc=(CheckBox)vListSortOrder.findViewById(R.id.chkbox1);
EditText edit=(EditText)vListSortOrder.findViewById(R.id.txtbox);
if (ckc.isChecked()){
edit.getText().toString();
String temp1 = textval.getText().toString();
Toast.makeText(getApplicationContext(), "fuck"+textval.getText().toString(), Toast.LENGTH_LONG).show();
val.add(temp1);
}
}catch (Exception e) {
// TODO: handle exception
}
}
and successful