dynamically create expandablelistview within expandablelistview in android - java

i have developed one dynamic expandablelistview successfully...how is dynamically create expandablelictview within another expandalilistview.
this is my code:
public class SingleMenuItemActivity extends ExpandableListActivity {
Button btninsert;
String selectedItem;
static final String KEY_NAME = "orderid";
static final String KEY_STATUS = "status";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.particular);
Button btninsert = (Button) findViewById(R.id.btn_insert);
btninsert.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String s= getIntent().getStringExtra("orderid");
String s1= getIntent().getStringExtra("status");
Intent i = new Intent(getApplicationContext(), InsertionExample.class);
i.putExtra(KEY_NAME, s);
i.putExtra(KEY_STATUS, s1);
startActivity(i);
}
});
// Construct Expandable List
final String NAME1 = "payment_method1";
final String NAME = "payment_method";
final String TOTAL = "total";
final String TOTAL1 = "total1";
final String IMAGE = "image";
final String FNAME1 = "firstname1";
final String FNAME = "firstname";
final String LNAME1 = "lastname1";
final String LNAME = "lastname";
final String PHONE1 = "phone1";
final String PHONE = "phone";
final String EMAIL1 = "email1";
final String EMAIL = "email";
final LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final ArrayList<HashMap<String, String>> headerData = new ArrayList<HashMap<String, String>>();
final HashMap<String, String> group1 = new HashMap<String, String>();
group1.put(NAME, "OrderInfo");
headerData.add( group1 );
final HashMap<String, String> group2 = new HashMap<String, String>();
group2.put(NAME, "CustomerInfo");
headerData.add( group2);
final ArrayList<ArrayList<HashMap<String, Object>>> childData = new ArrayList<ArrayList<HashMap<String, Object>>>();
final ArrayList<HashMap<String, Object>> group1data = new ArrayList<HashMap<String, Object>>();
childData.add(group1data);
final ArrayList<HashMap<String, String>> group2data = new ArrayList<HashMap<String,String>>();
final HashMap<String, String> group3 = new HashMap<String, String>();
group3.put(NAME, "PersonalInfo");
group2data.add( group3 );
final HashMap<String, String> group4 = new HashMap<String, String>();
group4.put(NAME, "ContactInfo");
group2data.add( group4 );
final ArrayList<HashMap<String, Object>> group3data = new ArrayList<HashMap<String, Object>>();
childData.add(group3data);
final ArrayList<HashMap<String, Object>> group4data = new ArrayList<HashMap<String, Object>>();
childData.add(group4data);
// Set up some sample data in both groups
final HashMap<String, Object> map = new HashMap<String,Object>();
String s= getIntent().getStringExtra("payment_method");
String s1= getIntent().getStringExtra("total");
map.put(NAME1, "Payment_method:");
map.put(NAME, s );
map.put(TOTAL1, "Total:");
map.put(TOTAL, s1);
group1data.add(map);
// map.put(IMAGE, getResources().getDrawable((i%3==0? R.drawable.color_green : R.drawable.color_red)));
// ( i%2==0 ? group1data : group2data ).add(map);
final HashMap<String, Object> map1 = new HashMap<String,Object>();
String s2= getIntent().getStringExtra("firstname");
String s3= getIntent().getStringExtra("lastname");
map1.put(FNAME, s2);
map1.put(FNAME1, "Firstname:");
map1.put(LNAME, s3);
map1.put(LNAME1, "Lastname:");
// map.put(IMAGE, getResources().getDrawable(R.drawable.color_yellow));
group3data.add(map1);
final HashMap<String, Object> map2 = new HashMap<String,Object>();
String s4= getIntent().getStringExtra("phone");
String s5= getIntent().getStringExtra("email");
map2.put(PHONE, s4);
map2.put(PHONE1, "Phone:");
map2.put(EMAIL, s5);
map2.put(EMAIL1, "Email:");
// map.put(IMAGE, getResources().getDrawable(R.drawable.color_yellow));
group4data.add(map2);
setListAdapter( new SimpleExpandableListAdapter(
this,
headerData,
R.layout.group_row,
new String[] { NAME }, // the names of the data
new int[] { R.id.order },
// the text field to populate with the field data
childData,
0,
null,
new int[] {}
) {
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
final View v = super.getChildView(groupPosition, childPosition, isLastChild, convertView, parent);
// Spinner spinner = (Spinner) findViewById(R.id.spnMusketeers);
// Populate your custom view here
((TextView)v.findViewById(R.id.payment_method1)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(NAME1) );
((TextView)v.findViewById(R.id.payment_method)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(NAME) );
((TextView)v.findViewById(R.id.phone1)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(PHONE1) );
((TextView)v.findViewById(R.id.phone)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(PHONE) );
((TextView)v.findViewById(R.id.email1)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(EMAIL1) );
((TextView)v.findViewById(R.id.email)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(EMAIL) );
((TextView)v.findViewById(R.id.firstname)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(FNAME) );
((TextView)v.findViewById(R.id.firstname1)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(FNAME1) );
((TextView)v.findViewById(R.id.total1)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(TOTAL1) );
((TextView)v.findViewById(R.id.total)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(TOTAL) );
((TextView)v.findViewById(R.id.lastname)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(LNAME) );
((TextView)v.findViewById(R.id.lastname1)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(LNAME1) );
return v;
}
#Override
public View newChildView(boolean isLastChild, ViewGroup parent) {
return layoutInflater.inflate(R.layout.expandable_list_item_with_image,null, false);
}
}
);
ExpandableListView list = (ExpandableListView) findViewById(android.R.id.list);
list.setOnChildClickListener(new OnChildClickListener(){
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
System.out.println("Group:"+groupPosition+", Child: "+childPosition);
return true;
}
});
}}
Here i wish to display the output is below format:
---->Orderinfo
* payment_method
* total
---->Customerinfo
---->Personalinfo
* firstname
* lastname
----->Contactinfo
* phone
* email
Here i can't develop this.
here how can i implement my code???
here i have created headerData(orderinfo,customerinfo) and group2data(personalinfo,contactinfo) for creating groups.Here i have used headerData only on below code.
setListAdapter( new SimpleExpandableListAdapter(
this,
headerData,
R.layout.group_row,
new String[] { NAME }, // the names of the data
new int[] { R.id.order },
// the text field to populate with the field data
childData,
so ly created orderinfo and customerinfo groups only.but i can't add group2data here.here i have add groupdata on this line means i got the following error:
- Breakpoint:SingleMenuItemActivity
- Line breakpoint:SingleMenuItemActivity [line: 134] - onCreate(Bundle)
- The constructor SimpleExpandableListAdapter(SingleMenuItemActivity, ArrayList>, ArrayList>, int, String[], int[], ArrayList>>, int, null, int[]) is
undefined
How can i resolve my error.please help me.

A ListView within a ListView gets pretty hairy. The OS has problems figuring out which listview to scroll, even though it may be obvious to you.
Anyways, it sounds like you should double-check your parameter list. Make sure it matches the constructor of that object.

Related

Listview prints Object not string java

I'm trying to display a listview with data out of openERP / odoo.
OpenERP returns an list of objects that I'm trying to use into a listview, but it prints out "Ljava.lang.object#number".
listOfValues return the list of objects, in my onPostExecute I want to connect it with the listview. But it doesn't work, anyone suggestion?
private class ListViewLoaderTask extends AsyncTask{
#Override
protected SimpleAdapter doInBackground(String... strJson) {
connector=new OpenerpRpc(getBaseContext());
connector.Config();
current_page += 1;
listOffValues = getListOffFieldValues(current_page, false, listOffValues);
String[] from = { "project_id"};
int[] to = { R.id.tv_address};
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), listOffValues, R.layout.lv_gps_layout, from, to);
return adapter;
}
/** Invoked by the Android on "doInBackground" is executed */
#Override
protected void onPostExecute(final SimpleAdapter adapter) {
// Setting adapter for the listview
mListView.setAdapter(adapter);
for(int i=0;i<adapter.getCount();i++){
HashMap<String, Object[]> hm = (HashMap<String, Object[]>) adapter.getItem(i);
final HashMap<String, String> companyDetails = new HashMap<String, String>();
Object po_ids = (Object[]) hm.get("project_id");
Object[] ret=(Object[]) hm.get("project_id");
Integer number = ((Integer) hm.get("project_id")[0]);
String projectId = ((String) hm.get("project_id")[1]);
companyDetails.put("project_id",projectId);
adapter.notifyDataSetChanged();
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String listName;
HashMap<String, String> hmDownload = new HashMap<String, String>();
String l = companyDetails.get("project_id");
Intent myIntent = new Intent(MainActivity.this, YardActivity.class);
myIntent.putExtra("id", Long.toString(id));
myIntent.putExtra("position", Integer.toString(position)); //Optional parameters
MainActivity.this.startActivity(myIntent);
}
});
}
progress.dismiss();
Log.d("/****","Data from odoo is finished");
}
}
Here is the output when i debug:
http://i62.tinypic.com/24esx87.png
I updated my example where you can see that I can get the name of the project out of the list. But when I try to visulize that It print that java.lang string. Is your solution the only solution? When I hit on an item in my listview I get the projectId that I hit, so why it dont what to visiulize the string value?
HashMap<String, Object[]> hm = (HashMap<String, Object[]>)adapter.getItem(i);
change to
HashMap<String, MyModel[]> hm = (HashMap<String, MyModel[]>) adapter.getItem(i);
where my model is a class you create that describe your data,
take a look at ObjectItem.java
http://www.javacodegeeks.com/2013/09/android-listview-with-adapter-example.html

