I am building one app having One list view showing the list of My favorites Fans. My list of Fans is this!
When i click on any item of this list then it show me complete profile of the concern Fan e.g., this
My Code is ->
public class FavouriteFansActivity extends ListActivity implements OnItemClickListener, OnLongClickListener {
ListView mFavFansListView;
JSONArray jArrayFavFans;//jArrayFavFans that contains jobjects of all fans. each jobj hv data of 1 unique fan!
JSONObject jFavFan_Data;//contain data of an indivisual fan
LazyAdapter adapter;
ArrayList<Object> favFansList;
ArrayList<String> mfavFansImgs;
ItemBean bean;
String favFans;
//String url="http://XXXXX/ManU/";//Live
String url="http://XXXXX/ManU/";//Local
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.on_favourite_fan_list);
prepareFavFanArrayLits();//method that prepare list of my favorite fans....
mFavFansListView = (ListView) findViewById(android.R.id.list);
adapter = new LazyAdapter(this, mfavFansImgs, favFansList);
mFavFansListView.setAdapter(adapter);
mFavFansListView.setOnItemClickListener(this);
mFavFansListView.setOnLongClickListener(this);
/** I am still not getting that when to call onPause(), onResume(), onRestart()... etc ??? */
}
/* .........onItemClick......... */
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
// TODO Auto-generated method stub
ItemBean bean = (ItemBean) adapter.getItem(position);
/**from here-> I am going to start one activity that show the complete profile of a
* particular Fan... According to the unique id received from clicking on ListItem!
*/
Intent in= new Intent(getParent(), FavFanProfile.class);
TabGroupActivity prnt = (TabGroupActivity) getParent();
Bundle fBundle= new Bundle();
fBundle.putString("fanId", bean.getUid());
in.putExtras(fBundle);
prnt.startChildActivity("FavFanProfile", in);
}
/* .........onLongClick......... */
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(FavouriteFansActivity.this, "To remove...Clk", Toast.LENGTH_SHORT).show();
return false;
}
/** Method used to prepare the List of Favorite Fans
* #author Rupesh */
public void prepareFavFanArrayLits() {
/* return me array containing data of all favFans */
Boolean mkFavFansList=false;
SharedPreferences favFansData = getSharedPreferences("jArrayFavFansPref", MODE_WORLD_WRITEABLE);
favFans=favFansData.getString("favFansData", "");
Log.i("FavFans_List->", "FavFans_DATA readed from prefs:"+favFans.toString());
if(!favFans.equals("")){
try {
mkFavFansList=true;
jArrayFavFans=new JSONArray(favFans);
favFansList = new ArrayList<Object>();
mfavFansImgs = new ArrayList<String>();
Log.i("fav_fansONfav", jArrayFavFans.toString());
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}else {
Log.i("else_favList_img", "list & image are initialized");
favFansList = new ArrayList<Object>();
mfavFansImgs = new ArrayList<String>();
}
// ++++++++
if(mkFavFansList){
try {
for (int i = 0; i < jArrayFavFans.length(); i++) {
// will return the data of each row fetched from JSONArray returned by location1.php
String data_of_each_user = jArrayFavFans.get(i).toString();
Log.i("Data Of User at index " + i + " is", data_of_each_user);
// I put the object at index "i" into JSONObject & retrieve data from name-value pair
jFavFan_Data = jArrayFavFans.getJSONObject(i);// data of User at index i
// in array
AddObjectToList(jFavFan_Data.getString("uniqid").toString(), jFavFan_Data.getString("name"),
jFavFan_Data.getString("distance"));
//Log.i("URL", url+"images/"+jFavFan_Data.get("uniqid").toString()+".png");
mfavFansImgs.add(url+"images/"+jFavFan_Data.get("uniqid").toString()+".png");
Log.i("IMG_URL", url+"images/"+jFavFan_Data.get("uniqid").toString()+".png");
String nm = jFavFan_Data.get("name").toString();
String uid = jFavFan_Data.get("uniqid").toString();
String dis = jFavFan_Data.get("distance").toString();
//System.out.println("Your Name: " + nm);
System.out.println("Your Unique Id: " + uid);
//System.out.println("Your Distance: " + dis);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
} else {
Log.i("NO_FAVORITE_FANS", "No Favorite Fans are added in favorites List!");
Toast.makeText(FavouriteFansActivity.this, "No Fans in Favorite List!", Toast.LENGTH_SHORT).show();
}
// ++++++++++
}
//**********************setting vales in bean*************************
public void AddObjectToList(String uid, String title, String desc) {
bean = new ItemBean();
bean.setUid(uid);
bean.setDescription(desc);
bean.setTitle(title);
favFansList.add(bean);
}
//***********************************************
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.i("favFansData_FavoriteFansActivity.java", "hi...on resume"+favFans);
prepareFavFanArrayLits();
setContentView(R.layout.on_favourite_fan_list);
mFavFansListView = (ListView) findViewById(android.R.id.list);
adapter = new LazyAdapter(this, mfavFansImgs, favFansList);
mFavFansListView.setAdapter(adapter);// come null pointer exception when no fan data is returned! hendle it...
mFavFansListView.setOnItemClickListener(this);
}
}
I stuck at the point -> That, how to remove one Item(one Fan) from this list(favorite_fans_list) ...???
I try to do something on onLongClick Listener but it doesn`t work.... I pleased to have any pointer or some sample which help me to overcome from this problem!!!
One way would be to modify the content in the adapter and then notify the listview has changed.
Your adapter holds an ArrayList for the data backing it.
You need to remove the object from the list. Then notify the adapter that the set has changed as follows.
favFansList.remove(index);
adapter.notifyDataSetChanged()
Related
i am working on a ecommerce app and i have a list where list of items will be there. Just like product name, price, discounted value etc fetched from database.
i am using ListView to show products where every item have there seprate Menu_ID. Whenever i click on list item following code is run where i use putExtra to open speciefic menu_id item details.
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
// go to menu detail page
Intent iDetail = new Intent(ActivityMenuList.this, ActivityMenuDetail.class);
iDetail.putExtra("menu_id", Menu_ID.get(position));
startActivity(iDetail);
}
and new activity will be open with product detail where i display add to cart button whenever i click on add to cart button item display in cart activity.
code is like
public void inputDialog() {
// open database first
try {
dbhelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(R.string.order);
alert.setMessage(R.string.number_order);
alert.setCancelable(false);
final EditText edtQuantity = new EditText(this);
int maxLength = 3;
edtQuantity.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
edtQuantity.setInputType(InputType.TYPE_CLASS_NUMBER);
alert.setView(edtQuantity);
alert.setPositiveButton("Add", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String temp = edtQuantity.getText().toString();
int quantity = 0;
// when add button clicked add menu to order table in database
if (!temp.equalsIgnoreCase("")) {
quantity = Integer.parseInt(temp);
Toast.makeText(getApplicationContext(), "Success add product to cart", Toast.LENGTH_SHORT).show();
if (dbhelper.isDataExist(Menu_ID)) {
dbhelper.updateData(Menu_ID, quantity, (Menu_price * quantity));
} else {
dbhelper.addData(Menu_ID, Menu_name, quantity, (Menu_price * quantity));
}
checkoutButton.setEnabled(true);
checkoutButton.setBackgroundColor(R.color.ColorPrimaryDark);
checkoutButton.setTextColor(Color.WHITE);
} else {
dialog.cancel();
checkoutButton.setEnabled(false);
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// when cancel button clicked close dialog
dialog.cancel();
}
});
alert.show();
}
Now the question is
i want to display add to cart button in product list where i place my order directly from product list without opening product detail.
ListActivity is like
public class ActivityMenuList extends AppCompatActivity {
ListView listMenu;
ProgressBar prgLoading;
SwipeRefreshLayout swipeRefreshLayout = null;
EditText edtKeyword;
ImageButton btnSearch;
TextView txtAlert;
// declare static variable to store tax and currency symbol
public static double Tax;
public static String Currency;
private ActivityMenuDetail details;
// declare adapter object to create custom menu list
AdapterMenuList mla;
// create arraylist variables to store data from server
public static ArrayList<Long> Menu_ID = new ArrayList<Long>();
public static ArrayList<String> Menu_name = new ArrayList<String>();
public static ArrayList<Double> Menu_price = new ArrayList<Double>();
public static ArrayList<String> Menu_image = new ArrayList<String>();
public static ArrayList<Double> Discounted_Price = new ArrayList<Double>();
public static ArrayList<String> Discounted_Value = new ArrayList<String>();
public static ArrayList<Double> Our_Price = new ArrayList<Double>();
String MenuAPI;
String fullAPI;
String TaxCurrencyAPI;
int IOConnect = 0;
long Category_ID;
String Category_name;
String Keyword;
// create price format
DecimalFormat formatData = new DecimalFormat("#.##");
DecimalFormat formatData1 = new DecimalFormat("#.##");
DecimalFormat formatData2 = new DecimalFormat("#.##");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_list);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final android.support.v7.app.ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(R.string.title_menu);
}
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setColorSchemeResources(R.color.orange, R.color.green, R.color.blue);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
listMenu = (ListView) findViewById(R.id.listMenu);
edtKeyword = (EditText) findViewById(R.id.edtKeyword);
btnSearch = (ImageButton) findViewById(R.id.btnSearch);
txtAlert = (TextView) findViewById(R.id.txtAlert);
// menu API url
MenuAPI = Config.ADMIN_PANEL_URL+"/api/get-menu-data-by-category-id2.php"+"?accesskey="+Config.AccessKey+"&category_id=";
// tax and currency API url
TaxCurrencyAPI = Config.ADMIN_PANEL_URL+"/api/get-tax-and-currency.php"+"?accesskey="+Config.AccessKey;
// get category id and category name that sent from previous page
Intent iGet = getIntent();
Category_ID = iGet.getLongExtra("category_id",0);
Category_name = iGet.getStringExtra("category_name");
MenuAPI += Category_ID;
mla = new AdapterMenuList(ActivityMenuList.this);
// call asynctask class to request tax and currency data from server
new getTaxCurrency().execute();
// event listener to handle search button when clicked
btnSearch.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
// get keyword and send it to server
try {
Keyword = URLEncoder.encode(edtKeyword.getText().toString(), "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MenuAPI += "&keyword=" + Keyword;
IOConnect = 0;
listMenu.invalidateViews();
clearData();
new getDataTask().execute();
}
});
// event listener to handle list when clicked
listMenu.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
// go to menu detail page
Intent iDetail = new Intent(ActivityMenuList.this, ActivityMenuDetail.class);
iDetail.putExtra("menu_id", Menu_ID.get(position));
startActivity(iDetail);
}
});
// Using to refresh webpage when user swipes the screen
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
IOConnect = 0;
listMenu.invalidateViews();
clearData();
new getDataTask().execute();
}
}, 3000);
}
});
listMenu.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
boolean enable = false;
if (listMenu != null && listMenu.getChildCount() > 0) {
boolean firstItemVisible = listMenu.getFirstVisiblePosition() == 0;
boolean topOfFirstItemVisible = listMenu.getChildAt(0).getTop() == 0;
enable = firstItemVisible && topOfFirstItemVisible;
}
swipeRefreshLayout.setEnabled(enable);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_category, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.cart:
// refresh action
Intent i = new Intent(ActivityMenuList.this, ActivityCart.class);
startActivity(i);
return true;
case R.id.refresh:
IOConnect = 0;
listMenu.invalidateViews();
clearData();
new getDataTask().execute();
return true;
case android.R.id.home:
// app icon in action bar clicked; go home
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// asynctask class to handle parsing json in background
public class getTaxCurrency extends AsyncTask<Void, Void, Void>{
// show progressbar first
getTaxCurrency(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(View.VISIBLE);
txtAlert.setVisibility(View.GONE);
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONDataTax();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(View.GONE);
// if internet connection and data available request menu data from server
// otherwise, show alert text
if((Currency != null) && IOConnect == 0){
new getDataTask().execute();
}else{
txtAlert.setVisibility(View.VISIBLE);
}
}
}
// method to parse json data from server
public void parseJSONDataTax(){
try {
// request data from tax and currency API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(TaxCurrencyAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
// parse json data and store into tax and currency variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data"); // this is the "items: [ ] part
JSONObject object_tax = data.getJSONObject(0);
JSONObject tax = object_tax.getJSONObject("tax_n_currency");
Tax = Double.parseDouble(tax.getString("Value"));
JSONObject object_currency = data.getJSONObject(1);
JSONObject currency = object_currency.getJSONObject("tax_n_currency");
Currency = currency.getString("Value");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
IOConnect = 1;
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// clear arraylist variables before used
void clearData(){
Menu_ID.clear();
Menu_name.clear();
Menu_price.clear();
Menu_image.clear();
Discounted_Value.clear();
Discounted_Price.clear();
Our_Price.clear();
}
// asynctask class to handle parsing json in background
public class getDataTask extends AsyncTask<Void, Void, Void>{
// show progressbar first
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(View.VISIBLE);
txtAlert.setVisibility(View.GONE);
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(View.GONE);
// if data available show data on list
// otherwise, show alert text
if(Menu_ID.size() > 0){
listMenu.setVisibility(View.VISIBLE);
listMenu.setAdapter(mla);
}else{
txtAlert.setVisibility(View.VISIBLE);
}
}
}
// method to parse json data from server
public void parseJSONData(){
clearData();
try {
// request data from menu API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(MenuAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
// parse json data and store into arraylist variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data"); // this is the "items: [ ] part
for (int i = 0; i < data.length(); i++) {
JSONObject object = data.getJSONObject(i);
JSONObject menu = object.getJSONObject("Menu");
Menu_ID.add(Long.parseLong(menu.getString("Menu_ID")));
Menu_name.add(menu.getString("Menu_name"));
Menu_price.add(Double.valueOf(formatData.format(menu.getDouble("Price"))));
Discounted_Price.add(Double.valueOf(formatData1.format(menu.getDouble("Discounted_Price"))));
Our_Price.add(Double.valueOf(formatData2.format(menu.getDouble("Our_Price"))));
Menu_image.add(menu.getString("Menu_image"));
Discounted_Value.add(menu.getString("Discounted_Value"));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
//mla.imageLoader.clearCache();
listMenu.setAdapter(null);
super.onDestroy();
}
#Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
finish();
}
ListAdapter code
public class AdapterMenuList extends BaseAdapter {
private Activity activity;
private ActivityMenuDetail details;
public AdapterMenuList(Activity act) {
this.activity = act;
}
public AdapterMenuList(ActivityMenuDetail details) {
this.details = details;
}
public int getCount() {
return ActivityMenuList.Menu_ID.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.lsv_item_menu_list, null);
holder = new ViewHolder();
holder.txtText = (TextView) convertView.findViewById(R.id.txtText);
holder.txtSubText = (TextView) convertView.findViewById(R.id.txtSubText);
holder.imgThumb = (ImageView) convertView.findViewById(R.id.ImageCatList);
holder.discounted_Price = (TextView) convertView.findViewById(R.id.DiscPriceCatList);
holder.discounted_Value = (TextView) convertView.findViewById(R.id.DiscValueCatList);
holder.discounted_Price.setTextColor(Color.GRAY);
holder.discounted_Price.setPaintFlags(holder.discounted_Price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
holder.addtocart = (TextView) convertView.findViewById(R.id.Listaddtocart);
holder.layout = (LinearLayout) convertView.findViewById(R.id.Listcardview);
holder.our_Price = (TextView) convertView.findViewById(R.id.Our_Price);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.discounted_Value.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
if(editable.toString().equals("0 % off") | editable.toString().equals("00 % off")){
// 1 - You can set empty text
holder.discounted_Value.setText("");
// 2 - Or you can change the color of the text
holder.discounted_Value.setTextColor(Color.TRANSPARENT);
// 3 - Or you can change the visibility of the view
holder.discounted_Value.setVisibility(View.INVISIBLE);
holder.layout.setVisibility(View.GONE);
}else{
//Here you should undo your code
//1 - if you using method one dose not need to do anything here
// for method 2
holder.discounted_Value.setTextColor(Color.BLACK);
// for method 3
holder.discounted_Value.setVisibility(View.VISIBLE);
holder.layout.setVisibility(View.VISIBLE);
}
}
});
holder.txtText.setText(ActivityMenuList.Menu_name.get(position));
holder.txtSubText.setText("\u20B9" + ActivityMenuList.Menu_price.get(position));
holder.discounted_Price.setText("\u20B9" + ActivityMenuList.Discounted_Price.get(position));
holder.discounted_Value.setText(ActivityMenuList.Discounted_Value.get(position)+ " % off");
holder.our_Price.setText("Our Price" + " " + "\u20B9" + ActivityMenuList.Our_Price.get(position));
Picasso.with(activity).load(Config.ADMIN_PANEL_URL+"/"+ActivityMenuList.Menu_image.get(position)).placeholder(R.drawable.loading).into(holder.imgThumb);
return convertView;
}
static class ViewHolder {
TextView txtText, txtSubText, discounted_Price, quantity, discounted_Value, our_Price;
ImageView imgThumb;
TextView addtocart;
LinearLayout layout;
}
}
Any idea how can i put add to cart button in listview item where i place order from list without opening new activity.
thankx.
Yes it is pretty straight forward to do.
Just add the "add to cart" option in every item itself.
So in the listview, show add to cart at the right most side where the user can click to add to the cart directly.
To get the click, in the base adapter in the getView() method, set the click listener on that holder item(add to cart button) and do the stuff in its onClick.
Sorry for my bad english.I am new to android and i parsed json data into listview,now i want to put on him a search functionality,but i have a problem,when i entered a words in edittext,then in the listview my items are duplicated,and items has been increases,look my code and screen shots.Thanks in advance and any help will be much appreciated.
My Artist Activity:
public class Artists extends Activity {
// Connection detector
ConnectionDetector cd;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
// This is not using now if you want you can remove its all references :)
ArrayList<HashMap<String, String>> albumsList;
ArrayList<AdapterDTOArtist> mAdapterDTOs = null;
private LazyAdapterArtist mLazyAdatper = null;
private ArrayList<String> array_sort = new ArrayList<String>();
int textlength = 0;
// albums JSONArray
JSONArray albums = null;
LinearLayout ll_artists_chart;
LinearLayout ll_artists_newrelease;
private EditText etSearch;
private static String URL_ALBUMS = "http://triplevmusic.com/dev/webservice/index.php?op=fetch_artists.json";
// JSON Node names
private static final String TAG_CONTACTS = "data";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private ListView lv = null;
EditText et_artists_searchWord;
// contacts JSONArray
JSONArray contacts = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.artists);
lv = (ListView) findViewById(R.id.artist_main_list_id);
cd = new ConnectionDetector(getApplicationContext());
// Check for internet connection
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(Artists.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Hashmap for ListView
albumsList = new ArrayList<HashMap<String, String>>();
mAdapterDTOs = new ArrayList<AdapterDTOArtist>();
// Loading Albums JSON in Background Thread
new LoadAlbums().execute();
// get listview
/**
* Listview item click listener TrackListActivity will be lauched by
* passing album id
* */
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
// on selecting a single album
}
});
ll_artists_chart = (LinearLayout) findViewById(R.id.ll_artists_chart);
ll_artists_newrelease = (LinearLayout) findViewById(R.id.ll_artists_newrelease);
et_artists_searchWord = (EditText) findViewById(R.id.et_artists_searchWord);
et_artists_searchWord.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
// ((Filterable) Artists.this.mAdapterDTOs).getFilter().filter(s);
List<AdapterDTOArtist> list = filter(s.toString(),mAdapterDTOs, true);
mAdapterDTOs.addAll(list);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
ll_artists_chart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getBaseContext(), ChartActivity.class);
startActivity(intent);
// finish();
}
});
ll_artists_newrelease.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getBaseContext(), NewReleases.class);
startActivity(intent);
//finish();
}
});
}
/**
* Background Async Task to Load all Albums by making http request
* */
class LoadAlbums extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Artists.this);
pDialog.setMessage("Listing Artists ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Albums JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
//List<NameValuePair> params = new ArrayList<NameValuePair>();
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(URL_ALBUMS);
// getting JSON string from URL
//String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET", params);
// Check your log cat for JSON reponse
Log.i("Albums JSON: ", "> " + json);
try {
//albums = new JSONArray(json);
albums = json.getJSONArray(TAG_CONTACTS);
if (albums != null) {
// looping through All albums
for (int i = 0; i < albums.length(); i++) {
JSONObject c = albums.getJSONObject(i);
// Storing each json item values in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
/*String EateryThmbnailUrl = c
.getString(TAG_THMBNAIL_URL);*/
// ~\/Uploads\/EateryImages\/\/7\/41283f1f-8e6f-42d4-b3c1-01f990efb428.gif
/*EateryThmbnailUrl = HOST_URL
+ EateryThmbnailUrl.replace("~", "");*/
AdapterDTOArtist adapterDTO = new AdapterDTOArtist();
adapterDTO.setmTag_Id(id);
adapterDTO.setmTag_Name(name);
// adapterDTO.setmImage_URL(EateryThmbnailUrl);
mAdapterDTOs.add(adapterDTO);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
HashMap<String, Integer> map1 = new HashMap<String, Integer>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
albumsList.add(map);
}
} else {
Log.d("Albums: ", "null");
}
} 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 albums
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
// updating listview
mLazyAdatper = new LazyAdapterArtist(Artists.this,
mAdapterDTOs);
lv.setAdapter(mLazyAdatper);
// mLazyAdatper.setDataSet(mAdapterDTOs);
}
});
}
}
public static List<AdapterDTOArtist> filter(String string,
Iterable<AdapterDTOArtist> iterable, boolean byName) {
if (iterable == null)
return new LinkedList<AdapterDTOArtist>();
else {
List<AdapterDTOArtist> collected = new LinkedList<AdapterDTOArtist>();
Iterator<AdapterDTOArtist> iterator = iterable.iterator();
if (iterator == null)
return collected;
while (iterator.hasNext()) {
AdapterDTOArtist item = iterator.next();
collected.add(item);
}
return collected;
}
}
}
My AdapterDTOArtist class :
public class AdapterDTOArtist {
private String mTag_Id;
private String mTag_Name;
public String getmTag_Name() {
return mTag_Name;
}
public void setmTag_Name(String mTag_Name) {
this.mTag_Name = mTag_Name;
}
public String getmTag_Id() {
return mTag_Id;
}
public void setmTag_Id(String mTag_Id) {
this.mTag_Id = mTag_Id;
}
}
My LazyAdapterArtist class:
public class LazyAdapterArtist extends BaseAdapter {
private Context mContext = null;
private ArrayList<AdapterDTOArtist> mAdapterDTOs = null;
public LazyAdapterArtist(Context context,
ArrayList<AdapterDTOArtist> mAdapterDTOs2) {
// TODO Auto-generated constructor stub
this.mContext = context;
this.mAdapterDTOs = mAdapterDTOs2;
}
public void setDataSet(ArrayList<AdapterDTOArtist> adapterDTOs) {
this.mAdapterDTOs = adapterDTOs;
notifyDataSetChanged();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mAdapterDTOs.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
ViewHolder mHolder = new ViewHolder();
if (row == null) {
// Cell is inflating for first time
row = LayoutInflater.from(mContext)
.inflate(com.whizpool.triplevmusic.R.layout.row_artists,
null, false);
mHolder.mNameTxt = (TextView) row
.findViewById(com.whizpool.triplevmusic.R.id.tv_row_artists);
row.setTag(mHolder);
} else {
// recycling of cells
mHolder = (ViewHolder) row.getTag();
}
mHolder.mNameTxt.setText(mAdapterDTOs.get(position).getmTag_Name());
return row;
}
static class ViewHolder {
TextView mNameTxt = null;
}
}
when parsed json data into listview my app look like this:
when enter word in edittext field then my app look like this:
I just want,when i entered the word for example i enter "D" then in a listview only those words were display which have starting word is "D".Thanks Alot and again sorry for my english.
The problem is that when you filter the data you add again to mAdapterDTOs list the results you need to clear the list before adding the results. To avoid losing your data you have to keep them in a separate list and when user times nothing show them.
Step 1: Use a field for keeping a backup of your data (just as mAdapterDTOs):
ArrayList<AdapterDTOArtist> mAdapterDTOs = null;
ArrayList<AdapterDTOArtist> mAdapterDTOsBackup= null;
Step 2: initialize that field:
mAdapterDTOs = new ArrayList<AdapterDTOArtist>();
mAdapterDTOsBackup = new ArrayList<AdapterDTOArtist>();
Step 3: Fill in all your data to the backup set just after parsing:
/**
* getting Albums JSON
* */
protected String doInBackground(String... args) {
// HERE all your code as it is!!!
// Just before return add a set keeping the backup of your data...
// initialize the set just as mAdapterDTOs
mAdapterDTOsBackup.addAll(mAdapterDTOs);
return null;
}
Step 4: When searching filter data from backup set and then add them on the mAdapterDTOs do not forget to clear it before.
et_artists_searchWord.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
// ((Filterable) Artists.this.mAdapterDTOs).getFilter().filter(s);
List<AdapterDTOArtist> list = filter(s.toString(),mAdapterDTOsBackup, true);
mAdapterDTOs.clear(); // <--- clear the list before add
mAdapterDTOs.addAll(list); // <--- here is the double add if you do not clear before
mLazyAdatper.setDataSet(mAdapterDTOs);// update the adapter data (edit 2)
}
Edit: split answer in steps in order to be more clear the process also added at least one of your line to show where to add each code snippet.
i am newcomer in android domain. , please help me .
i have two string array ,from one array with the help of adapter i get the spinner drop down view.the thing is that when i click the drop down list i have to populate the value of the same position from the second array. i paste my code. please help me.
Code :
class programList extends AsyncTask<String, Long, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String url = "http://mydomain.com/app/getdata.php?type=program_list&id="
+ surveyId;
String output = null;
JSONParserList Jparser = new JSONParserList();
output = Jparser.getJSONFromUrl(url);
return output;
}
#Override
protected void onPostExecute(String output) {
// TODO Auto-generated method stub
Log.e("JSONRESPONSE", output);
try {
JSONObject jObject = new JSONObject(output);
JSONArray OUTPUT = jObject.getJSONArray("OUTPUT");
String[] allStates = new String[OUTPUT.length()+1];
String[] allDistrics = new String[OUTPUT.length()];
allStates[0] = "Select Program";
for (int i = 0; i < OUTPUT.length(); i++) {
JSONObject eachProgram = OUTPUT.getJSONObject(i);
String adb = eachProgram.getString("adp");
String district = eachProgram.getString("district");
String location = eachProgram.getString("location");
String p_id = eachProgram.getString("p_id");
ProgramList programlist = new ProgramList();
programlist.setAdp(adb);
programlist.setDistrict(district);
programlist.setLocation(location);
programlist.setP_id(p_id);
// programlist.setAdpList(adb);
Toast.makeText(getApplicationContext(),
"id: " + programlist.getP_id(), Toast.LENGTH_LONG).show();
programList.add(programlist);
allStates[i+1] = adb;
allDistrics[i] = district;
}
// programDropDown();
Spinner sprogram = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapterstate = new ArrayAdapter<String>(
startSurvey.this, android.R.layout.simple_spinner_item,
allStates);
sprogram.setAdapter(adapterstate);
sprogram.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapter, View v,
int position, long id) {
// TODO Auto-generated method stub
String program = adapter.getItemAtPosition(position).toString();
// long id1 = adapter.getId();
**String d = allDistrics[position-1];**
// Showing selected spinner item
Toast.makeText(getApplicationContext(),
"Program position: " + position, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
// adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
my error is given on that star position
All districts isn't available at that scope, also you need to include the actual log cat errors when you post a question like this please
Edit
Actually variable being available may be your problem, but position I believe is zero-index just like the array and so may also be a problem: position-1 can = -1 and be out of bounds
To fix the scope of your districts variable you can use the final keyword final String[] districts ...
I have a json feed from this URL which contains 20 fields and I parse all the datas..but again I need to load more data from the json feed after showing the 20 fields in listview.
I have created a AsyncTask and loaded the json in listview. this is my class
public void onCreate(Bundle savedInstanceState) {
new DoInBackgrd().execute();
}
private class DoInBackgrd extends AsyncTask<Void, Void, Void> implements
DialogInterface.OnCancelListener {
private ProgressDialog processDialog;
#Override
protected void onPreExecute() {
processDialog = ProgressDialog.show(List.this, "",
getString(R.string.loading), true);
processDialog.setCancelable(true);
}
public void onCancel(DialogInterface arg0) {
// TODO Auto-generated method stub
if (processDialog.isShowing()) {
processDialog.dismiss();
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
Jsonfunctions jParser = new Jsonfunctions();
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
results = json.getJSONArray(TAG_RESULTS);
// looping through All Contacts
for (int i = 0; i < results.length(); i++) {
JSONObject c = results.getJSONObject(i);
id = c.getString(TAG_ID);
name = c.getString(TAG_NAME);
adress = c.getString(TAG_ADRRESS);
latitude = c.getString(TAG_LATITUDE);
latitudeAry.add(c.getString(TAG_LATITUDE).toString());
longitude = c.getString(TAG_lONGITUDE);
latitudeAry.add(c.getString(TAG_lONGITUDE).toString());
distance = c.getString(TAG_DISTANCE);
image = c.getString(TAG_IMAGE);
phone = c.getString(TAG_TELEPHONE);
telphonenumberAry
.add(c.getString(TAG_TELEPHONE).toString());
NameAry.add(c.getString(TAG_NAME).toString());
resourceAry.add(new ResourceClass(point, id, name, adress,
distance, latitude, longitude, phone));
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void unused) {
if (processDialog.isShowing()) {
processDialog.dismiss();
}
listView.setAdapter(new ASyncAdapter());
listView.setDividerHeight(2);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long id) {
Intent details = new Intent(List.this, Details.class);
details.putExtra("position", position + 1);
details.putExtra("name", resourceAry.get(position)
.getName());
details.putExtra("adress", resourceAry.get(position)
.getAdress());
details.putExtra("phone", resourceAry.get(position)
.getTelephone());
details.putExtra("latitudes", latitude);
details.putExtra("longitudes", longitude);
startActivity(details);
}
});
}
}
Thanks in advance
I had just finished working on similar kind of requirement(issue faced on is specified in)
Hence I'm hoping to provide you proper solution that is helpful to you and saves ur time.
If I'm not wrong you need to populate same ListView with next 20(i.e. 21 - 40) fields obtained in response for server api.
In that case u need to call server api again and again for that u need an event. Say u add a 'Next' button and on its click u retrive next 20 fields(21 - 40).
Currently in ur code in 'DoInBackgrd', you are binding/setting Adapter(ASyncAdapter) each time you need to bind new records/fields to ListView. This is not a good practice, also it at a instance it will not refresh fields of newly assigned adapter in listView.
Hence you should :
Just retrieve/parse new fileds from JSon and set them in adapter. Adapter will notify your listView about data change and listView will refresh its view.
Considering that 'ASyncAdapter' is your custom adapter that implements ArrayAdapter, just add following(change Variable type from Restaurant to as per your requirement) method to it.
public void reSet(ArrayList<Resturant> resturantsCache) {
//This will clear your current fields/records in adpter
clear();
//This will new fields/records in adpter from provided resturantsCache ArrayList.
for (Resturant resturant : resturantsCache) {
add(resturant);
}
}
Hope you will be able to replace variable types in provided method and use it as per you requirements, In case you need more help please provide ASyncAdapter code.
Thanks.
This is a follow up question from my question thread exiting error in android
I created an async task but the values do not show up in the list view....
public class History extends Activity implements OnItemClickListener
{
/** Called when the activity is first created. */
ListView list;
//LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
ArrayList<String> listItems;
//DEFINING STRING ADAPTER WHICH WILL HANDLE DATA OF LISTVIEW
ArrayAdapter<String> adapter;
private String resDriver,resPassenger,ID;
private ProgressDialog dialog;
ArrayList<HashMap<String, Object>> listInfo = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> item;
JSONObject jDriver;
//JSONObject jPassenger;
// Make strings for logging
private final String TAG = this.getClass().getSimpleName();
private final String RESTORE = ", can restore state";
private final String state = "Home Screen taking care of all the tabs";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent loginIntent = getIntent();
ID = loginIntent.getStringExtra("ID");
listItems = new ArrayList<String>();
Log.i(TAG, "Started view active rides");
setContentView(R.layout.searchresults);
list = (ListView)findViewById(R.id.ListView01);
list.setOnItemClickListener(this);
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,listItems);
list.setAdapter(adapter);
getInfo();
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3)
{
// TODO Auto-generated method stub
Toast.makeText(this, "u clicked " + listItems.get(position) ,Toast.LENGTH_LONG).show();
}
public void getInfo(){
DownloadInfo task = new DownloadInfo();
task.execute(new String[] { "http://www.vogella.de" });
}
private class DownloadInfo extends AsyncTask<String, Void , ArrayList<String>>{
#Override
protected ArrayList<String> doInBackground(String ... strings) {
ArrayList<String> listItems1;
jDriver = new JSONObject();
try {
jDriver.put("ID", ID);
jDriver.put("task", "GET DATES");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
listItems1 = new ArrayList<String>();
Log.i(TAG,"Sending data for the driver rides");
resDriver = HTTPPoster.sendJson(jDriver,"URL"); // Any Server URL
JSONObject driver;
try {
driver = new JSONObject(resDriver);
Log.i(TAG,"Recieved Driver details");
if ( driver.getString("DATABASE ERROR").equals("False")){
int length = Integer.parseInt( driver.getString("length"));
Log.i(TAG,"length is " + length);
for( int i =0 ; i< length ; i++){
String info = driver.getString(Integer.toString(i));
String[] array = info.split(",");
Log.i(TAG,"array is " + Arrays.toString(array));
Log.i(TAG,"Date "+ array.length);
Log.i(TAG,"DONE WITH THE LOOP");
//listInfo.add(item);
Log.i(TAG,"Date is"+array[0]);
listItems1.add(array[0]);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
listItems1.add("No driver rides created");
}
return listItems1;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
listItems = result;
adapter.notifyDataSetChanged();
}
}
}
The problem is that the values in the adapter do not get modified...
You initialize your adapter with a empty listItems, after your fill your listItems in AsyncTask. onPostExecute(), your adapter is not get updated, try this:
protected void onPostExecute(ArrayList<String> result) {
listItems = result;
adapter.addAll(ListItems);
adapter.notifyDataSetChanged();
}
Hope that help.
listItems = result; won't work, you need to use :
listItems.clear();
listItems.addAll(result);
If you create another list, your adapter won't know it, because it keeps a reference to the old list (which remains the same).