i have news application that download data from web and displays it in listview ,but how can i make that first row is different ,bigger height ,different layout and stuff ?
this is main activity source
public class Home extends Activity {
// All static variables
static final String URL = "http://dmb.site50.net/application.php?app_access_key=c4ca4238a0b923820dcc509a6f75849b";
// XML node keys
static final String KEY_SONG = "song"; // parent node
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_ARTIST = "artist";
static final String KEY_DURATION = "duration";
static final String KEY_THUMB_URL = "thumb_url";
public static final String TAG_NEWS = "news";
public static final String TAG_ID = "id";
public static final String TAG_TITLE = "title";
public static final String TAG_STORY = "story";
public static final String TAG_SH_STORY = "shorten";
public static final String TAG_DATETIME = "datetime";
public static final String TAG_AUTHOR = "author";
public static final String TAG_IMG = "img";
ListView list;
LazyAdapter adapter;
Button mBtnNaslovnica;
private ViewSwitcher viewSwitcher;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
mBtnNaslovnica = (Button) findViewById(R.id.mBtnNaslovnica);
mBtnNaslovnica.setSelected(true);
TextView txtView=(TextView) findViewById(R.id.scroller);
txtView.setSelected(true);
ImageButton mBtnRefresh = (ImageButton) findViewById(R.id.btnRefresh);
mBtnRefresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new LoadingTask().execute(URL);
}
});
ArrayList<HashMap<String, String>> homeList = new ArrayList<HashMap<String, String>>();
JSONObject jsonobj;
try {
jsonobj = new JSONObject(getIntent().getStringExtra("json"));
JSONArray news = jsonobj.getJSONArray(TAG_NEWS);
for(int i = 0; i < news.length(); i++){
JSONObject c = news.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String story = c.getString(TAG_STORY);
String shorten = c.getString(TAG_SH_STORY);
String author = c.getString(TAG_AUTHOR);
String datetime = c.getString(TAG_DATETIME);
String img = c.getString(TAG_IMG);
// 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_TITLE, title);
map.put(TAG_STORY, story);
map.put(TAG_IMG, img);
map.put(TAG_DATETIME, datetime);
map.put(TAG_AUTHOR, author);
// adding HashList to ArrayList
homeList.add(map);}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, homeList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String cur_title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String cur_story = ((TextView) view.findViewById(R.id.einfo2)).getText().toString();
String cur_author = ((TextView) view.findViewById(R.id.einfo1)).getText().toString();
String cur_datetime = ((TextView) view.findViewById(R.id.einfo)).getText().toString();
ImageView cur_img = (ImageView) view.findViewById(R.id.list_image);
String cur_img_url = (String) cur_img.getTag();
Intent i = new Intent("com.example.androidhive.CURENTNEWS");
i.putExtra("CUR_TITLE", cur_title);
i.putExtra("CUR_STORY", cur_story);
i.putExtra("CUR_AUTHOR", cur_author);
i.putExtra("CUR_DATETIME", cur_datetime);
i.putExtra("CUR_IMG_URL", cur_img_url);
startActivity(i);
}
});
}
public void loadPage(){
}
public void startNewActivity(){
}
public class LoadingTask extends AsyncTask<String, Object, Object>{
XMLParser parser = new XMLParser();
JSONParser jParser = new JSONParser();
#Override
protected Object doInBackground(String... params) {
// TODO Auto-generated method stub
String URL = params[0];
JSONObject json = jParser.getJSONFromUrl(URL);
//String xml = parser.getXmlFromUrl(URL); // getting XML from URL
// getting DOM element
return json;
}
protected void onPostExecute(Object result){
Intent startApp = new Intent("com.example.androidhive.HOME");
startApp.putExtra("json", result.toString());
startActivity(startApp);
}
}
}
You need to modify your LazyAdapter code to return right layout for each row, depending on any criteria you want. ListView simply uses view given by adapter, so it is nothing special to have each row layouted differently. Please note that to make it work correctly you need to implement getItemViewType() and getViewTypeCount() as well.
Related
// 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";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_list);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
int itemPosition = position;
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
// String add = ((TextView) view.findViewById(R.id.address))
// .getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
String price =((TextView) view.findViewById(R.id.price)).getText().toString();
String amount=((TextView) view.findViewById(R.id.mobile_labels)).getText().toString();
//String sweet = ((TextView) view.findViewById(R.id.home))
// .getText().toString();
// Starting single contact activity
Intent in = new Intent(SearchActivity.this,
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
//in.putExtra(TAG_PHONE_MOBILE,description);
//in.putExtra(TAG_PHONE_HOME,price);
// in.putExtra(TAG_PHONE_OFFICE,amount);
//in.putExtra(TAG_ADDRESS,add);
//in.putExtra(TAG_PHONE_MOBILE, description);
// in.putExtra(TAG_PHONE_HOME,sweet);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(SearchActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
// String add = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone node is 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);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
// contact.put(TAG_ADDRESS,add);
contact.put(TAG_PHONE_MOBILE, mobile);
contact.put(TAG_PHONE_HOME,home);
contact.put(TAG_PHONE_OFFICE,office);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
SearchActivity.this, contactList,
R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL,
TAG_PHONE_MOBILE ,TAG_PHONE_HOME,TAG_PHONE_OFFICE }, new int[] { R.id.name,
R.id.email, R.id.mobile,R.id.price ,R.id.mobile_labels});
setListAdapter(adapter);
}
}
}
Here is the list. In this I am getting name,email and mobile number. In the list when I select a name in the list open a new activity in that activity I need name, email, phone, address, gender, office. How should I pass this in next activity.
Here is the next activity code.
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String email = in.getStringExtra(TAG_EMAIL);
String mobile = in.getStringExtra(TAG_PHONE_MOBILE);
String home = in.getStringExtra(TAG_PHONE_HOME);
String office= in.getStringExtra(TAG_PHONE_OFFICE);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblEmail = (TextView) findViewById(R.id.email_label);
TextView lblMobile = (TextView) findViewById(R.id.mobile_label);
TextView lblMobiles = (TextView) findViewById(R.id.mobile_labels);
TextView lblOffice = (TextView) findViewById(R.id.mobile_office);
lblName.setText(name);
lblEmail.setText(email);
lblMobile.setText(mobile);
lblMobiles.setText(home);
lblOffice.setText(office);
}
}
It's better if I have only a name in the listview. On selecting the name in the list further details should be displayed, for instance: name, phone, email, address, gender.
Pass them through the intent you used to start the new activity. When you generate the intent you can bundle some information and pass it as an extra. Then all the information should be in the bundle when your new activity starts. That's probably the easiest way.
There's lots of information in those links, and google has tutorials on how to use intents as well.
Hope that helps!
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";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_list);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
int itemPosition = position;
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
// String add = ((TextView) view.findViewById(R.id.address))
// .getText().toString();
// String description = ((TextView) view.findViewById(R.id.mobile))
//.getText().toString();
//String sweet = ((TextView) view.findViewById(R.id.home))
// .getText().toString();
// Starting single contact activity
Intent in = new Intent(SearchActivity.this,
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
//in.putExtra(TAG_ADDRESS,add);
//in.putExtra(TAG_PHONE_MOBILE, description);
// in.putExtra(TAG_PHONE_HOME,sweet);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(SearchActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
// String add = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone node is 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);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
// contact.put(TAG_ADDRESS,add);
contact.put(TAG_PHONE_MOBILE, mobile);
contact.put(TAG_PHONE_HOME,home);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
SearchActivity.this, contactList,
R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL,
TAG_PHONE_MOBILE ,TAG_PHONE_HOME }, new int[] { R.id.name,
R.id.email, R.id.mobile,R.id.home });
setListAdapter(adapter);
}
}
}
I have a list activity in the list it display the name,email,phone number on select an item in the list open a new activity and display the same name, email,number but i need others details in nextactivity including addrees,gender,home, office
In the nextactivity i displaying this items
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String email = in.getStringExtra(TAG_EMAIL);
String mobile = in.getStringExtra(TAG_PHONE_MOBILE);
String home = in.getStringExtra(TAG_PHONE_HOME);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblEmail = (TextView) findViewById(R.id.email_label);
TextView lblMobile = (TextView) findViewById(R.id.mobile_label);
TextView lblMobiles = (TextView) findViewById(R.id.mobile_labels);
lblName.setText(name);
lblEmail.setText(email);
lblMobile.setText(mobile);
lblMobiles.setText(home);
}
}
Inclusignthsi i want to display address,home,office .
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String email = in.getStringExtra(TAG_EMAIL);
String mobile = in.getStringExtra(TAG_PHONE_MOBILE);
String home = in.getStringExtra(TAG_PHONE_HOME);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblEmail = (TextView) findViewById(R.id.email_label);
TextView lblMobile = (TextView) findViewById(R.id.mobile_label);
TextView lblMobiles = (TextView) findViewById(R.id.mobile_labels);
lblName.setText(name);
lblEmail.setText(email);
lblMobile.setText(mobile);
lblMobiles.setText(home);
}
#subhas i have updated th other activity code
I have a list view that I populate from a JSON array. First the values are extracted from the JSON array, then put into a HashMap. Then this HashMap is added to an ArrayList. From here, the necessary data is added to a ListAdapter.
I searched online for days now, to find a way to add a search function to this, but none of them uses this combination of ListAdapater, ArrayList and HashMap. I am a beginner so can someone help me do this please?
This is my code
public class ListNew extends Activity {
ListView list;
TextView eid;
TextView ename;
TextView edesc;
//Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "somelink";
//JSON Node Names
private static final String TAG_OS = "events";
private static final String TAG_EID = "eid";
private static final String TAG_ENAME = "ename";
private static final String TAG_ETYPE = "etype";
private static final String TAG_EDESC = "edesc";
private static final String TAG_ESDATE = "esdate";
private static final String TAG_EEDATE = "eedate";
private static final String TAG_ESTIME = "estime";
private static final String TAG_EETIME = "eetime";
private static final String TAG_LOCATION = "location";
private static final String TAG_CREATED_AT = "created_at";
private static final String TAG_EDITED_AT = "edited_at";
private static final String TAG_CREATEDBY = "createdby";
private static final String TAG_IMAGE = "image";
private static final String TAG_APPROVED = "approved";
EditText inputSearch;
ListAdapter adapter;
public static final String TABLE_EVENT = "event";
JSONArray events = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//from here
inputSearch = (EditText) findViewById(R.id.etSearch);
setContentView(R.layout.listnew);
oslist = new ArrayList<HashMap<String, String>>();
new JSONParse().execute();
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
eid = (TextView)findViewById(R.id.vers);
ename = (TextView)findViewById(R.id.name);
edesc = (TextView)findViewById(R.id.api);
pDialog = new ProgressDialog(ListNew.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl2(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
events = json.getJSONArray(TAG_OS);
for(int i = 0; i < events.length(); i++){
JSONObject c = events.getJSONObject(i);
// Storing JSON item in a Variable
String eid = c.getString(TAG_EID);
String ename = c.getString(TAG_ENAME);
String etype = c.getString(TAG_ETYPE);
String edesc = c.getString(TAG_EDESC);
String esdate = c.getString(TAG_ESDATE);
String eedate = c.getString(TAG_EEDATE);
String estime = c.getString(TAG_ESTIME);
String eetime = c.getString(TAG_EETIME);
String location = c.getString(TAG_LOCATION);
String created_at = c.getString(TAG_CREATED_AT);
String edited_at = c.getString(TAG_EDITED_AT);
String createdby = c.getString(TAG_CREATEDBY);
String image = c.getString(TAG_IMAGE);
String approved = c.getString(TAG_APPROVED);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_EID, eid);
map.put(TAG_ENAME, ename);
map.put(TAG_ETYPE, etype);
map.put(TAG_EDESC, edesc);
map.put(TAG_ESDATE, esdate);
map.put(TAG_EEDATE, eedate);
map.put(TAG_ESTIME, estime);
map.put(TAG_EETIME, eetime);
map.put(TAG_LOCATION, location);
map.put(TAG_CREATED_AT, created_at);
map.put(TAG_EDITED_AT, edited_at);
map.put(TAG_CREATEDBY, createdby);
map.put(TAG_IMAGE, image);
map.put(TAG_APPROVED, approved);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
TextView emptyText = (TextView)findViewById(R.id.empty);
list.setEmptyView(emptyText);
//Log.d("TAG_is d first one", TAG_APPROVED + "," + approved);
adapter = new SimpleAdapter(ListNew.this, oslist,
R.layout.list_v,
new String[] { TAG_ENAME,TAG_CREATEDBY, TAG_CREATED_AT }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(ListNew.this, NewEvent.class);
i.putExtra("eid", oslist.get(+position).get("eid") );
i.putExtra("ename", oslist.get(+position).get("ename") );
i.putExtra("etype", oslist.get(+position).get("etype") );
i.putExtra("edesc", oslist.get(+position).get("edesc") );
i.putExtra("esdate", oslist.get(+position).get("esdate") );
i.putExtra("eedate", oslist.get(+position).get("eedate") );
i.putExtra("estime", oslist.get(+position).get("estime") );
i.putExtra("eetime", oslist.get(+position).get("eetime") );
i.putExtra("location", oslist.get(+position).get("location") );
i.putExtra("created_at", oslist.get(+position).get("created_at") );
i.putExtra("edited_at", oslist.get(+position).get("edited_at") );
i.putExtra("createdby", oslist.get(+position).get("createdby") );
i.putExtra("image", byteArray);
i.putExtra("approved", oslist.get(+position).get("approved") );
startActivity(i);
}
});
}//end if
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
As per you description I believe you have custom adapter implementation for your list view. In case of custom adapters yon need to create your own filters by implementing
http://developer.android.com/reference/android/widget/Filterable.html
or
http://developer.android.com/reference/android/widget/Filter.html
Below is the simple tutorial to take inspiration
http://www.survivingwithandroid.com/2012/10/android-listview-custom-filter-and.html
========== Example for simple search ===
You need to create an Edit text on top of list view
<EditText
android:id="#+id/editTxt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:maxLines="1" />
Then apply text change listener to this edit text
editTxt.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
and you are done.
For Finding the key items fromt he listview i had not used filter in the adapter, but now by following this link aded the filter but in this line String playerName=songsList.get(i).get("title").toString(); I am getting the error
The method get(String) is undefined for the type String
and also in searchResults.add(songsList.get(i)); as
The method add(HashMap<String,String>) in the type ArrayList<HashMap<String,String>> is not applicable for the arguments (String)
Here's is my entire code
public class Home extends ListActivity {
//how many to load on reaching the bottom
int itemsPerPage = 15;
boolean loadingMore = false;
//For test data :-)
Calendar d = Calendar.getInstance();
ArrayList<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://india.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";
#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) {
adapter.getFilter().filter(s.toString());
}
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);
}
});
and the adapter class is
public class LazyAdapter extends BaseAdapter implements Filterable{
TextView title;
private Activity activity;
// private TextWatcher textWatcher;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
final EditText searchBox=(EditText) findViewById(R.id.search);
ArrayList<HashMap<String, String>> searchResults;
ArrayList<String> songsList;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
private EditText findViewById(int search) {
// TODO Auto-generated method stub
return null;
}
public int getCount() {
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) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.activity_home, null);
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView date = (TextView)vi.findViewById(R.id.date); // artist name
TextView content = (TextView)vi.findViewById(R.id.content); // duration
TextView name = (TextView)vi.findViewById(R.id.name);
// duration
ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
// Setting all values in listview
title.setText(song.get(Home.KEY_TITLE));
date.setText(song.get(Home.KEY_DATE));
content.setText(song.get(Home.KEY_CONTENT));
name.setText(song.get(Home.KEY_NAME));
imageLoader.DisplayImage(song.get(Home.KEY_URL), thumb_image);
return vi;
}
public void add(String string) {
// TODO Auto-generated method stub
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence data,FilterResults searchResults) {
songsList = (ArrayList<String>) searchResults.values; // has the filtered values
notifyDataSetChanged(); // notifies the data with new filtered values
}
#Override
protected FilterResults performFiltering(CharSequence playerName) {
// TODO Auto-generated method stub
return null;
}
};
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)))
searchResults.add(songsList.get(i));
}
}
return filter;
}
}
ArrayList<String> songsList;
so songsList is an ArrayList of Strings... if you do songsList.get(i) you'll have a String. The String object has not a "get" method, sou you cannot go further with
songsList.get(i).get("title").toString().
The same thing happens here:
searchResults=new ArrayList<HashMap<String, String>>
so if you call searchResults.add you have to pass a hashmap, not a String.
Please check your type definitions again and it will work.
songsList is a list of strings so you cannot do a get() on its item
I am using listview to display items obtained from json response. Currently 10 items are displaying, as i scroll down more items must load but it is not happening. Following is my code can anyone help me? Answers will be appreciated.
public class MainActivity extends ListActivity {
ListView list;
LazyAdapter adapter;
JSONArray posts;
// All static variables
static final String URL = "http://site.org/";
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.activity_main);
final Handler handler = new Handler();
Runnable runable = new Runnable() {
#Override
public void run() {
//call the function
LoadData();
//also call the same runnable
handler.postDelayed(this, 40000);
}
};
handler.postDelayed(runable, 10);
}public void LoadData(){
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
JSONArray 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();
}
// Getting adapter by passing json data ArrayList
adapter=new LazyAdapter(this, songsList);
adapter.notifyDataSetChanged();
ListView list=(ListView)findViewById(android.R.id.list);
list.setAdapter(adapter);
// Launching new screen on Selecting Single ListItem
list.setOnItemClickListener(new OnItemClickListener() {
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();
String date = ((TextView) view.findViewById(R.id.date)).getText().toString();
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String content = ((TextView) view.findViewById(R.id.content)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),SampleDesp.class);
in.putExtra(KEY_TITLE, title);
in.putExtra(KEY_DATE, date);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_CONTENT, content);
startActivity(in);
}
});
list.setOnScrollListener(new OnScrollListener(){
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
}
#Override
public void onScrollStateChanged(AbsListView view,
int scrollState) {
// TODO Auto-generated method stub
}
});
}
}