Using Textwatcher with a simpleexpandablelistview in Android

In my previous app, I had a listview and and edittext at the bottom of it. I have been using the textwatcher in the edittext to filter a listview. The contents of the listview come from a simplecursoradapter.
edittext.addTextChangedListener(filterTextWatcher);
cursor.setFilterQueryProvider(new FilterQueryProvider() {
#Override
public Cursor runQuery(CharSequence constraint) {
Cursor cursor=mDbHelper.fetchFilteredNotes(edittext.getText().toString());
return cur;
}
});
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(android.text.Editable s) {
};
public void beforeTextChanged(CharSequence s, int start, int count, int after) {};
public void onTextChanged(CharSequence s, int start, int before, int count) {
simplecursoradapter.getFilter().filter(s.toString());
};
};
In my current app, I have an expandablelistview. I would like to use a similar feature like filtering the content of the expandablelistview.
Am not sure if I can make use of textwatcher for this. Is there any other way to get this done or can I use textwatcher in this as well. ?
This is the relevant portion of code:
private DbAdapter mDbHelper;
List<Map<String, String>> groupData,groupDataCat;
List<List<Map<String, String>>> childData,childDataCat;
Map<String, String> curGroupMap;
List<Map<String, String>> meaning=null;
Map<String, String> curChildMap;
private static final String WORD = "WORD";
private static final String MEANING = "MEANING";
SimpleExpandableListAdapter mAdapter;
ExpandableListView elvCat;
temp=mDbHelper.fetchAllNotes();
temp.moveToFirst();
getActivity().startManagingCursor(temp);
if(temp.moveToFirst()){
groupDataCat = new ArrayList<Map<String, String>>();
childDataCat = new ArrayList<List<Map<String, String>>>();
for (int i = 0; i < temp.getCount(); i++) {
Map<String, String> catGroupMap = new HashMap<String, String>();
groupDataCat.add(catGroupMap);
catGroupMap.put(WORD, temp.getString(temp.getColumnIndexOrThrow(DbAdapter.KEY_WORD)));
List<Map<String, String>> meaning = new ArrayList<Map<String, String>>();
Map<String, String> catChildMap = new HashMap<String, String>();
meaning.add(catChildMap);
catChildMap.put(MEANING, temp.getString(temp.getColumnIndexOrThrow(DbAdapter.KEY_MEANING)));
childDataCat.add(meaning);
temp.moveToNext();
}
}
mAdapter = new SimpleExpandableListAdapter(
WordListFragment.this.getActivity(),
groupDataCat,
R.layout.word_list_item,
new String[] {WORD},
new int[] { R.id.tvWord },
childDataCat,
R.layout.meaning_list_item,
new String[] {MEANING},
new int[] { R.id.tvMeaning}
);
view=inflater.inflate(R.layout.word_list_temp, container, false);
elvCat = (ExpandableListView) view.findViewById(R.id.elvWord);
elvCat.setAdapter(mAdapter);
return view;
}
The way I got this to work was that in the onTextChanged() method, I called up a function which would query the database and get the filtered data. I repopulate the expandable listview again based on the query results.
private void populateList(String filter) {
temp = mDbHelper.fetchSugNotes(filter);
temp.moveToFirst();
this.startManagingCursor(temp);
groupDataCat = new ArrayList<Map<String, String>>();
childDataCat = new ArrayList<List<Map<String, String>>>();
for (int i = 0; i < temp.getCount(); i++) {
Map<String, String> catGroupMap = new HashMap<String, String>();
groupDataCat.add(catGroupMap);
catGroupMap.put(WORD, temp.getString(temp
.getColumnIndexOrThrow(DbAdapter.KEY_WORD)));
List<Map<String, String>> meaning = new ArrayList<Map<String, String>>();
Map<String, String> catChildMap = new HashMap<String, String>();
meaning.add(catChildMap);
catChildMap.put(MEANING, temp.getString(temp
.getColumnIndexOrThrow(DbAdapter.KEY_MEANING)));
childDataCat.add(meaning);
temp.moveToNext();
}
mAdapter = new SimpleExpandableListAdapter(this, groupDataCat,
R.layout.word_list_item, new String[] { WORD },
new int[] { R.id.tvWord }, childDataCat,
R.layout.meaning_list_item, new String[] { MEANING },
new int[] { R.id.tvMeaning });
elvCat.setAdapter(mAdapter);

Listview becomes empty after giving the keyword in search bar in android

Currently i'm working on How to find the items from the listview when given the keyword for the item in edittext, the listview becomes empty and the output is displaying in toast message, can anybody help like how to make the found "item" to display it in listivew?
public class Home extends ListActivity {
//how many to load on reaching the bottom
int itemsPerPage = 15;
boolean loadingMore = false;
ArrayList<String> songsList;
ListView list;
LazyAdapter adapter, adapter1;
JSONArray posts;
//ArrayList thats going to hold the search results
ArrayList<HashMap<String, String>> searchResults;
LayoutInflater inflater;
// All static variables
static final String URL = "http://abc.net/ads/?json=get_recent_posts";
static final String KEY_POSTS = "posts";
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_DATE = "date";
static final String KEY_CONTENT = "content";
static final String KEY_AUTHOR = "author";
static final String KEY_NAME = "name";
static final String KEY_ATTACHMENTS = "attachments";
static final String KEY_SLUG = "slug";
static final String KEY_THUMB_URL = "thumbnail";
static final String KEY_IMAGES = "images";
static final String KEY_URL = "url";
private static final String DEBUGTAG = null;
protected static final String TAG = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText searchBox=(EditText) findViewById(R.id.search);
final ListView list=(ListView)findViewById(android.R.id.list);
//get the LayoutInflater for inflating the customomView
//this will be used in the custom adapter
inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
final JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
posts = json.getJSONArray(KEY_POSTS);
// looping through all song nodes <song>
for(int i = 0; i < posts.length(); i++){
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(KEY_ID);
String title = c.getString(KEY_TITLE);
String date = c.getString(KEY_DATE);
String content = c.getString(KEY_CONTENT);
// to remove all <P> </p> and <br /> and replace with ""
content = content.replace("<br />", "");
content = content.replace("<p>", "");
content = content.replace("</p>", "");
//authornumber is agin JSON Object
JSONObject author = c.getJSONObject(KEY_AUTHOR);
String name = author.getString(KEY_NAME);
String url = null;
String slug = null;
try {
JSONArray atta = c.getJSONArray("attachments");
for(int j = 0; j < atta.length(); j++){
JSONObject d = atta.getJSONObject(j);
slug = d.getString(KEY_SLUG);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = images.getJSONObject(KEY_THUMB_URL);
url = thumbnail.getString(KEY_URL);
}
} catch (Exception e) {
e.printStackTrace();
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, id);
map.put(KEY_TITLE, title);
map.put(KEY_DATE, date);
map.put(KEY_NAME, name);
map.put(KEY_CONTENT, content);
map.put(KEY_SLUG, slug);
map.put(KEY_URL, url);
// adding HashList to ArrayList
songsList.add(map);
}
}catch (JSONException e) {
e.printStackTrace();
}
//searchResults=OriginalValues initially
searchResults=new ArrayList<HashMap<String, String>>(songsList);
// Getting adapter by passing json data ArrayList
adapter = new LazyAdapter(this, songsList);
list.setAdapter(adapter);
searchBox.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
//get the text in the EditText
String searchString = searchBox.getText().toString();
int textLength = searchString.length();
//clear the initial data set
searchResults.clear();
for (int i = 0; i < songsList.size(); i++) {
String playerName = songsList.get(i).get("title").toString();
if (textLength <= playerName.length()) {
//compare the String in EditText with Names in the ArrayList
if (searchString.equalsIgnoreCase(playerName.substring(0, textLength)))
Toast.makeText(getApplicationContext(), playerName, 1).show();
Home.this.adapter.getFilter();
searchResults.add(songsList.get(i));
Log.d(TAG, "title");
}
}
adapter.notifyDataSetChanged();
list.setAdapter(new ArrayAdapter<String>
(Home.this,
R.layout.activity_home));
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
Home.this.adapter.getFilter();
}
});
adapter.notifyDataSetChanged();
list.setAdapter(new ArrayAdapter<String>(Home.this, R.layout.activity_home));
You are not giving any data set to populate the ListView.
Just like you initially populated the ListView with songsList data
adapter = new LazyAdapter(this, songsList);
list.setAdapter(adapter);
use:
adapter = new LazyAdapter(this, searchResults);
list.setAdapter(adapter);
try this,
edittext code for search
etSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Call back the Adapter with current character to Filter
adapter1.getFilter().filter(s.toString());
}
........
add arraylist to listview to display
adapter1 = new MyAdapter(MainActivity.this, mProductArrayList);
lvProducts.setAdapter(adapter1);
Adapter Class
public class MyAdapter extends BaseAdapter implements Filterable {
private ArrayList<Product> mOriginalValues; // Original Values
private ArrayList<Product> mDisplayedValues; // Values to be displayed
LayoutInflater inflater;
public MyAdapter(Context context, ArrayList<Product> mProductArrayList) {
this.mOriginalValues = mProductArrayList;
this.mDisplayedValues = mProductArrayList;
inflater = LayoutInflater.from(context);
}
..........
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.row, null);
holder.llContainer = (LinearLayout)convertView.findViewById(R.id.llContainer1);
holder.tvName = (TextView) convertView.findViewById(R.id.tvName);
holder.tvPrice = (TextView) convertView.findViewById(R.id.tvPrice);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvName.setText(mDisplayedValues.get(position).name);
holder.tvPrice.setText(mDisplayedValues.get(position).price+"");
holder.llContainer.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(MainActivity.this, mDisplayedValues.get(position).price.toString() , Toast.LENGTH_SHORT).show();
}
});
return convertView;
}

