ArrayAdapter not working properly - Android - android

I have a class that extends ArrayAdapter. This class works but the problem is when I add an item to the List it doubles that item, so there are two Identical list items. Here is my current ArrayAdapter class,
class Item {
String username;
String number;
String content;
public Item (String username, String number, String content){
this.username = username;
this.number = number;
this.content = content;
}
public CharSequence getNumber() {
// TODO Auto-generated method stub
return username;
}
public CharSequence getUsername() {
// TODO Auto-generated method stub
return number;
}
public CharSequence getContent() {
// TODO Auto-generated method stub
return content;
}
}
class ListAdapter extends ArrayAdapter<Item> {
public ListAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
}
private List<Item> items;
public ListAdapter(Context context, int resource, List<Item> items) {
super(context, resource, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.list_item, null);
}
final Item p = items.get(position);
if (p != null) {
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
Button numberButton = (Button)v.findViewById(R.id.listNumberButton);
commentView.setText(p.getContent());
NumbersView.setText(p.getNumber());
usernamesView.setText(p.getUsername());
usernameButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("usernameOfProfile", p.username);
startActivity(i);
finish();
}
});
numberButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("NumberProfile", p.number);
startActivity(i);
finish();
}
});
}
return v;
}
}
final List <Item> tempList = new ArrayList <Item>();
ListView yourListView = (ListView) findViewById(android.R.id.list);
final ListAdapter customAdapter = new ListAdapter(DashboardActivity.this, R.layout.list_item, tempList);
yourListView.setAdapter(customAdapter);
Here is my AsyncTask that gathers the information in the background. In the onPostExecute is where I add the Items to my list.
final ProgressDialog progDailog = new ProgressDialog(DashboardActivity.this);
class loadComments extends AsyncTask<JSONObject, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progDailog.setIndeterminate(false);
progDailog.setCancelable(true);
progDailog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
progDailog.show();
progDailog.setContentView(R.layout.progress_circle);
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
protected JSONObject doInBackground(JSONObject... params) {
JSONObject json2 = CollectComments.collectComments(usernameforcomments, offsetNumber);
return json2;
}
#Override
protected void onPostExecute(JSONObject json2) {
try {
if (json2.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res2 = json2.getString(KEY_SUCCESS);
if(Integer.parseInt(res2) == 1){
String username = json2.getString(KEY_USERNAME);
String number = json2.getString(KEY_NUMBER);
String content = json2.getString(KEY_COMMENT);
tempList.add (new Item (username, number, content));
customAdapter.addAll(tempList);
}//end if key is == 1
else{
// Error in registration
registerErrorMsg.setText(json2.getString(KEY_ERROR_MSG));
}//end else
}//end if
} //end try
catch (JSONException e) {
e.printStackTrace();
}//end catch
progDailog.dismiss();
}
}
new loadComments().execute();

Try to clear contents of adapter before you do addAll

Related

Filter returns empty listview

