I have created an activity to get and show data to a custom list view.
Now I have changed this to fragment but onItemclick does not work.
SiteNews.java
public class SiteNews extends Fragment implements OnTabChangeListener,
OnPageChangeListener {
private TabHost tabHost;
private ViewPager viewPager;
private FragmentPagerNewsAdapter fragmentPagerNewsAdapter;
int i = 0;
View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.tabs_news_layout, container, false);
// put tabhost here:
// ***************************** part 1
// ***************************************************
i++;
// init tabhost
this.initializeTabHost(savedInstanceState);
// init ViewPager
this.initializeViewPager();
// ***************************** part 1
// ***************************************************
return v;
}
private void initializeViewPager() {
List<Fragment> fragmentsnews = new Vector<Fragment>();
fragmentsnews.add(new FragmentAllNews());
fragmentsnews.add(new FragmentUnreadNews());
this.fragmentPagerNewsAdapter = new FragmentPagerNewsAdapter(
getChildFragmentManager(), fragmentsnews);
this.viewPager = (ViewPager) v.findViewById(R.id.viewPagernews);
this.viewPager.setAdapter(this.fragmentPagerNewsAdapter);
this.viewPager.setOnPageChangeListener(this);
}
// fake content for tabhost
class FakeContent implements TabContentFactory {
private final Context mContext;
public FakeContent(Context context) {
mContext = context;
}
#Override
public View createTabContent(String tag) {
View v = new View(mContext);
v.setMinimumHeight(0);
v.setMinimumWidth(0);
return v;
}
}
private void initializeTabHost(Bundle args) {
tabHost = (TabHost) v.findViewById(android.R.id.tabhost);
tabHost.setup();
for (int i = 1; i <= 2; i++) {
TabHost.TabSpec tabSpec;
tabSpec = tabHost.newTabSpec("Tab " + i);
tabSpec.setIndicator("Tab " + i);
tabSpec.setContent(new FakeContent(getActivity()));
tabHost.addTab(tabSpec);
}
tabHost.setOnTabChangedListener(this);
}
#Override
public void onTabChanged(String tabId) {
int pos = this.tabHost.getCurrentTab();
this.viewPager.setCurrentItem(pos);
HorizontalScrollView hScrollView = (HorizontalScrollView) v
.findViewById(R.id.hScrollViewnews);
View tabView = tabHost.getCurrentTabView();
int scrollPos = tabView.getLeft()
- (hScrollView.getWidth() - tabView.getWidth()) / 2;
hScrollView.smoothScrollTo(scrollPos, 0);
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
this.tabHost.setCurrentTab(position);
}
}
FragmentAllnews.java
public class FragmentAllNews extends Fragment implements View.OnClickListener {
ViewGroup v;
ListView list;
CustomAdapterAllNews adapter;
JSONObject json_data;
JSONArray jArray;
NewsGetData newsGetData;
ArrayList<String> id, title_news, text_news, cat_id, status;
String data, url, msg, check, readnumber, ACTION_SCAN, contents;
ArrayList<News> newsha;
News n;
int sizearray;
Resources res;
ArrayList<News> items;
News ne;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = (ViewGroup) inflater.inflate(R.layout.tabfragmentallnews,
container, false);
list = (ListView) v.findViewById(R.id.listallnews);
res = getResources();
createarray();
/* items = new ArrayList<News>();
for (int k = 0; k < 25; k++) {
ne = new News();
ne.setTitle_news("title_news " + String.valueOf(k));
ne.setText_news("text_news " + String.valueOf(k));
ne.setCat_id(k);
ne.setStatus(k);
items.add(ne);
}*/
ReadData task1 = new ReadData();
task1.execute(new String[] { "url address" });
return v;
}
private void createarray() {
id = new ArrayList<String>();
title_news = new ArrayList<String>();
text_news = new ArrayList<String>();
cat_id = new ArrayList<String>();
status = new ArrayList<String>();
id.clear();
title_news.clear();
text_news.clear();
cat_id.clear();
status.clear();
}
private class ReadData extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog = new ProgressDialog(getActivity());
#Override
protected void onPreExecute() {
dialog.setMessage("Reading Data...");
dialog.show();
}
String text = "";
ArrayList<String> list1;
#Override
protected Boolean doInBackground(String... urls) {
url = "php url address";
InputStream is1;
for (String url1 : urls) {
// Read from web to InputStream
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// HttpPost post = new HttpPost(url1);
HttpResponse response = client.execute(post);
is1 = response.getEntity().getContent();
} catch (ClientProtocolException e) {
Toast.makeText(getActivity(), e.toString(),
Toast.LENGTH_LONG).show();
return false;
} catch (IOException e) {
Toast.makeText(getActivity(), e.toString(),
Toast.LENGTH_LONG).show();
return false;
}
// end of Read from web to InputStream
// Convert from InputStream to String Text
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(is1,
"iso-8859-1"), 8);
String line = null;
while ((line = reader.readLine()) != null) {
text += line + "\n";
}
is1.close();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// end of Convert from InputStream to String Text
// Convert from Text to JSON and add to ArrayList list1
list1 = new ArrayList<String>();
try {
JSONArray jArray = new JSONArray(text);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonData = jArray.getJSONObject(i);
list1.add(jsonData.getString("title_news") + " - "
+ jsonData.getString("text_news"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// end of Convert from Text to JSON and add to ArrayList list1
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
if (result == true) {
// add list1 to ArrayAdapter
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(
getActivity(), android.R.layout.simple_list_item_1,
list1);
// set adapter into listStudent
// list.setAdapter(adapter1);
Toast.makeText(getActivity(), text, Toast.LENGTH_LONG).show();
data = text;
newsha = parseJSON3(data);
adddata(newsha);
} else {
Toast.makeText(getActivity(), "Error", Toast.LENGTH_LONG)
.show();
}
dialog.dismiss();
}
}
/*
* #Override public void onItemClick(AdapterView<?> parent, View
* clickedView, int pos, long id) { TextView tv1 = (TextView)clickedView;
* int commaIndex = tv1.getText().toString().indexOf(","); String st_id =
* tv1.getText().toString().substring(0, commaIndex);
*
* Intent in = new Intent(this, EditDataActivity.class);
* in.putExtra("st_id", st_id); startActivity(in);
*
* }
*/
public void onItemClick(int mPosition) {
try {
News tempValues = (News) newsha.get(mPosition);
Toast.makeText(getActivity(), tempValues.getText_news(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
// Toast.makeText(CustomListView,"no", Toast.LENGTH_LONG).show();
}
}
public ArrayList<News> parseJSON3(String result) {
ArrayList<News> userha = new ArrayList<News>();
try {
jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
n = new News();
n.setId(json_data.getInt("id"));
id.add(String.valueOf(json_data.getInt("id")));
n.setTitle_news(json_data.getString("title_news"));
title_news.add(json_data.getString("title_news"));
n.setText_news(json_data.getString("text_news"));
text_news.add(json_data.getString("text_news"));
n.setCat_id(json_data.getInt("cat_id"));
cat_id.add(String.valueOf(json_data.getInt("cat_id")));
n.setStatus(json_data.getInt("status"));
status.add(String.valueOf(json_data.getInt("status")));
userha.add(n);
}
sizearray = text_news.size();
if (sizearray <= 0) {
Toast.makeText(getActivity(), "get data error",
Toast.LENGTH_LONG).show();
} else {
}
} catch (JSONException e) {
// toast(9);
}
return userha;
}
private void adddata(ArrayList<News> newsha2) {
adapter = new CustomAdapterAllNews(getActivity(), newsha2, newsha2, res);
list.setAdapter(adapter);
}
#Override
public void onClick(View v) {
}
}
CustomAdapterAllNews.java
public class CustomAdapterAllNews extends BaseAdapter implements OnClickListener {
/*********** Declare Used Variables *********/
private Activity activitynews;
private ArrayList datanews;
private static LayoutInflater inflaternews=null;
public Resources resnews;
News tempValuesnews=null;
int i=0;
TableLayout tableLayout1news;
private List<News> worldpopulationlistnews = null;
private ArrayList<News> arraylistnews;
/************* CustomAdapter Constructor *****************/
public CustomAdapterAllNews(Activity a, ArrayList d, List<News> worldpopulationlist, Resources resLocal) {
/********** Take passed values **********/
activitynews = a;
datanews=d;
resnews = resLocal;
this.arraylistnews = new ArrayList<News>();
this.worldpopulationlistnews = worldpopulationlist;
this.arraylistnews.addAll(worldpopulationlist);
/*********** Layout inflator to call external xml layout () **********************/
inflaternews = (LayoutInflater)activitynews.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/******** What is the size of Passed Arraylist Size ************/
public int getCount() {
if(datanews.size()<=0)
return 1;
return datanews.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder to contain inflated xml file elements ***********/
public static class ViewHolder{
public TextView text;
public TextView text1;
public ImageView image;
}
/*********** Depends upon data size called for each row , Create each ListView row ***********/
#SuppressLint("InflateParams")
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
/********** Inflate tabitem.xml file for each row ( Defined below ) ************/
vi = inflaternews.inflate(R.layout.list_news, null);
/******** View Holder Object to contain tabitem.xml file elements ************/
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.textlistnews);
holder.text1=(TextView)vi.findViewById(R.id.text1listnews);
holder.image=(ImageView)vi.findViewById(R.id.imagelistnews);
/************ Set holder with LayoutInflater ************/
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
if(datanews.size()<=0)
{
holder.text.setText("No Data");
holder.text1.setText("نتیجه یافت نشد");
holder.image.setImageResource(resnews.getIdentifier("com.iranvizhe:drawable/"+"image00",null,null));
}
else
{
/***** Get each Model object from Arraylist ********/
tempValuesnews=null;
tempValuesnews = (News) datanews.get(position);
/************ Set Model values in Holder elements ***********/
holder.text.setText(tempValuesnews.getTitle_news());
holder.text1.setText(tempValuesnews.getText_news());
holder.image.setImageResource(resnews.getIdentifier("com.iranvizhe:drawable/image0",null,null));
/******** Set Item Click Listner for LayoutInflater for each row ***********/
vi.setOnClickListener(new OnItemClickListener(position));
}
return vi;
}
#Override
public void onClick(View v) {
Log.v("CustomAdapter", "=====Row button clicked");
}
/********* Called when Item click in ListView ************/
private class OnItemClickListener implements OnClickListener{
private int mPosition;
OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View arg0) {
// FragmentAllNews sct = (FragmentAllNews)activitynews;
// Tab1Fragment sct = (Tab1Fragment)activity;
// sct.onItemClick(mPosition);
}
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlistnews.clear();
if (charText.length() == 0) {
worldpopulationlistnews.addAll(arraylistnews);
}
else
{
for (News wp : arraylistnews)
{
if (wp.getTitle_news().toLowerCase(Locale.getDefault()).contains(charText)
| wp.getText_news().toLowerCase(Locale.getDefault()).contains(charText))
{
worldpopulationlistnews.add(wp);
}
}
}
notifyDataSetChanged();
}
}
When I put this code:
// FragmentAllNews sct = (FragmentAllNews)activitynews;
// Tab1Fragment sct = (Tab1Fragment)activity;
// sct.onItemClick(mPosition);
on click does not work for me and I need on click in list view.
Don't use v.setOnclicklistener() in adapter, better use in fragment only as below
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
try {
News tempValues = (News) newsha.get(mPosition);
Toast.makeText(getActivity(), tempValues.getText_news(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
// Toast.makeText(CustomListView,"no", Toast.LENGTH_LONG).show();
}
}
});
Related
android ListActivity how to make Custom Adapter getter setter using ,call json Volley library populate data ListActivity ? could not populate data with Json how to implement ,Please Help me
my code
ItemFragment Class
public class ItemFragment extends ListActivity {
RequestParse requestParse;
MySharedPreferences prefs;
String UsrId;
Context context;
ArrayList<BizForumArticleInfo> list = new ArrayList<>();
private List<BizForumArticleInfo> CountryCodeNumber = new ArrayList<>();
MobileArrayAdapter adapter;
LinearLayoutManager mLayoutManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_android_example);
requestParse = new RequestParse();
prefs = MySharedPreferences.getInstance(this, SESSION);
UsrId = prefs.getString("UsrID", "");
context = getApplicationContext();
setListAdapter(new MobileArrayAdapter(this,0, list));
getJson(60);
}
public void getJson(final int limit){
requestParse.postJson(ConfigApi.postArticleBiz(), new RequestParse.VolleyCallBackPost() {
#Override
public void onSuccess(String result) {
list = parseResponse(result);
}
#Override
public void onRequestError(String errorMessage) {
}
#Override
public Map OnParam(Map<String, String> params) {
params.put("sessionid", UsrId);
params.put("offset", "0");
params.put("limit", String.valueOf(limit));
params.put("viewtype", "all");
params.put("access_token","e3774d357aa7d4bd14e9763b5459ee9cf7ebe36161c142551836ee510d98814a:b349b76b334a94b2");
return params;
}
});
}
public static ArrayList<BizForumArticleInfo> parseResponse(String response) {
ArrayList<BizForumArticleInfo> bizList = new ArrayList<>();
try {
JSONObject json = new JSONObject(response);
JSONArray data = json.getJSONArray(DATA);
for (int i = 0; i < data.length(); i++) {
BizForumArticleInfo ls = new BizForumArticleInfo();
JSONObject item = data.getJSONObject(i);
String ArticleTitle = item.getString("ArticleTitle");
String Article = item.getString("Article");
M.i("===================",ArticleTitle);//working
ls.setArticleTitle(ArticleTitle);
ls.setArticleArticle(Article);
bizList.add(ls);
}
} catch (JSONException e) {
e.printStackTrace();
}
return bizList;
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String selectedValue = (String) getListAdapter().getItem(position);
Toast.makeText(this, selectedValue, Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.putExtra("selectedValue", selectedValue);
setResult(RESULT_OK, intent);
finish();
//startActivity(new Intent(v.getContext(), MainActivity.class));
}
}
Adapter Class
public class MobileArrayAdapter extends ArrayAdapter<BizForumArticleInfo> {
private Activity activity;
private ArrayList<BizForumArticleInfo> lPerson;
private static LayoutInflater inflater = null;
public MobileArrayAdapter (Activity activity, int textViewResourceId,ArrayList<BizForumArticleInfo> _lPerson) {
super(activity, textViewResourceId, _lPerson);
try {
this.activity = activity;
this.lPerson = _lPerson;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
} catch (Exception e) {
}
}
public int getCount() {
return lPerson.size();
}
public BizForumArticleInfo getItem(BizForumArticleInfo position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder {
public TextView display_name;
public TextView display_number;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
try {
if (convertView == null) {
vi = inflater.inflate(R.layout.list_mobile, null);
holder = new ViewHolder();
holder.display_name = (TextView) vi.findViewById(R.id.label);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
holder.display_name.setText(lPerson.get(position).getArticleTitle());
} catch (Exception e) {
}
return vi;
}
}
This ListView class where i bring different element from my server with help of php and JSON calls to my listview. The problem is i would like to send the ID of element to another view when i click of specific element on listview. and in another View i would like to publish the detail information about the element that i clicked. Any wan have idea about that?
public class Forestillinger extends AppCompatActivity {
ListView dagensaktivitet;
TextView txt;
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
JSONParser jsonParser = new JSONParser();
JSONObject hc = null;
JSONArray fstilling;
public String hk = "";
int success;
String msg;
final Context c = this;
StableArrayAdapter adb;
private static final String url_Forestillinger = "http://barnestasjonen.no/test/db_get_forestillinger.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forestillinger);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
dagensaktivitet = (ListView) findViewById(R.id.forestillinglist);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems) {
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView txt = (TextView) view.findViewById(android.R.id.text1);
txt.setTextColor(Color.WHITE);
return view;
}
};
dagensaktivitet.setAdapter(adapter);
Log.d("i oncreate", adapter.toString());
//if(!fromLocalDB())
try {
new getShows().execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
//JSONObject tickets = task.getJSon();
adapter.notifyDataSetChanged();
dagensaktivitet.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getApplicationContext(), Forestilling.class);
i.putExtra("selectedItem", listItems.get(position));
startActivity(i);
}
});
}
public void fromExtDB() throws JSONException {
fstilling = hc.getJSONArray("forestillinger");
for (int i = 0; i < fstilling.length(); i++) {
listItems.add(fstilling.getJSONObject(i).getString("tittel")+fstilling.getJSONObject(i).getString("id"));
}
}
#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_forestillinger, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void forestillingResult(){
new AlertDialog.Builder(Forestillinger.this)
.setTitle("OBS!!!")
.setMessage(msg)
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
hk = "";
finish();
}
})
.show();
}
private class StableArrayAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
List<Integer> trialId;
public StableArrayAdapter(Context context, int textViewResourceId, List<String> objects, List<Integer> objectId) {
super(context, textViewResourceId, objects);
for (int i = 0; i < objects.size(); i++)
mIdMap.put(objects.get(i), i);
trialId = objectId;
}
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
public int getActualId(int position)
{
return trialId.get(position);
}
}
class getShows extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args) {
Log.d("TEST", "jeg er her");
List<NameValuePair> params = new ArrayList<NameValuePair>();
//params.add(new BasicNameValuePair("id", "adam#gmail.com"));
//params.add(new BasicNameValuePair("type", "android"));
JSONObject json = jsonParser.makeHttpRequest(url_Forestillinger, "POST", params);
try {
if (json != null) {
success = Integer.parseInt(json.getString("success"));
msg = json.toString();
System.out.println("Vi er her:" + msg + " " + success);
}
if (success == 1) {
hc = json;
System.out.println("jojo"+json.toString());
}
else
{
msg=json.getString("message");
System.out.println(msg);
msg= Html.fromHtml(msg).toString();
hk = msg;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
//run code
try {
Log.d("TAG23", "vi er in onpostExecute");
if(success == 1) {
fromExtDB();
}else{
forestillingResult();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
and here is the second view.
public class Forestilling extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forestilling);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/*Bundle extras = getIntent().getExtras();
Log.d("TAG:", "" + extras.getInt("TryThis"));*/
Bundle extras = getIntent().getExtras();
String s = extras.getString("selectedItem");
Log.d("TAG:", "" + s);
TextView tit = (TextView)findViewById(R.id.tittel);
TextView dato = (TextView)findViewById(R.id.dato);
}
#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_forestilling, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I'm not allowed to flag at this moment, but this might be a duplicate of how can i use the number from textfield of each row in listview and make a call on this number?
Anyway, my answer given there might solve your problem:
Here is what I do:
private class MyAdapter extends BaseAdapter {
private ListView listView;
...
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
this.listView = (ListView) viewGroup;
and then in each View.OnClickListener I can get the position of the clicked item by
#Override
public void onClick(View view) {
...
MyAdapter.this.listView.getPositionForView((View) view.getParent()));
I am using listview to populate data coming from the server. This listview will show that data in a fragmentTab. Now the data is parsing fine and logcat is also showing the data. But the data is not being populated by listview. I tried to see the error through debugging but there is no problem. Even the Holder in adapter catches the data but it's not displayed. I don't know what the problem is. I tried the following questions but didn't got the answer.
Android - ListView in Fragment does not showing up
Android - ListView in Fragment does not show
ListView in Fragment Not Displayed
Below is my fragment and the adapter.
Tastemaker Fragment:
public class TasteMakersFragment extends Fragment
{
CommonClass commonTasteMakers;
String tasteMaker_url = CommonClass.url+ URLConstants.Host.URL_ALL_SUGGESTED_TASTEMAKERS;
String user_token = "8aa0dcd5aaf54c8a5aaef1aa242f342f";
ListView suggested_list;
List<SuggestedUserModel> suggestedUsers_list = new ArrayList<>();
SuggestedUsersAdapter mAdapter;
int selectedPosition = 0;
public TasteMakersFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.from(getActivity()).inflate(R.layout.suggested_users_tastemakers, null);
commonTasteMakers = new CommonClass(getActivity().getApplicationContext());
suggested_list = (ListView)v.findViewById(R.id.lst_suggestedUsers);
new GetSuggestedUsers().execute(tasteMaker_url);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
private class GetSuggestedUsers extends AsyncTask< String, Void, Void>
{
private ProgressDialog Dialog = new ProgressDialog(getActivity());
protected void onPreExecute() {
if (suggestedUsers_list.isEmpty())
{
Dialog = ProgressDialog.show(getActivity(),"Please be patient!","Fetching for first time...");
}
}
#Override
protected Void doInBackground(String... params)
{
if (suggestedUsers_list.isEmpty())
{
getSuggestedUsers();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
else{
Log.d("---- Already Fetched --", "---- Already Fetched ----");
return null;
}
}
protected void onPostExecute(Void unused)
{
Dialog.dismiss();
mAdapter = new SuggestedUsersAdapter(getActivity(), suggestedUsers_list);
suggested_list.setAdapter(mAdapter);
suggested_list.setSelection(selectedPosition);
mAdapter.notifyDataSetChanged();
//startMainActivity();
}
}
private List<SuggestedUserModel> getSuggestedUsers()
{
StringRequest postRequest = new StringRequest(Request.Method.POST, tasteMaker_url, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
try {
//JSONObject jsonResponse = new JSONObject(response).getJSONObject("form");
JSONObject jsonResponse = new JSONObject(response);
if (jsonResponse.has("data"))
{
JSONObject data = jsonResponse.getJSONObject("data");
String code = jsonResponse.getString("code");
if(code.equals("200"))
{
if(data.has("tasteMakers"))
{
JSONArray tastemakers = data.getJSONArray("tasteMakers");
for (int i =0; i<tastemakers.length(); i++)
{
JSONObject jsnObj = tastemakers.getJSONObject(i);
String id = jsnObj.getString("userId");
String name = jsnObj.getString("name");
String profilePic = jsnObj.getString("imgUrl");
Boolean isFollowed = jsnObj.getBoolean("isFollowed");
suggestedUsers_list.add(new SuggestedUserModel(id,
name,
profilePic,
isFollowed));
Log.d("Names are ----", "size is=" + name +" and their id are: "+id);
}
// Log.d("Adapter list ----", "size is=" + suggestedUsers_list.size());
}
}
else {
Log.d("Error0 Error Error", "response------:" + jsonResponse);
}
}
// Log.d("response222---------","response22222------:"+jsonResponse);
} catch (JSONException e) {
Log.d("-----Stop------", "!!!");
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<>();
// the POST parameters:
params.put("sessionToken", user_token);
return params;
} };
postRequest.setRetryPolicy(new DefaultRetryPolicy(20000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(getActivity().getApplicationContext()).add(postRequest);
return suggestedUsers_list;
}
}
Adapter Class:
public class SuggestedUsersAdapter extends BaseAdapter {
Context context;
int count = 1;
private List<SuggestedUserModel> allUsers;
public SuggestedUsersAdapter(FragmentActivity activity, List<SuggestedUserModel> suggestUserModel)
{
Log.d("Custom Adapter called", "" + suggestUserModel.size());
context = activity;
allUsers = suggestUserModel;
//FragmentActivity mActivity = activity;
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return allUsers.size();
// return imageId.length;
}
#Override
public Object getItem(int position) {
return allUsers.get(position);
// return position;
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint({"ViewHolder", "InflateParams", "CutPasteId"})
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final mHolder holder;
// int type = getItemViewType(position);
LayoutInflater layoutInflater;
getItemViewType(position);
if (convertView == null)
{
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.suggested_users_tastemaker_cell, null);
holder = new mHolder();
// convertView.setTag(mFeedsListItemViewHolder);
holder.txt_suggestUserName = (TextView) convertView.findViewById(R.id.tv_tasteMakerName);
holder.imgV_userProfile = (ImageView) convertView.findViewById(R.id.imgBtn_tasteMaker_pic);
holder.btnFollow = (Button) convertView.findViewById(R.id.btnFollow_tasteMaker);
holder.btnFollowing = (Button) convertView.findViewById(R.id.btnFollowing);
convertView.setTag(holder);
} else {
holder = (mHolder) convertView.getTag();
}
final SuggestedUserModel suggestUser = allUsers.get(position);
holder.txt_suggestUserName.setText(allUsers.get(position).getSuggested_UserName());
/*if(suggestUser.getSuggested_UserImage().equals(""))
{
Picasso
.with(context)
.load(R.mipmap.ic_launcher)
.transform(new CropSquareTransformationHomePage())
.into(holder.imgV_userProfile);
}
else {
Picasso
.with(context)
.load(suggestUser.getSuggested_UserImage())
.transform(new CropSquareTransformationHomePage())
.into(holder.imgV_userProfile);
}*/
holder.pos = position;
//mFeedsListItemViewHolder.setData(allPersons.get(position));
return convertView;
}
private class mHolder {
TextView txt_suggestUserName;
ImageView imgV_userProfile;
Button btnFollow;
Button btnFollowing;
int pos;
}
}
Note: I already tried declaring listview and assigning adapter in onActivityCreated() method of fragment but no effect.
Any Help will be appreciated.
I am developing an application in which i am getting a large json data from the server. i want to display it in the list view. But i am getting the same value repeated. The no of items shown by the list view is proper. only same data repeated in all the list items.
Here is my code.
public class HistoryActivity extends AppCompatActivity {
private Toolbar toolbar;
String strServerResponse = null;
ProgressDialog nDialog;
ArrayList<String>clicklat;
ArrayList<String>clicklong;
ArrayList<String>dttime;
ArrayList<Pojo> history;
HistoryAdapter myAdapter;
ListView list;
public String date, inTime, outTime, inLat, inLong;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
toolbar = (Toolbar) findViewById(R.id.app_bar);
toolbar.setTitle("History");
clicklat=new ArrayList<String>();
clicklong=new ArrayList<String>();
dttime=new ArrayList<String>();
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
list = (ListView) findViewById(R.id.historyList);
history = new ArrayList<Pojo>();
new NetCheck().execute();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ArrayList<String>clicklat= new ArrayList<String>(history.get(position).getLati());
ArrayList<String>clicklong= new ArrayList<String>(history.get(position).getLongi());
ArrayList<String>dttime= new ArrayList<String>(history.get(position).getDatetime());
Intent i = new Intent(HistoryActivity.this, DetailsActivity.class);
i.putStringArrayListExtra("clicklat", clicklat);
i.putStringArrayListExtra("clicklong", clicklong);
i.putStringArrayListExtra("clickdatetime", dttime);
startActivity(i);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class NetCheck extends AsyncTask<Void, Void, Void> {
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
nDialog.dismiss();
// TODO Auto-generated method stub
myAdapter = new HistoryAdapter(HistoryActivity.this, history);
list.setAdapter(myAdapter);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(
"http://myurl");
httpRequest.setHeader("Content-Type", "application/json");
SharedPreferences mmm = getSharedPreferences(
"MyPref", MODE_PRIVATE);
String logempid = mmm.getString("id", null);
JSONObject json = new JSONObject();
json.put("empid", logempid);
Log.e("JSON Object", json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding("UTF-8");
se.setContentType("application/json");
httpRequest.setEntity(se);
HttpResponse httpRes = httpClient.execute(httpRequest);
java.io.InputStream inputStream = httpRes.getEntity()
.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
strServerResponse = sb.toString();
Log.e("Server Response", "" + strServerResponse.toString());
if (strServerResponse != null) {
try {
JSONArray arr = new JSONArray(strServerResponse);
for (int k = 0; k < arr.length(); k++) {
JSONObject jsonObj1 = arr.getJSONObject(k);
Pojo pojo = new Pojo();
JSONArray subArrayLat = jsonObj1.getJSONArray("lati_long");
List<String> lati= new ArrayList<String>();
List<String> longi= new ArrayList<String>();
List<String> dateandtime= new ArrayList<String>();
for (int i = 0; i < subArrayLat.length(); i++) {
String lat = subArrayLat.getJSONObject(i).getString("Latitude").toString();
String loong = subArrayLat.getJSONObject(i).getString("Longitude").toString();
String datetimee = subArrayLat.getJSONObject(i).getString("date_time").toString();
lati.add(lat);
longi.add(loong);
dateandtime.add(datetimee);
}
pojo.setLati(lati);//adding latitude list
pojo.setLongi(longi); //adding longitude list
pojo.setDatetime(dateandtime);
String dateee = arr.getJSONObject(k).getString("login_date");
String timeeee = arr.getJSONObject(k).getString("login_time");
String timeeee2 = arr.getJSONObject(k).getString("logout_time");
pojo.setDate(dateee);
pojo.setLoginTime(timeeee);
pojo.setLogoutTime(timeeee2);
history.add(pojo);
}
} catch (JSONException e) {
e.printStackTrace();
}
And this is Adapter
public class HistoryAdapter extends BaseAdapter {
private Context activity;
TextView tv_date;
TextView tv_loginTime;
TextView tv_logoutTime;
ArrayList<Pojo> list;
private ArrayList<Pojo> arraylist = null;
public static LayoutInflater inflater;
private Context context;
public HistoryAdapter(Context a, ArrayList<Pojo> history) {
// TODO Auto-generated constructor stub
activity = a;
list = history;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.arraylist = new ArrayList<Pojo>();
this.arraylist.addAll(list);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
if(convertView == null) {
v = inflater.inflate(R.layout.history_item, parent, false);
}
final Pojo pojo = list.get(position);
tv_date = (TextView) v.findViewById(R.id.historyDate);
tv_loginTime = (TextView) v.findViewById(R.id.historyLoginTime);
tv_logoutTime = (TextView) v.findViewById(R.id.historyLogoutTime);
tv_date.setText(pojo.getDate());
tv_loginTime.setText(pojo.getLoginTime());
tv_logoutTime.setText(pojo.getLogoutTime());
return v;
}
}
and setters and getters
public class Pojo {
public static String empid11;
public static String loginTime;
public static String date;
public static String logoutTime;
public static List<String> lat;
public static List<String> datetime;
public static List<String> longi;
public static List<String> inlogin;
public static List<String> inDate;
public List<String> getInTime(){
return this.inlogin;
}
public List<String> getInDate(){
return this.inDate;
}
public void setInDate(List<String> inDate){
this.inDate = inDate;
}
public List<String> getLati(){
return this.lat;
}
public List<String> getLongi(){
return this.longi;
}
public void setLati(List<String> lat){
this.lat = lat;
}
public void setLongi(List<String> longi){
this.longi = longi;
}
public void setId(String empid) {
this.empid11 = empid;
}
public String getId() {
return empid11;
}
public void setLoginTime(String loginTime) {
this.loginTime = loginTime;
}
public String getLoginTime() {
return loginTime;
}
public void setLogoutTime(String logoutTime) {
this.logoutTime = logoutTime;
}
public String getLogoutTime() {
return logoutTime;
}
public void setDate(String date) {
this.date = date;
}
public String getDate() {
return date;
}
public List<String> getDatetime(){
return this.datetime;
}
public void setDatetime(List<String> datetime){
this.datetime = datetime;
}
}
Hello see the modifiy version of your adapter. Let me know if you have any problem with it.
public class HistoryAdapter extends BaseAdapter
{
private Context activity;
TextView tv_date;
TextView tv_loginTime;
TextView tv_logoutTime;
private ArrayList<Pojo> arraylist = null;
public static LayoutInflater inflater;
private Context context;
public HistoryAdapter(Context a) {
activity = a;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.arraylist = new ArrayList<Pojo>();
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void addHistoryData(ArrayList<Pojo> newDataset){
if(arraylist != null){
arraylist.addAll(newDataset);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder mViewHolder = null;
if(convertView == null)
{
mViewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.history_item, parent, false);
mViewHolder.tv_date = (TextView) convertView.findViewById(R.id.historyDate);
mViewHolder.tv_loginTime = (TextView)convertView.findViewById(R.id.historyLoginTime);
mViewHolder.tv_logoutTime = (TextView)convertView.findViewById(R.id.historyLogoutTime);
convertView.setTag(mViewHolder);
}else{
mViewHolder = (ViewHolder) convertView.getTag();
}
final Pojo pojo = list.get(position);
mViewHolder.tv_date.setText(pojo.getDate());
mViewHolder.tv_loginTime.setText(pojo.getLoginTime());
mViewHolder.tv_logoutTime.setText(pojo.getLogoutTime());
return v;
}
public class ViewHolder{
TextView tv_date
TextView tv_loginTime;
TextView tv_logoutTime;
}
}
In next the activity NetCheck class when web service response come change like below :
history.add(pojo);
myAdapter.addHistoryData(history);
myAdapter.notifiyDatasetChanged();
There may be problem you are getting repeated value in array, please check your array first.
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.