How to make filtered items to displayed in listview using search functionality(android)

I have a edittext, search button and listview in my activity, based on the keyword given in the edittext box all the related items should be displayed in the listview, now i'm able to get the those related items in toast, that is all the related items gets poped up one by one in toast and gets diappeared, but i want it be in displayed in listview, how will i make it?
here's my code
public class Home extends ListActivity {
ArrayList<HashMap<String, String>> songsList;
ListView list;
LazyAdapter adapter;
JSONArray posts;
//ArrayList thats going to hold the search results
ArrayList<HashMap<String, String>> searchResults;
LayoutInflater inflater;
// All static variables
static final String URL = "http://www.example.com/ads/?json=get_recent_posts";
static final String KEY_POSTS = "posts";
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_DATE = "date";
static final String KEY_CONTENT = "content";
static final String KEY_AUTHOR = "author";
static final String KEY_NAME = "name";
static final String KEY_ATTACHMENTS = "attachments";
static final String KEY_SLUG = "slug";
static final String KEY_THUMB_URL = "thumbnail";
static final String KEY_IMAGES = "images";
static final String KEY_URL = "url";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText searchBox=(EditText) findViewById(R.id.search);
final ListView list=(ListView)findViewById(android.R.id.list);
//get the LayoutInflater for inflating the customomView
//this will be used in the custom adapter
inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
final JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
posts = json.getJSONArray(KEY_POSTS);
// looping through all song nodes <song>
for(int i = 0; i < posts.length(); i++){
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(KEY_ID);
String title = c.getString(KEY_TITLE);
String date = c.getString(KEY_DATE);
String content = c.getString(KEY_CONTENT);
// to remove all <P> </p> and <br /> and replace with ""
content = content.replace("<br />", "");
content = content.replace("<p>", "");
content = content.replace("</p>", "");
//authornumber is agin JSON Object
JSONObject author = c.getJSONObject(KEY_AUTHOR);
String name = author.getString(KEY_NAME);
String url = null;
String slug = null;
try {
JSONArray atta = c.getJSONArray("attachments");
for(int j = 0; j < atta.length(); j++){
JSONObject d = atta.getJSONObject(j);
slug = d.getString(KEY_SLUG);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = images.getJSONObject(KEY_THUMB_URL);
url = thumbnail.getString(KEY_URL);
}
} catch (Exception e) {
e.printStackTrace();
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, id);
map.put(KEY_TITLE, title);
map.put(KEY_DATE, date);
map.put(KEY_NAME, name);
map.put(KEY_CONTENT, content);
map.put(KEY_SLUG, slug);
map.put(KEY_URL, url);
// adding HashList to ArrayList
songsList.add(map);
}
}catch (JSONException e) {
e.printStackTrace();
}
//searchResults=OriginalValues initially
searchResults=new ArrayList<HashMap<String, String>>(songsList);
// Getting adapter by passing json data ArrayList
adapter=new LazyAdapter(this, songsList);
list.setAdapter(adapter);
searchBox.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
//get the text in the EditText
String searchString=searchBox.getText().toString();
int textLength=searchString.length();
//clear the initial data set
searchResults.clear();
for(int i=0;i<songsList.size();i++)
{
String playerName=songsList.get(i).get("title").toString();
if(textLength<=playerName.length()){
//compare the String in EditText with Names in the ArrayList
if(searchString.equalsIgnoreCase(playerName.substring(0,textLength)))
Toast.makeText(getApplicationContext(),playerName,1).show();
searchResults.add(songsList.get(i));
}
}
adapter.notifyDataSetChanged();
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
// Launching new screen on Selecting Single ListItem
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> map = songsList.get(position);
Intent in = new Intent(Home.this, Singlemenuitem.class);
in.putExtra(KEY_TITLE, map.get(KEY_TITLE));
in.putExtra(KEY_DATE, map.get(KEY_DATE));
in.putExtra(KEY_NAME, map.get(KEY_NAME));
in.putExtra(KEY_CONTENT, map.get(KEY_CONTENT));
in.putExtra(KEY_URL, map.get(KEY_URL));
startActivity(in);
}
});
}
i replaced the below code so got the my search function working:)
searchBox.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
//get the text in the EditText
searchString=searchBox.getText().toString();
textLength=searchString.length();
searchResults.clear();
for(int i=0;i<songsList.size();i++)
{
playerName=songsList.get(i).get("title").toString();
System.out.println("player name "+playerName);
if(textLength<=playerName.length()){
//compare the String in EditText with Names in the ArrayList
if(searchString.equalsIgnoreCase(playerName.substring(0,textLength))){
searchResults.add(songsList.get(i));
System.out.println("the array list is "+songsList.get(i));
adapter=new LazyAdapter(Home.this, searchResults);
list.setAdapter(adapter);
}
}
}
if(searchResults.isEmpty()){
Toast toast= Toast.makeText(getApplicationContext(),
"No Items Matched", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
adapter.notifyDataSetChanged();
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
System.out.println("before changed");
}
public void afterTextChanged(Editable s) {
System.out.println("after changed");
}
});
You have made the filtering last really messy. Try the code that is working for me.
First set the filteration true for the list,
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
Then use the edit text for filteration as follows,
editText.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
}
public void afterTextChanged(Editable arg0) {
MyActivity.this.adapter.getFilter().filter(arg0);
}
});
Use this code and check if it works or not.