Hi I am trying a search/filter app where data are coming from mySql database to fill up the listview. The populating of listview is working perfectly fine, except for the filtering part. It doesn't filter the listview, it's empty. Help please.
MAIN Activity:
public class MainActivity extends Activity {
public static final String url = "";
// Declare Variables
ListView list;
ListViewAdapter adapter;
EditText editsearch;
String[] rank;
String[] country;
String[] population;
ArrayList<WorldPopulation> arraylist = new ArrayList<WorldPopulation>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Generate list View from ArrayList
displayListView();
// Locate the ListView in listview_main.xml
list = (ListView) findViewById(R.id.listview);
// Pass results to ListViewAdapter Class
adapter = new ListViewAdapter(this, arraylist);
// Binds the Adapter to the ListView
list.setAdapter(adapter);
// Locate the EditText in listview_main.xml
editsearch = (EditText) findViewById(R.id.search);
// Capture Text in EditText
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
}
private void displayListView() {
// Creating volley request obj
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>(){
#Override
public void onResponse(String response) {
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void parseData(String json) {
JSONArray items = null;
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json);
items = jsonObject.getJSONArray("result");
rank = new String[items.length()];
country = new String[items.length()];
population = new String[items.length()];
for (int i = 0; i < items.length(); i++) {
JSONObject jo = items.getJSONObject(i);
rank[i] = jo.getString("rank");
country[i] = jo.getString("country");
population[i] = jo.getString("population");
WorldPopulation wp = new WorldPopulation(rank[i], country[i],
population[i]);
// Binds all strings into an array
arraylist.add(wp);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
BASE Adapter:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<WorldPopulation> worldpopulationlist = null;
private ArrayList<WorldPopulation> arraylist;
public ListViewAdapter(Context context, List<WorldPopulation> worldpopulationlist) {
mContext = context;
this.worldpopulationlist = worldpopulationlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<WorldPopulation>();
this.arraylist.addAll(worldpopulationlist);
}
public class ViewHolder {
TextView rank;
TextView country;
TextView population;
}
#Override
public int getCount() {
return worldpopulationlist.size();
}
#Override
public WorldPopulation getItem(int position) {
return worldpopulationlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.rank = (TextView) view.findViewById(R.id.rank);
holder.country = (TextView) view.findViewById(R.id.country);
holder.population = (TextView) view.findViewById(R.id.population);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.rank.setText(worldpopulationlist.get(position).getRank());
holder.country.setText(worldpopulationlist.get(position).getCountry());
holder.population.setText(worldpopulationlist.get(position).getPopulation());
// Listen for ListView Item Click
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(mContext, SingleItemView.class);
// Pass all data rank
intent.putExtra("rank",(worldpopulationlist.get(position).getRank()));
// Pass all data country
intent.putExtra("country",(worldpopulationlist.get(position).getCountry()));
// Pass all data population
intent.putExtra("population",(worldpopulationlist.get(position).getPopulation()));
// Pass all data flag
// Start SingleItemView Class
mContext.startActivity(intent);
}
});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
}
else
{
for (WorldPopulation wp : arraylist)
{
if (wp.getCountry().toLowerCase(Locale.getDefault()).contains(charText))
{
worldpopulationlist.add(wp);
}
}
}
notifyDataSetChanged();
}
And the model:
public class WorldPopulation {
private String rank;
private String country;
private String population;
public WorldPopulation(String rank, String country, String population) {
this.rank = rank;
this.country = country;
this.population = population;
}
public String getRank() {
return this.rank;
}
public String getCountry() {
return this.country;
}
public String getPopulation() {
return this.population;
}
}

Blank listview getting in android

