Hi i have to developed listview with load more button using xml parsing in android application.
Here i have faced some problem.
my xml feed is empty means how can hide the load more button on last page.
i have used below code here.
public class CustomizedListView extends Activity {
// All static variables
private String URL = "http://dev.mmm.com/xctesting/xcart444pro/retrieve.php?page=1";
// XML node keys
static final String KEY_SONG = "Order";
static final String KEY_TITLE = "orderid";
static final String KEY_DATE = "date";
static final String KEY_ARTIST = "payment_method";
int current_page = 1;
ListView lv;
LazyAdapter adapter;
ProgressDialog pDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView) findViewById(R.id.list);
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_SONG);
// looping through all song nodes <song>
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_ID, parser.getValue(e, KEY_ID));
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
songsList.add(map);
}
Button btnLoadMore = new Button(this);
btnLoadMore.setText("Load More");
btnLoadMore.setBackgroundResource(R.drawable.lgnbttn);
// Adding Load More button to lisview at bottom
lv.addFooterView(btnLoadMore);
// Getting adapter
adapter = new LazyAdapter(this, songsList);
lv.setAdapter(adapter);
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Starting a new async task
new loadMoreListView().execute();
}
});
}
private class loadMoreListView extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(
CustomizedListView.this);
pDialog.setMessage("Please wait..");
//pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.my_progress_indeterminate));
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
pDialog.setContentView(R.layout.custom_dialog);
}
protected Void doInBackground(Void... unused) {
current_page += 1;
// Next page request
URL = "http://dev.mmm.com/xctesting/xcart444pro/retrieve.php?page=" + current_page;
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_SONG);
NodeList nl = doc.getElementsByTagName(KEY_SONG);
if (nl.getLength() == 0)
{
btnLoadMore.setVisibility(View.GONE);
pDialog.dismiss();
}
else
// 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_ID, parser.getValue(e, KEY_ID));
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
songsList.add(map);
}
// get listview current position - used to maintain scroll position
int currentPosition = lv.getFirstVisiblePosition();
// Appending new data to menuItems ArrayList
adapter = new LazyAdapter(
CustomizedListView.this,
songsList);
lv.setAdapter(adapter);
lv.setSelectionFromTop(currentPosition + 1, 0);
}
});
return (null);
}
protected void onPostExecute(Void unused) {
// closing progress dialog
pDialog.dismiss();
}
}
}
EDIT:
Here i have to run the app means the listview is displayed on perpage 4 items.my last page having 1 item.please refer this screenshot:lastpage
In last page i have to click the load more button means have to go next activity and successfully hide the button on empty page..please refer this screenshot:empty page-so hide the button
i have to check the condition for empty page:
if (nl.getLength() == 0)
{
btnLoadMore.setVisibility(View.GONE);
pDialog.dismiss();
}
How can i write the conditon fot last page?????pleas ehelp me
Here i wish to need the o/p is hide the button on last page.
Please help me.how can i check the condition.give me some code programmatically.
First off, why are you using runOnUiThread inside an AsyncTaks? This should not be necessary. The code that has to run in the background, in the doInBackground method is enough.
Furthermore, you could use the third parameter type of the AsyncTask to return a result from te doInBackground to the onPostExecute. Then depending on the result, you can change the visibility of the button there.
To do this, the reference to the Button (btnLoadMore in your case) should be a instance variable, so it should be defined in the class, not in the onCreate method. Otherwise it will not be accessible from outside this method.
I asume the nodelist will be empty when the feed is empty? Then it will look something like this:
public class CustomizedListView extends Activity {
private Button btnLoadMore;
public void onCreate(){
btnLoadMore = new Button(this);
<do stuff>
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Starting a new async task
new LoadMoreListView().execute();
}
});
new LoadMoreListView().execute();// execute the AsyncTask once in the onCreate, so you don't have to duplicate the code here to load the listview.
}
private class LoadMoreListView extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
< Show dialog>;
}
#Override
protected Void doInBackground(Void... unused) {
Boolean listIsEmpty;
< Page request>;
< Retrieve element list>;
< If element list size == 0, listIsEmpty = true; return listIsEmpty>;
< Process elements, fill list etc.>;
< End of doInBackground, listIsEmpty = false; return listIsEmpty>;
}
#Override
protected void onPostExecute(Boolean listIsEmpty) {
< If listIsEmpty == true -> btnLoadMore.setVisibility(View.GONE);>
< Close dialog>
}
}
}
}
I achieved load more using this way I dont use footer view for it
public boolean mHasLoadMore = false;
class MyAdapter extends ArrayAdapter implements OnItemClickListener{
public MyAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
}
public int getTotal(){
return super.getCount();
}
#Override
public int getCount() {
if(super.getCount()>0)
return super.getCount()+1;
else
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if( getTotal() == (position+1) && mHasLoadMore ){
TextView loadMoreView = new TextView(getContext());
loadMoreView.setText("Load More");
return loadMoreView;
}
else {
View theView = new View(getContext());
// inflate & add what you need for item view here you can modify it to reuse convertView also
return theView;
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
if( getTotal() == (position+1) && mHasLoadMore ){
// load more button clicked do handling for load more launch async
//task to do load more after that if found 0 result change mHasLoadMore to false
//& call notifydatadetchanged
}
else
{
// handle item click here
}
}
}
Use such adapter for your listview & set value of mHasLoadMore first time while loading data & call notifydatasetchanged
Related
i'm making a news app which in the news activity i have a tab slider with 2 tabs called , "new news" - "random or top news". which each tabs content are fragment.(i hope u get me!).
but the problem is im using a code to parse the this page content > http://aliak.xzn.ir/rap/get_all_products.php (i think u findout what site code im using)...
the problem is that if i want to show this in fragment(not activity) i have to write this code:
public class tab1 extends ListFragment {}
instead of this :
public class tab1 extends Fragment {}
and i the pager adapter i have problem which tells me the listfragment is not accepted! and if i dont use list fragment i have many errors!
THE CODES FOR APP :
my tab1 fragment ::
public class tab1 extends ListFragment {
//static final String url_all_products = "http://aliak.xzn.ir/rap/get_all_products.php";
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
final String TAG_SUCCESS = "success";
final String TAG_PRODUCTS = "products";
final String TAG_PID = "pid";
final String TAG_NAME = "name";
// JSON Node names
// products JSONArray
JSONArray products = null;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_1, container, false);
/**
* Background Async Task to Load all product by making HTTP Request
*/
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("درحال دريافت اخبار،کمي صبر کنيد!");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest("http://aliak.xzn.ir/rap/get_all_products.php", "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getActivity().getApplicationContext(),
Main.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), productsList,
R.layout.list_item, new String[]{TAG_PID,
TAG_NAME},
new int[]{R.id.pid, R.id.name});
// updating listview
setListAdapter(adapter);
}
});
}
}
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
return v;
}
}
my adapter class :
/**
* Created by hp1 on 21-01-2015.
*/
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
// Build a Constructor and assign the passed Values to appropriate values in the class
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
//This method return the fragment for the every position in the View Pager
#Override
public Fragment getItem(int position) {
if (position == 0) // if the position is 0 we are returning the First tab
{
tab1 tab1 = new tab1();
return tab1;
} else // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab
{
tab2 tab2 = new tab2();
return tab2;
}
}
/*
*/
// This method return the titles for the Tabs in the Tab Strip
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
// This method return the Number of tabs for the tabs Strip
#Override
public int getCount() {
return NumbOfTabs;
}
}
IF U NEEDED MORE CODES JUST TELL ME , ILL ANSWER IN 2 MIN TOPS!
check your imports and make sure your Fragment and ListFragment come from the same package, i.e. both android.support.v4.app.Fragment/ListFragment or both android.app.Fragment/ListFragment. Whichever one you use it has to be consistent with your actual fragment class implementations.
I have written a program to display the list of json data from a url which has an image and 5 textviews which is displaying perfectly.
Url : https://itunes.apple.com/search?term=jack+johnson&limit=50.
When i click on an item from the list i want to display the details of that item in another activity based on the track-id
Url : https://itunes.apple.com/lookup?id=659234741
So when i click on the item the details are getting displayed in the textview , but by default it is displaying the details of id = 659234741 for some items or in short the details does not match.
Need some help to figure out the problem
My Code :
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultsList = new ArrayList<HashMap<String, String>>();
lv = getListView();
// Calling async task to get json
new GetTunesDetails().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetTunesDetails extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// 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
tunes = jsonObj.getJSONArray(TAG_RESULT);
// looping through All Products
for (int i = 0; i < tunes.length(); i++) {
JSONObject c = tunes.getJSONObject(i);
artworkImage = c.getString("artworkUrl100");
wrapperType = c.getString("wrapperType");
artistName = c.getString("artistName");
collectionName = c.getString("collectionName");
trackName = c.getString("trackName");
collectionPrice = c.getString("collectionPrice");
trackId = c.getString("trackId");
// tmp hashmap for single contact
HashMap<String, String> tunesMap = new HashMap<String,
String>();
// adding each child node to HashMap key => value
// contact.put(TAG_ID, firstname);
tunesMap.put(TAG_ARTWORK_IMAGE, artworkImage);
tunesMap.put(TAG_WRAPPER_TYPE, wrapperType);
tunesMap.put(TAG_ARTIST_NAME, artistName);
tunesMap.put(TAG_COLLECTION_NAME, collectionName);
tunesMap.put(TAG_TRACK_NAME, trackName);
tunesMap.put(TAG_COLLECTION_PRICE, collectionPrice);
tunesMap.put(TAG_TRACK_ID, trackId);
// adding contact to contact list
resultsList.add(tunesMap);
}
} 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);
if (pDialog.isShowing())
pDialog.dismiss();
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, resultsList);
// Set the adapter to the ListView
lv.setAdapter(adapter);
}
}
ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
int position;
TextView wrapperType, artistName, collectionName, trackName,
collectionPrice;
ImageView artworkImage;
public ListViewAdapter(Context context, ArrayList<HashMap<String, String>>
arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
// this.position = position;
inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.custom_row, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
wrapperType = (TextView) itemView.findViewById(R.id.wrapperType);
artistName = (TextView) itemView.findViewById(R.id.artistName);
collectionName = (TextView) itemView.findViewById(R.id.collectionName);
trackName = (TextView) itemView.findViewById(R.id.trackName);
collectionPrice = (TextView)
itemView.findViewById(R.id.collectionPrice);
// Locate the ImageView in listview_item.xml
artworkImage = (ImageView) itemView.findViewById(R.id.artworkImage);
// Capture position and set results to the TextViews
wrapperType.setText(resultp.get(MainActivity.TAG_WRAPPER_TYPE));
artistName.setText(resultp.get(MainActivity.TAG_ARTIST_NAME));
collectionName.setText(resultp.get(MainActivity.TAG_COLLECTION_NAME));
trackName.setText(resultp.get(MainActivity.TAG_TRACK_NAME));
collectionPrice.setText(resultp.get(MainActivity.TAG_COLLECTION_PRICE));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.TAG_ARTWORK_IMAGE),
artworkImage);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) { // TODO Auto-generated method
Toast.makeText(context, "Clicked at position " + position,
Toast.LENGTH_LONG).show();
Intent intent = new Intent(context, SingleTrack.class);
intent.putExtra("track_image",
resultp.get(MainActivity.TAG_ARTWORK_IMAGE));
intent.putExtra("wrapper_type",
resultp.get(MainActivity.TAG_WRAPPER_TYPE));
intent.putExtra("artistName",
resultp.get(MainActivity.TAG_ARTIST_NAME));
intent.putExtra("collectionName",
resultp.get(MainActivity.TAG_COLLECTION_NAME));
intent.putExtra("trackName",
resultp.get(MainActivity.TAG_TRACK_NAME));
intent.putExtra("collectionPrice",
resultp.get(MainActivity.TAG_COLLECTION_PRICE));
intent.putExtra("trackId",
resultp.get(MainActivity.TAG_TRACK_ID));
context.startActivity(intent);
}
});
return itemView;
}
SingleTrack.java : This is the class where i displaying the details on single item click
public class SingleTrack extends Activity {
// URL to get contacts JSON
private static String url = "";
// JSON Node names
static final String TAG_RESULT = "results";
static final String TAG_ARTWORK_IMAGE = "artworkUrl100";
static final String TAG_WRAPPER_TYPE = "wrapperType";
static final String TAG_ARTIST_NAME = "artistName";
static final String TAG_COLLECTION_NAME = "collectionName";
static final String TAG_TRACK_NAME = "trackName";
static final String TAG_COLLECTION_PRICE = "collectionPrice";
static final String TAG_TRACK_ID = "trackId";
// contacts JSONArray
JSONArray tracks = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> singleTrackDetails;
ProgressDialog pDialog;
String passedData1, passedData2, passedData3, passedData4, passedData5,
passedData6, passedData7;
TextView wrapperTypeText, artistNameText, collectionNameText, trackNameText,
collectionPriceText;
ImageView trackImage;
String artworkImage, wrapperType, artistName, collectionName, trackName,
collectionPrice, trackId;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.single_track);
wrapperTypeText = (TextView) findViewById(R.id.wrapperType1);
artistNameText = (TextView) findViewById(R.id.artistName1);
collectionNameText = (TextView) findViewById(R.id.collectionName1);
trackNameText = (TextView) findViewById(R.id.trackName1);
collectionPriceText = (TextView) findViewById(R.id.collectionPrice);
trackImage = (ImageView) findViewById(R.id.artworkImage1);
passedData1 = getIntent().getStringExtra("track_image");
passedData2 = getIntent().getStringExtra("wrapper_type");
passedData3 = getIntent().getStringExtra("artistName");
passedData4 = getIntent().getStringExtra("collectionName");
passedData5 = getIntent().getStringExtra("trackName");
passedData6 = getIntent().getStringExtra("collectionPrice");
passedData7 = getIntent().getStringExtra("trackId");
singleTrackDetails = new ArrayList<HashMap<String, String>>();
// url
url = "https://itunes.apple.com/lookup?id=" + passedData7;
// Calling async task to get json
new GetSingleTrackDetails().execute();
}
class GetSingleTrackDetails extends AsyncTask<String, Void, String> {
private JSONObject jsonObj;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(SingleTrack.this);
pDialog.setMessage("Loading Track Details...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
// 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
tracks = jsonObj.getJSONArray(TAG_RESULT);
// looping through All Products
for (int i = 0; i < tracks.length(); i++) {
JSONObject c = tracks.getJSONObject(i);
artworkImage = c.getString("artworkUrl100");
wrapperType = c.getString("wrapperType");
artistName = c.getString("artistName");
collectionName = c.getString("collectionName");
trackName = c.getString("trackName");
collectionPrice = c.getString("collectionPrice");
trackId = c.getString("trackId");
// tmp hashmap for single contact
HashMap<String, String> tunesMap = new HashMap<String,
String>();
// adding each child node to HashMap key => value
// contact.put(TAG_ID, firstname);
tunesMap.put(TAG_ARTWORK_IMAGE, artworkImage);
tunesMap.put(TAG_WRAPPER_TYPE, wrapperType);
tunesMap.put(TAG_ARTIST_NAME, artistName);
tunesMap.put(TAG_COLLECTION_NAME, collectionName);
tunesMap.put(TAG_TRACK_NAME, trackName);
tunesMap.put(TAG_COLLECTION_PRICE, collectionPrice);
tunesMap.put(TAG_TRACK_ID, trackId);
// adding contact to contact list
singleTrackDetails.add(tunesMap);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
wrapperTypeText.setText(wrapperType);
artistNameText.setText(artistName);
collectionNameText.setText(collectionName);
trackNameText.setText(trackName);
collectionPriceText.setText(collectionPrice);
}
}
Thank you
The problem is that you are initializing the resultp each element in your getView method, so therefore the last id/element of the listview adapter's data will be considered as the resultp.
Im sure that the id 659234741 is the last element, which will always be the id for each onclick that would happen.
A solution for this is to create a final resultp within your getView method instead of having just one global resultp.
final HashMap<String, String> resultp = data.get(position);
I have been trying to find answers, but it has been hard to find a solution that works.
I tried setting the adapter to null, clearing the actual list but neither seems to work.
I am using a ListView with a ListAdapter and am trying to make it clear on a change of search Text when text is changed.
list.clear(); works but it does not occur on text change.
Here is my code:
private EditText search_input;
private Button search_button;
// progress bar for search results
private ProgressDialog search_loading;
private ListView wordSearchList;
private ListAdapter adapter;
// no result layout
private LinearLayout no_res;
// create list for adapter
ArrayList<HashMap<String, String>> list;
// database helper
private DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dictionary_search);
search_input = (EditText) findViewById(R.id.search_dictionary);
search_button = (Button) findViewById(R.id.search_button);
search_button.setOnClickListener(this);
// linear layout for no results
no_res = (LinearLayout) findViewById(R.id.search_result_ll);
// create hashmap list
list = new ArrayList<HashMap<String, String>>();
// remove views if they exist
search_input.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// REMOVE LIST VIEW AND ADAPTER
// list.clear();
if (no_res.getChildCount() > 0) {
no_res.removeAllViews();
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onClick(View v) {
if (v == search_button) {
// clear list for fresh start
list.clear();
no_res.removeAllViews();
// validate input and that something was entered
if (search_input.getText().toString().length() < 1) {
// missing required info (null was this but lets see)
Toast.makeText(getApplicationContext(),
"Please search for something!", Toast.LENGTH_LONG)
.show();
} else {
String search_data;
search_data = search_input.getText().toString();
// remove any current views on search again
// REMOVE THE LIST VIEW
// execute the query search
List<DatabaseWordsFTS> search_results = db
.getSingleWordSearch(search_data);
// if no search results returned
if (search_results.size() <= 0) {
TextView no_results_tv = new TextView(this);
no_results_tv.setText("No results found.");
no_res.addView(no_results_tv);
}
// setup listview
wordSearchList = (ListView) findViewById(R.id.wordSearchList);
for (DatabaseWordsFTS word_found : search_results) {
// have to create hashmap in loop
HashMap<String, String> map = new HashMap<String, String>();
// convert d id to long
Integer dictionary_id_convert = (int) (long) word_found._dictionaryId;
// extract dictionary from d-id - since it is not a list and
// just a variable
DatabaseDictionary dictionary_found = db
.getDictionary(dictionary_id_convert);
// extract languages to send below
Integer dln_1 = (int) dictionary_found._language1Id;
Integer dln_2 = (int) dictionary_found._language2Id;
Integer dln_3 = (int) dictionary_found._language3Id;
Integer dln_4 = (int) dictionary_found._language4Id;
// get languages for the words based on ids passed in
List<DatabaseLanguages> LanguagesForD = db
.getAllLanguagesWithId(dln_1, dln_2, dln_3, dln_4);
// add name to hashmap and rest of the data as strings
map.put("w_1", word_found.get_word1_fts());
map.put("l_1", LanguagesForD.get(0)._language_name);
map.put("d_id", String.valueOf(dictionary_id_convert));
map.put("w_id", String.valueOf(word_found.get_id()));
if (word_found.get_word2_fts() != null) {
map.put("w_2", word_found.get_word2_fts());
map.put("l_2", LanguagesForD.get(1)._language_name);
}
if (word_found.get_word3_fts() != null) {
map.put("w_3", word_found.get_word3_fts());
map.put("l_3", LanguagesForD.get(2)._language_name);
}
if (word_found.get_word4_fts() != null) {
map.put("w_4", word_found.get_word4_fts());
map.put("l_4", LanguagesForD.get(3)._language_name);
}
list.add(map);
// used to dismiss progress bar for searching
search_loading.dismiss();
}
String[] from = { "w_1", "w_2", "w_3", "w_4" }; // , "word3",
// "word4"
int[] to = { R.id.textName, R.id.textLanguage };
adapter = new SimpleAdapter(this, list,
R.layout.dictionary_row, from, to);
wordSearchList.setAdapter(adapter);
wordSearchList
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
HashMap itemValue = (HashMap) wordSearchList
.getItemAtPosition(position);
String w_id = (String) itemValue.get("w_id");
String d_id = (String) itemValue.get("d_id");
String l_1 = (String) itemValue.get("l_1");
String l_2 = (String) itemValue.get("l_2");
String l_3 = (String) itemValue.get("l_3");
String l_4 = (String) itemValue.get("l_4");
String w_1 = (String) itemValue.get("w_1");
String w_2 = (String) itemValue.get("w_2");
String w_3 = (String) itemValue.get("w_3");
String w_4 = (String) itemValue.get("w_4");
// Show Alert
Toast.makeText(
getApplicationContext(),
"Position :" + itemPosition
+ " ListItem : " + w_id,
Toast.LENGTH_LONG).show();
// creating bundle
Bundle d_data = new Bundle();
// add to bundle
d_data.putString("w_id", w_id);
d_data.putString("wd_id", d_id);
d_data.putString("w_1", w_1);
d_data.putString("l_1", l_1);
// get tags only if it exists
if (w_2 != null) {
d_data.putString("w_2", w_2);
d_data.putString("l_2", l_2);
}
if (w_3 != null) {
d_data.putString("w_3", w_3);
d_data.putString("l_3", l_3);
}
if (w_4 != null) {
d_data.putString("w_4", w_4);
d_data.putString("l_4", l_4);
}
// start new intent based on the tag -
Intent single_word_view = new Intent(
DictionaryWordSearch.this,
DictionarySingleWordView.class);
// call extras
single_word_view.putExtras(d_data);
// new_dictionary_view.putExtra("d_id",
// WhatAmISupposeToPassInHere);
startActivity(single_word_view);
}
});
}
EDIT: (Below worked for me)
Changed ListAdapter to SimpleAdapter
if(adapter != null){list.clear(); adapter.notifyDataSetChanged();}
Added the above code in onTextChange
Look if you want the TextView with no result you can implement this code
listView.setEmptyView(emptyView)
and pass your TextView to this method ,
for clearing the ListView you can clear your collection and call notifyChangeDataSet or set adapter with null try both and feed me back
I want to display first 10 item continue to upload to 10 item when they reach the end of the list. The error: "The method setOnScrollListener(AbsListView.OnScrollListener) in the type AbsListView is not applicable for the arguments (new Runnable(){})" in line list=getListView().setOnScrollListener(this);. How to fix?
public class CustomizedListView extends ListActivity implements OnScrollListener{
private ProgressDialog pDialog;
// All static variables
static final String URL = "https://api.api2cart.com/v1.0/product.list.xml?api_key=6aed775211e8c3d556db063d12125d2d&store_key=ed58a22dfecb405a50ea3ea56979360d&start=0&count=19¶ms=id,u_model,name,price,images,short_description";
// XML node keys
static final String KEY_SONG = "product"; // parent node
static final String KEY_ID = "id";
static final String KEY_TITLE = "u_model";
static final String KEY_ARTIST = "name";
static final String KEY_DURATION = "price";
static final String KEY_THUMB_URL = "http_path";
static final String KEY_SHORT_DESCRIPTION = "short_description";
ListView list;
LazyAdapter adapter;
ArrayList<HashMap<String, String>> songsList;
//#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
songsList = new ArrayList<HashMap<String, String>>();
new LoadCatalog().execute();
}
public void onScroll(AbsListView view, int firstVisible, int visibleCount, int totalCount) {
boolean loadMore = /* maybe add a padding */
firstVisible + visibleCount >= totalCount;
if(loadMore) {
adapter.count += visibleCount; // or any other amount
adapter.notifyDataSetChanged();
}
}
public void onScrollStateChanged(AbsListView v, int s) { }
class LoadCatalog extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CustomizedListView.this);
pDialog.setMessage("Загрузка каталога ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_SONG);
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_ID, parser.getValue(e, KEY_ID));
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
map.put(KEY_SHORT_DESCRIPTION, parser.getValue(e, KEY_SHORT_DESCRIPTION));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
// adding HashList to ArrayList
songsList.add(map);
}
return null;
}
public void onScroll(AbsListView view, int firstVisible, int visibleCount, int totalCount) {
boolean loadMore = /* maybe add a padding */
firstVisible + visibleCount >= totalCount;
if(loadMore) {
adapter.count += visibleCount; // or any other amount
adapter.notifyDataSetChanged();
}
}
public void onScrollStateChanged(AbsListView v, int s) { }
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
list=getListView().setOnScrollListener(this);
adapter=new LazyAdapter(CustomizedListView.this, songsList);
list.setAdapter(adapter);
}
});
} }}
Change "this" for CustomizedListView.this, with "this" you are actually refering to the Runnable Object you created inside the parameters of runOnUiThread method, you should point to the class that implements the Scroll Listener by using "CustomizedListView.this" (in case CustomizedListView implements the Scroll Listener interface)
Hope this Helps.
Regards
#Override
public void onStart() {
super.onStart();
getListView().setOnScrollListener(this);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
I treat XML and deduce which category parent_id = 0. Each line in the list has a unique id. How to display the list of strings that Activity belong to this line? (eg string has id = 1. When you click on this line you want to display a string in which the parent_id = 1). Need to use the new Activity or can use CatalogActivity.java?
CatalogActivity.java
public class CatalogActivity extends ListActivity {
private ProgressDialog pDialog;
static final String URL = "https://api.api2cart.com/v1.0/category.list.xml?api_key=6aed775211e8c3d556db063d12125d2d&store_key=ed58a22dfecb405a50ea3ea56979360d&start=0&count=38¶ms=id,name,parent_id,images";
static final String KEY_ITEM = "category";
static final String KEY_ID = "id";
static final String KEY_PARENT_ID = "parent_id";
static final String KEY_TITLE = "name";<br>
static final String KEY_THUMB_URL = "http_path";
String Parend_id;
int id_parent;
ListView list;
LazyAdapter adapter;
ArrayList<HashMap<String, String>> catalogList;
//#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
catalogList= new ArrayList<HashMap<String, String>>();
new LoadCatalog().execute();
}
class LoadCatalog extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CatalogActivity.this);
pDialog.setMessage("Загрузка каталога ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all song nodes <song>
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);
Parend_id=parser.getValue(e, KEY_PARENT_ID);
if(Parend_id.equals("0")) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
catalogList.add(map);
}
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
list=getListView();
adapter=new LazyAdapter(CatalogActivity.this, catalogList);
list.setAdapter(adapter);
}
});
// list=(ListView)findViewById(R.id,list);
// Getting adapter by passing xml data ArrayList
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent showInfo = new Intent(getApplicationContext(), CatalogActivity.class);
startActivity(showInfo);
}
});
}
}
}
example XML file (XML rendered as a PNG)
When I click on Components in ListView put Mac as id Components = parent_id Mac