how to Integrate Pull to RefreshListview in Android

public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
static final int MENU_MANUAL_REFRESH = 0;
static final int MENU_DISABLE_SCROLL = 1;
static final int MENU_SET_MODE = 2;
private LinkedList<String> mListItems;
//private PullToRefreshView mPullRefreshListView;
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This is My parsing COde i m able to get String value now i have Put JsonParser class in My project .
public class PullToRefreshListActivity extends Activity {
static final int MENU_MANUAL_REFRESH = 0;
static final int MENU_DISABLE_SCROLL = 1;
static final int MENU_SET_MODE = 2;
private PullToRefreshView mPullRefreshListView;
private ArrayAdapter<String> mAdapter;
private static String url = "http://api.androidhive.info/contacts/";
/** Called when the activity is first created. */
private LinkedList<String> mListItems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pull_to_refresh_listview);
mPullRefreshListView = (PullToRefreshView) findViewById(R.id.pull_refresh_list);
// Set a listener to be invoked when the list should be refreshed.
mPullRefreshListView.setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh() {
mPullRefreshListView.setLastUpdatedLabel(DateUtils
.formatDateTime(getApplicationContext(),
System.currentTimeMillis(),
DateUtils.FORMAT_SHOW_TIME
| DateUtils.FORMAT_SHOW_DATE
| DateUtils.FORMAT_ABBREV_ALL));
// Do work to refresh the list here.
new GetDataTask().execute();
}
});
ListView actualListView = mPullRefreshListView.getRefreshableView();
mListItems = new LinkedList<String>();
mListItems.addAll(Arrays.asList(mStrings));
mAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, mListItems);
// You can also just use setListAdapter(mAdapter)
actualListView.setAdapter(mAdapter);
}
private class GetDataTask extends AsyncTask<Void, Void, String[]> {
#Override
protected String[] doInBackground(Void... params) {
// Simulates a background job.
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
return mStrings;
}
#Override
protected void onPostExecute(String[] result) {
mListItems
.addFirst("Added after refresh..New Version Coming soon J-elly Bean");
mAdapter.notifyDataSetChanged();
// Call onRefreshComplete when the list has been refreshed.
mPullRefreshListView.onRefreshComplete();
super.onPostExecute(result);
}
}
private String[] mStrings = { "A-stro", "B-ender", "C-upcake", "E-clair",
"F-royo", "G-ingerbread", "H-oneycomb", "I-ce Cream Sandwich ",
"Android Versions From iamvijayakumar.blogspot.com" };
}
This is Dummy Example for PullToRefreshListview which i did. Now I want to Integrate so that i can display data in ListView with Pull To Refresh. Can u please help me how to integrate? Where i will place code for parsing and all?? Please help me .
In the Dummy Example, You given simply replace Adapter creation by using the below which is used to set data using Hashmap list. TAG_ID etc are used to be columns. Create an xml with name row and put 4 textview in the row layout and give them names as below which I have used in int array. Then set this adapter to listview.
mAdapter= new SimpleAdapter(this, mylist, R.layout.row,
new String[] {TAG_ID, TAG_NAME, TAG_EMAIL,TAG_PHONE_MOBILE}, new int[]
{R.id.tvtagid, R.id.tvtagname, R.id.tvtagemail,R.id.tvtagphone});
In the above adapter mylist is an Arraylist of your HashMap objects.

Categories

Resources