public class Setting extends Activity implements OnClickListener {
ListView listView1;
ImageView backbutton;
String Url = "http://182.71.212.110:8083/api/values/userdetails";
String Id;
String Designation;
String EmployeeName;
JSONArray _jarray;
DataModel datamodel = new DataModel();
ArrayList<DataModel> list = new ArrayList<DataModel>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.setting);
listView1 = (ListView) findViewById(R.id.listView1);
backbutton = (ImageView) findViewById(R.id.backbutton);
backbutton.setOnClickListener(this);
new GetUserdetail().execute();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.backbutton) {
finish();
}
}
class GetUserdetail extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
String json = HttpHitter.ExecuteData(Url);
_jarray = new JSONArray(json);
System.out.println("_jarray" + _jarray);
for (int i = 0; i <= _jarray.length(); i++) {
JSONObject _obj = _jarray.getJSONObject(i);
if (Id != null) {
datamodel.setId(_obj.getString("Id"));
}
if (Designation != null) {
datamodel.setDesignation(_obj.getString("Designation"));
}
if (EmployeeName != null) {
datamodel.setEmployeeName(_obj
.getString("EmployeeName"));
}
list.add(datamodel);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
CustomList adapter = new CustomList(Setting.this, list);
listView1.setAdapter(adapter);
}
}
}
public class DataModel implements Parcelable {
private String Id = "";
private String Designation = "";
private String EmployeeName = "";
public String getId() {
return Id;
}
public void setId(String id) {
this.Id = id;
}
public String getDesignation() {
return Designation;
}
public void setDesignation(String designation) {
this.Designation = designation;
}
public String getEmployeeName() {
return EmployeeName;
}
public void setEmployeeName(String employeeName) {
this.EmployeeName = employeeName;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
public DataModel() {
// TODO Auto-generated constructor stub
}
public DataModel(Parcel in) {
Id = in.readString();
EmployeeName = in.readString();
Designation = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeString(Id);
dest.writeString(EmployeeName);
dest.writeString(Designation);
}
}
public class CustomList extends BaseAdapter {
Context context;
private ArrayList<DataModel> arrModel;
public CustomList(Context context, ArrayList<DataModel> arrModel) {
this.context = context;
this.arrModel = arrModel;
}
/* private view holder class */
private class ViewHolder {
TextView txtTitle;
TextView txtDesc;
ImageView locationimage;
ImageView roleimageview;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.settingrowitem, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView
.findViewById(R.id.rowcontact_txtName);
holder.txtTitle = (TextView) convertView
.findViewById(R.id.rowcontact_txtrole);
holder.locationimage = (ImageView) convertView
.findViewById(R.id.imageView1);
holder.roleimageview = (ImageView) convertView
.findViewById(R.id.imageView2);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtDesc.setText(arrModel.get(position).getEmployeeName());
holder.txtTitle.setText(arrModel.get(position).getDesignation());
if (position % 2 == 0) {
convertView.setBackgroundColor(Color.parseColor("#ffffff"));
}
else {
convertView.setBackgroundColor(Color.parseColor("#f5f6f1"));
}
return convertView;
}
#Override
public int getCount() {
return arrModel.size();
}
#Override
public Object getItem(int position) {
return arrModel.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
There are three class which I have use to parse data from from web service and and trying to print in Listview .I am able to do Json parsing and getting data from server insetting.javaclass:
list.add(datamodel);
and bind this in list in onpostexcute method:
CustomList adapter = new CustomList(Setting.this, list);
listView1.setAdapter(adapter);
Using this i am trying to print data in listview item but I am getting blank value in each item while Number Json is 49 and i am getting that 49 but getDesignation and getEmploye I am getting blank value please check and tell me where I am doing mistake I have tried much unable to get Print that value please check suggest me
Where are you inistailizind the Id,Designation and EmployeeName, it will be null itself. so doInBackground wont add any datamodel. remove the check
class GetUserdetail extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
String json = HttpHitter.ExecuteData(Url);
_jarray = new JSONArray(json);
System.out.println("_jarray" + _jarray);
for (int i = 0; i <= _jarray.length(); i++) {
DataModel datamodel = new DataModel();
JSONObject _obj = _jarray.getJSONObject(i);
datamodel.setId(_obj.getString("Id"));
datamodel.setDesignation(_obj.getString("Designation"));
datamodel.setEmployeeName(_obj.getString("EmployeeName"));
list.add(datamodel);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
CustomList adapter = new CustomList(Setting.this, list);
listView1.setAdapter(adapter);
}
}
Initialise the model inside the for loop and try once.
To identify changes in your list item you should call
adapter.notifyDataSetChanged();
call it before setting adapter to list view.

Getting image from .epub file in Android

I am using siegmann.nl/epublib to read epub file. My Activity code is mentioned here.
public class EpubReaderActivity extends Activity
{
private LayoutInflater inflater;
private List<RowData> contentDetails;
public static final String BOOK_NAME = "books/wodehouse.epub";
ListView titleListView;
ImageView imgButtonBack;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
titleListView = (ListView)findViewById(R.id.listView1);
inflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
contentDetails = new ArrayList<RowData>();
AssetManager assetManager = getAssets();
try
{
InputStream epubInputStream = assetManager.open(BOOK_NAME);
Book book = (new EpubReader()).readEpub(epubInputStream);
logContentsTable(book.getTableOfContents().getTocReferences(), 0);
}
catch (IOException e)
{
Log.e("epublib", e.getMessage());
}
CustomAdapter adapter = new CustomAdapter(this, R.layout.list,R.id.title, contentDetails);
titleListView.setAdapter(adapter);
titleListView.setTextFilterEnabled(true);
titleListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
RowData rowData = contentDetails.get(position);
Intent intent = new Intent(EpubReaderActivity.this, ContentViewActivity.class);
try
{
intent.putExtra("display", new String(rowData.getResource().getData()));
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
startActivity(intent);
}
});
imgButtonBack = (ImageView)findViewById(R.id.imagBackButton);
imgButtonBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(EpubReaderActivity.this, ListOfBook.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
overridePendingTransition(R.anim.slide_left,R.anim.slide_right);
}
});
}
private class CustomAdapter extends ArrayAdapter<RowData>
{
public CustomAdapter(Context context, int resource, int textViewResourceId, List<RowData> objects)
{
super(context, resource, textViewResourceId, objects);
}
private class ViewHolder
{
private View row;
private TextView titleHolder = null;
public ViewHolder(View row)
{
super();
this.row = row;
}
public TextView getTitle()
{
if(null == titleHolder)
titleHolder = (TextView) row.findViewById(R.id.title);
return titleHolder;
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
TextView title = null;
RowData rowData = getItem(position);
if(null == convertView)
{
convertView = inflater.inflate(R.layout.list, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
title = holder.getTitle();
title.setText(rowData.getTitle());
return convertView;
}
}
private void logContentsTable(List<TOCReference> tocReferences, int depth)
{
if (tocReferences == null)
{
return;
}
for (TOCReference tocReference:tocReferences)
{
StringBuilder tocString = new StringBuilder();
for (int i = 0; i < depth; i++)
{
tocString.append("\t");
}
tocString.append(tocReference.getTitle());
RowData row = new RowData();
row.setTitle(tocString.toString());
row.setResource(tocReference.getResource());
contentDetails.add(row);
logContentsTable(tocReference.getChildren(), depth + 1);
}
}
private class RowData
{
private String title;
private Resource resource;
public RowData()
{
super();
}
public String getTitle()
{
return title;
}
public Resource getResource()
{
return resource;
}
public void setTitle(String title)
{
this.title = title;
}
public void setResource(Resource resource)
{
this.resource = resource;
}
}
}
Here is read the content in webView
public class ContentViewActivity extends Activity {
WebView webView;
ImageView imgButtonBack;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.content);
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
String displayString = getIntent().getExtras().getString("display");
if(displayString != null)
webView.loadData(displayString, "text/html", "utf-8");
imgButtonBack = (ImageView)findViewById(R.id.imagBackButton);
imgButtonBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(ContentViewActivity.this, EpubReaderActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
overridePendingTransition(R.anim.slide_left,R.anim.slide_right);
}
});
}
}
I want get an image on the next Activity when i click on image of the book page from webview .And null is print on LogCat.Can someone help me how to do this.
Thanks to appreciate.

Custom adapter never empty

I've custom adapter that populates custom listview with data fetched from server. What I want is check if adapter is empty and append data to listview if it is empty else fill the listview with data and notifyDataSetChanged. I'm implementing OnScrollListener to load more data from server. But adapter never is empty and always notifyDataSetChanged is called.
My List Activity
public class ListResultActivity extends Activity implements OnScrollListener{
private ArrayList<BusinessListData> businesses;
private ListView businessList;
private LayoutInflater layoutInflator;
private BusinessListIconTask imgFetcher;
BusinessListDataAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.businesslist);
this.businessList = (ListView) findViewById(R.id.lvBusinesslist);
this.adapter= new BusinessListDataAdapter(this,
this.imgFetcher, this.layoutInflator, this.businesses);
getData();
businessList.setOnScrollListener(this);
}
#Override
public Object onRetainNonConfigurationInstance() {
Object[] myStuff = new Object[2];
myStuff[0] = this.businesses;
myStuff[1] = this.imgFetcher;
return myStuff;
}
/**
* Bundle to hold refs to row items views.
*
*/
public static class MyViewHolder {
public TextView businessName, businessAddress, phoneNo;
public Button btnProfile;
public ImageView icon;
public BusinessListData business;
}
public void setBusinesses(ArrayList<BusinessListData> businesses) {
this.imgFetcher = new BusinessListIconTask(this);
this.layoutInflator = LayoutInflater.from(this);
this.businesses = businesses;
if(adapter !=null){
this.adapter.notifyDataSetChanged();
}else{
this.adapter= new BusinessListDataAdapter(this,
this.imgFetcher, this.layoutInflator, this.businesses);
businessList.setAdapter(adapter);
}
}
private void getData() {
// TODO Auto-generated method stub
Intent myIntent = getIntent();
// gets the arguments from previously created intent
String metroTxt = myIntent.getStringExtra("key");
String metroLoc = myIntent.getStringExtra("loc");
String metroId = myIntent.getStringExtra("qt");
BusinessListApiTask spTask = new BusinessListApiTask(
ListResultActivity.this);
try {
spTask.execute(metroTxt, metroLoc, metroId);
} catch (Exception e) {
spTask.cancel(true);
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
if (businessList.getLastVisiblePosition() == totalItemCount - 1) {
getData();
adapter.notifyDataSetChanged();
Log.d("test count", "abc"+totalItemCount);
}
}
}
Class to fetch data from server and set to adapter
public class BusinessListApiTask extends AsyncTask<String, Integer, String> {
private ProgressDialog progDialog;
private Context context;
private ListResultActivity activity;
private static final String debugTag = "sodhpuch";
HashMap<String, String> queryValues;
/**
* Construct a task
*
* #param activity
*/
public BusinessListApiTask(ListResultActivity activity) {
// TODO Auto-generated constructor stub
super();
this.activity = activity;
this.context = this.activity.getApplicationContext();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progDialog = ProgressDialog.show(this.activity, "Search", this.context
.getResources().getString(R.string.looking_for_business), true,
false);
}
#Override
protected String doInBackground(String... params) {
try {
// Log.d(debugTag, "Background:" +
// Thread.currentThread().getName());
String result = BusinessListHelper.downloadFromServer(params);
// try {
//
// updateSQLite(result);
//
// } catch (Exception e) {
// return result;
// }
Log.d("result", result);
return result;
} catch (Exception e) {
return new String();
}
}
#Override
protected void onPostExecute(String result) {
ArrayList<BusinessListData> businessData = new ArrayList<BusinessListData>();
progDialog.dismiss();
try {
JSONObject respObj = new JSONObject(result);
int success = respObj.getInt("success");
Log.d("Success", "abc"+success);
if (success == 1) {
JSONArray tracks = respObj.getJSONArray("idioms");
for (int i = 0; i < tracks.length(); i++) {
JSONObject track = tracks.getJSONObject(i);
String businessName = track.getString("name");
String businessAddress = track.getString("address");
String phone = track.getString("phone");
String id = track.getString("id");
String deals_in = track.getString("deals_in");
businessData.add(new BusinessListData(businessName,
businessAddress, id, phone, deals_in));
}
} else {
Log.d("Success", "first"+success);
// Log.d(debugTag, "Background:" + result);
// DBController controller = new DBController(context);
// businessData = controller.getBusinessList();
return ;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// }
this.activity.setBusinesses(businessData);
}
My Adapter
public class BusinessListDataAdapter extends BaseAdapter implements
OnClickListener {
private static final String debugTag = "BusinessListDataAdapter";
private ListResultActivity activity;
private BusinessListIconTask imgFetcher;
private LayoutInflater layoutInflater;
private ArrayList<BusinessListData> businesses;
BusinessListData business;
public BusinessListDataAdapter(ListResultActivity a,
BusinessListIconTask i, LayoutInflater l,
ArrayList<BusinessListData> data) {
this.activity = a;
this.imgFetcher = i;
this.layoutInflater = l;
this.businesses = data;
}
#Override
public int getCount() {
return this.businesses.size();
}
public void clear()
{
businesses.clear();
notifyDataSetChanged();
}
#Override
public boolean areAllItemsEnabled() {
return true;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int pos) {
return pos;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
MyViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.trackrow, parent,
false);
holder = new MyViewHolder();
holder.businessName = (TextView) convertView
.findViewById(R.id.tvBusinessName);
holder.businessAddress = (TextView) convertView
.findViewById(R.id.tvAddress);
holder.phoneNo = (TextView) convertView.findViewById(R.id.tvPhone);
holder.icon = (ImageView) convertView.findViewById(R.id.album_icon);
holder.btnProfile = (Button) convertView
.findViewById(R.id.btnProfile);
holder.btnProfile.setTag(holder);
convertView.setTag(holder);
} else {
holder = (MyViewHolder) convertView.getTag();
}
convertView.setOnClickListener(this);
business= businesses.get(pos);
holder.business = business;
holder.businessName.setText(business.getName());
holder.businessAddress.setText(business.getAddress());
holder.phoneNo.setText(business.getPhone());
holder.btnProfile.setOnClickListener(this);
// if(track.getImageUrl() != null) {
// holder.icon.setTag(track.getImageUrl());
// Drawable dr = imgFetcher.loadImage(this, holder.icon);
// if(dr != null) {
// holder.icon.setImageDrawable(dr);
// }
// } else {
holder.icon.setImageResource(R.drawable.filler_icon);
// }
return convertView;
}
#Override
public void onClick(View v) {
String deals_in = business.getDeals().toString();
Log.d("name", deals_in);
MyViewHolder holder = (MyViewHolder) v.getTag();
if (v instanceof Button) {
Intent profile = new Intent(activity,
ProfileActivity.class);
profile.putExtra("deals_in", deals_in);
profile.putExtra("phone", holder.business.getPhone());
profile.putExtra("address", holder.business.getAddress());
profile.putExtra("name", holder.business.getName());
this.activity.startActivity(profile);
} else if (v instanceof View) {
Log.d("test","call testing");
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" +holder.business.getPhone()));
this.activity.startActivity(intent);
}
Log.d(debugTag, "OnClick pressed.");
}
}
Try this way,hope this will help you to solve your problem.
public void setBusinesses(ArrayList<BusinessListData> businesses) {
imgFetcher = new BusinessListIconTask(this);
layoutInflator = LayoutInflater.from(this);
if(this.businesses == null || adapter==null){
this.businesses = new ArrayList<BusinessListData>();
adapter= new BusinessListDataAdapter(this,imgFetcher,layoutInflator,this.businesses);
businessList.setAdapter(adapter);
}
this.businesses.addAll(businesses);
adapter.notifyDataSetChanged();
}
You have the adapter object in your setBusinesses Method. You just need to check the size of the adapter too as follows which is solve your problem.
if(adapter !=null && adapter.getCount()>0)
{
this.adapter.notifyDataSetChanged();
}
else
{
this.adapter= new BusinessListDataAdapter(this,
this.imgFetcher, this.layoutInflator, this.businesses);
businessList.setAdapter(adapter);
}
this will check the size of your BusinessListData object in the adapter and this will not initialize the adapter again and again.
Hope this Solves your problem.
Thank You!
Change use of OnScrollListener. Use Asynctask class and onPreExecute() set adapter as null. Load data in doInBackground() method and call custom adapter in onPostExecute(). I hope it 'll work fine.

Repeating values in listview after back press

I have an application it have two activities. When press a button in the main activity, it shows customized listview, then I press hard back button and go to the main page of my application.
Then I again press the same button and go to the listview it shows the repeated values in the listview.
Any one have any sloution please???
CookList = new ArrayList<HashMap<String, String>>();
try {
url = new URI(cookUri);
List<DataModels> list1 = new ArrayList<DataModels>();
CookListServer cookServer = new CookListServer();
StringBuilder responseString = cookServer.CookConnect(url, "hi");
System.out.println("responseString---------"+responseString);
for(int i=0; i< itemId.size(); i++){
HashMap<String, String> Cook = new HashMap<String, String>();
Cook.put("ItemId", itemId.get(i));
System.out.println("itemId--------"+itemId.get(i));
Cook.put("ItemName", itemName.get(i));
Cook.put("ItemQty", itemQty.get(i));
CookList.add(Cook);
list1.add(get(i));
}
adapter = new MySimpleArrayAdapter(context, CookList, R.layout.cooklist_item, list1);
setListAdapter(adapter);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private DataModels get(int s) {
return new DataModels(s);
}
#Override
public void onResume() {
super.onResume();
adapter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
// Adapter to list the Albums
public class MySimpleArrayAdapter extends ArrayAdapter<HashMap<String, String>> implements SectionIndexer {
private final Context context;
private final ArrayList<HashMap<String, String>> values;
List<DataModels> modellist;
public MySimpleArrayAdapter(Context context, ArrayList<HashMap<String, String>> values, int layout, List<DataModels> modellist) {
super(context, R.layout.cooklist_item, values);
this.context = context;
this.values = values;
this.modellist = modellist;
}
private final class ViewHolder {
public TextView Nametext;
public TextView Qntytext;
public Button prepareButton;
}
private LayoutInflater mLayoutInflater = null;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
if (mLayoutInflater == null) {
mLayoutInflater = LayoutInflater.from(context);
}
convertView = mLayoutInflater.inflate(R.layout.cooklist_item, null);
viewHolder = new ViewHolder();
viewHolder.Nametext = (TextView) convertView.findViewById(R.id.label);
viewHolder.Qntytext = (TextView) convertView.findViewById(R.id.textView1);
viewHolder.prepareButton = (Button) convertView.findViewById(R.id.prepareButton1);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
((ViewHolder) convertView.getTag()).prepareButton.setTag(modellist.get(position));
}
final HashMap<String, String> cooklist = values.get(position);
final ViewHolder holder = (ViewHolder) convertView.getTag();
final String ItemId = cooklist.get("ItemId");
final String ItemName = cooklist.get("ItemName");
final String ItemQty = cooklist.get("ItemQty");
System.out.println("ItemId---------"+ItemId);
System.out.println("ItemName---------"+ItemName);
System.out.println("ItemQty---------"+ItemQty);
holder.Nametext.setText(ItemName);
holder.Qntytext.setText(ItemQty);
registerForContextMenu(convertView);
holder.prepareButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DataModels element = (DataModels) viewHolder.prepareButton.getTag();
holder.prepareButton.setEnabled(false);
}
});
return convertView;
}
#Override
public int getPositionForSection(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getSectionForPosition(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object[] getSections() {
// TODO Auto-generated method stub
return null;
}
}
Thanks...
I got a solution
#Override
protected void onDestroy() {
itemId.clear();
itemName.clear();
itemQty.clear();
super.onDestroy();
}
Thanks....

Categories

Resources