Scrolldown issue in CustomListView - android

I am developing android application about CustomListView,firstly I am parsing data from web servis then I add this data to ListView but When I pull down to scrollView I got this error:
at android.widget.ListView.makeAndAddView(ListView.java:1792)
at android.widget.ListView.fillDown(ListView.java:676)
at android.widget.ListView.fillGap(ListView.java:640)
at android.widget.AbsListView.trackMotionScroll(AbsListView.java:4911)
at android.widget.AbsListView.scrollIfNeeded(AbsListView.java:2923)
at android.widget.AbsListView.onTouchEvent(AbsListView.java:3234)
at android.view.View.dispatchTouchEvent(View.java:5553)
MainActivity:
public class MainActivity extends Activity implements OnRefreshListener {
ListView list;
String[] web;
Integer[] imageId = { R.drawable.enveloppe, R.drawable.enveloppe,
R.drawable.enveloppe, R.drawable.enveloppe, R.drawable.enveloppe,
R.drawable.enveloppe, R.drawable.enveloppe
};
SwipeRefreshLayout swipeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.list);
web = new String[13];
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
AsyncCallBanner banner = new AsyncCallBanner();
// Call execute
banner.execute();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this,
"You Clicked at " + web[+position], Toast.LENGTH_SHORT)
.show();
}
});
// TODO Auto-generated catch block
// TODO Auto-generated catch block
}
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
swipeLayout.setRefreshing(false);
}
}, 5000);
}
// ////////// for Parsing data
private class AsyncCallBanner extends AsyncTask<Void, Void, String> {
ProgressDialog dialog;
#Override
protected String doInBackground(Void... params) {
Log.i("TAG", "doInBackground");
Connect();
return null;
}
#Override
protected void onPostExecute(String result) {
Log.i("TAG", "onPostExecute");
// txt1.setText(Icerik);
CustomList adapter = new CustomList(MainActivity.this, web, imageId);
list.setAdapter(adapter);
dialog.dismiss();
}
#Override
protected void onPreExecute() {
Log.i("TAG", "onPreExecute");
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Lütfen bekleyiniz");
dialog.setIndeterminate(true);
dialog.show();
}
}
private void Connect() {
// TODO Auto-generated method stub
JSONObject returndata = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://api.androidhive.info/contacts/");
httppost.setHeader("Content-type", "application/json");
JSONObject jsonparameter = new JSONObject();
try {
// jsonparameter.put("AnketID", "3");
httppost.setEntity(new StringEntity(jsonparameter.toString(),
"UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
Log.i("#banner_responseString", "" + responseString);
try {
returndata = new JSONObject(responseString);
JSONArray jsonMainNode = returndata.optJSONArray("contacts");
int lengthJsonArr = jsonMainNode.length();
Log.i("#lengthJson", "" + lengthJsonArr);
int sorusayisi = lengthJsonArr;
for (int i = 0; i < sorusayisi; i++) {
if (i == sorusayisi)
break;
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
try {
web[i] = jsonChildNode.optString("name").toString(); // URL
} catch (Exception e) {
}
}
} catch (JSONException e) {
}
} catch (Exception e) {
}
}
}
Custom Class:
public class CustomList extends ArrayAdapter<String> {
private final Activity context;
private final String[] web;
private final Integer[] imageId;
public CustomList(Activity context, String[] web, Integer[] imageId) {
super(context, R.layout.list_single, web);
this.context = context;
this.web = web;
this.imageId = imageId;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.list_single, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
txtTitle.setText(web[position]);
imageView.setImageResource(imageId[position]);
return rowView;
}
}

please change your getView Function as following and test it and feed me back
#Override
public View getView(int position, View view, ViewGroup parent) {
TextView txtTitle=null;
ImageView imageView=null;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view== null) {
view= mInflater.inflate(R.layout.list_single, null);
txtTitle = (TextView) view.findViewById(R.id.txt);
imageView = (ImageView) view.findViewById(R.id.img);
}
txtTitle.setText(web[position]);
imageView.setImageResource(imageId[position]);
return view;
}

Related

onitemclick does not work in fragment (custom list view)

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();
}
}
});

How to populate partial Data into ListView

Still i am populating all JSON data into ListView, but now i want to populate (records into ListView) based on visibility, when user scrolls I want to show progess bar for 5 seconds and then want to populate more records (those will be visible to user) and so on...
I don't want to populate all data into ListView for the first time !
MainActivity.java:
public class MainActivity extends Activity {
ArrayList<Main> arrayList;
MainAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arrayList = new ArrayList<Main>();
new JSONAsyncTask().execute("....");
ListView listview = (ListView)findViewById(R.id.list);
adapter = new MainAdapter(getApplicationContext(), R.layout.row, arrayList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), arrayList.get(position).getTitle(), Toast.LENGTH_LONG).show();
}
});
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("data");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Main main = new Main();
main.setTitle(object.getString("title"));
Log.v("title:", object.getString("title"));
arrayList.add(main);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
MainAdapter.java:
public class MainAdapter extends BaseAdapter {
ArrayList<Main> arrayList;
LayoutInflater layoutInflater;
int resource;
ViewHolder viewHolder;
public MainAdapter(Context context, int resource, ArrayList<Main> arrayList) {
this.layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.resource = resource;
this.arrayList = arrayList;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrayList.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) {
// convert view = design
View view = convertView;
if (view == null) {
viewHolder = new ViewHolder();
view = layoutInflater.inflate(resource, null);
viewHolder.tvName = (TextView) view.findViewById(R.id.tvName);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.tvName.setText(arrayList.get(position).getTitle());
return view;
}
static class ViewHolder {
public TextView tvName;
}
}
You can try using this library (Android-Infinite-Scroll-Listview)
I've used it before and it's easy to work with.

Update Listview after post new data from dialogfragment

I am trying to update my listview directly after I submit new data from DialogFragment.
But when I call notifyDataSetChanged() it give me an NullPointerException and my app is close.
So this is the scenario what I want
And this is my code
This activity that I use to get data from the server
public class LayoutActivity extends Fragment {
private ListView listview;
private ListItemAdapter theAdapter;
String URL = "http://localhost/api/question/get_newest_except/0/0/15";
ProgressDialog pDialog;
NodeList nodelist;
public LayoutActivity() {
super();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.layout_main, container,false);
DownloadXML a = new DownloadXML(this);
a.execute(URL);
listview = (ListView) rootview.findViewById(R.id.list01);
return rootview;
}
public class DownloadXML extends AsyncTask<String, Void, Void>{
private LayoutActivity aku;
ArrayList<ListItemObject> data;
public DownloadXML(LayoutActivity aku) {
super();
this.aku = aku;
}
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.show();
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
data = new ArrayList<ListItemObject>();
ListItemObject itemData;
try{
for (int temp = 0; temp < nodelist.getLength(); temp++) {
Node nNode = nodelist.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
itemData = new ListItemObject();
itemData.setId(getNode("pb__question__id",eElement));
itemData.setOwner(getNode("pb__question__consumer__id",eElement));
if(!getNode("pb__question__consumer__id",eElement).equalsIgnoreCase("0")){
itemData.setName(getNode("pb__question__consumer__name",eElement));
itemData.setJob(getNode("pb__question__consumer__occupation", eElement));
itemData.setProfilePic(getNode("pb__question__consumer__pp",eElement));
}
itemData.setStatus(getNode("pb__question__title",eElement));
itemData.setExtras(getNode("pb__question__topic__name", eElement));
if(!getNode("att__pict",eElement).isEmpty()){
itemData.setImage(getNode("att__pict", eElement));
}
if(getNode("pb__question__type", eElement).equalsIgnoreCase("1")){
itemData.setOpini(getNode("pb__question__total__opini", eElement));
}else if(getNode("pb__question__type", eElement).equalsIgnoreCase("2") || getNode("pb__question__type", eElement).equalsIgnoreCase("3")){
itemData.setOpini(getNode("pb__question__total__polling", eElement));
}else if(getNode("pb__question__type", eElement).equalsIgnoreCase("4")){
itemData.setOpini(getNode("pb__question__total__rating", eElement));
}
itemData.setTipe(getNode("pb__question__type", eElement));
itemData.setIkuti(getNode("pb__question__total__follow", eElement));
itemData.setSebarkan(getNode("pb__question__total__share", eElement));
data.add(itemData);
}
}
theAdapter = new ListItemAdapter(aku.getActivity(),data);
listview.setAdapter(theAdapter);
}catch(Exception e){
Toast.makeText(getActivity(), "Koneksi dengan server gagal", Toast.LENGTH_SHORT).show();
}
pDialog.dismiss();
}
#Override
protected Void doInBackground(String... Url) {
// TODO Auto-generated method stub
try {
URL url = new URL(Url[0]);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
nodelist = doc.getElementsByTagName("pb__question");
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
}
private static String getNode(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
String result = "";
if(nValue!=null){
result = nValue.getNodeValue();
}
return result;
}
}
and this is the listview adapter, in this adapter I call Dialog from each item
public class ListItemAdapter extends BaseAdapter{
private ArrayList<ListItemObject> itemCards;
private Context mContext;
private FragmentManager mFragmentManager;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public ListItemAdapter(FragmentActivity fa, ArrayList<ListItemObject> d) {
super();
this.mContext = fa;
this.itemCards= d;
mFragmentManager = fa.getSupportFragmentManager();
}
#Override
public int getCount() {
return itemCards.size();
}
#Override
public Object getItem(int pos) {
return itemCards.get(pos);
}
#Override
public long getItemId(int pos) {
return pos;
}
#Override
public View getView(final int position, View convertview, ViewGroup parent) {
// TODO Auto-generated method stub
View row=null;
row = convertview;
row = View.inflate(mContext, R.layout.item_layout, null);
final boolean[] mHighlightedPositions = new boolean[itemCards.size()];
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
LinearLayout containerPP = (LinearLayout) row.findViewById(R.id.idCon);
NetworkImageViewCircle fotoPP = (NetworkImageViewCircle) row.findViewById(R.id.pp);
TextView nama = (TextView) row.findViewById(R.id.name);
TextView kerjaan = (TextView) row.findViewById(R.id.jobs);
NetworkImageView gambar = (NetworkImageView) row.findViewById(R.id.feedImage1);
TextView status = (TextView) row.findViewById(R.id.txtStatusMsg);
TextView extra = (TextView) row.findViewById(R.id.txtUrl);
TextView opinion = (TextView) row.findViewById(R.id.opini);
TextView follow = (TextView) row.findViewById(R.id.ikuti);
TextView share = (TextView) row.findViewById(R.id.sebarkan);
Button Opini = (Button) row.findViewById(R.id.Button01);
Button Ikuti = (Button) row.findViewById(R.id.Button02);
Button Sebarkan = (Button) row.findViewById(R.id.Button03);
Ikuti.setTag(position);
Opini.setTag(position);
ListItemObject item = itemCards.get(position);
if(item.getName()==null){
containerPP.setVisibility(View.GONE);
}
if(item.getExtras().equalsIgnoreCase("Pertanyaan Pengguna")){
extra.setVisibility(View.GONE);
}
if(item.getImage()==null){
gambar.setVisibility(View.GONE);
}
if(item.getTipe().equals("4")){
opinion.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.star_icon, 0);
}else if(item.getTipe().equals("2") || item.getTipe().equals("3")){
opinion.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.poll_icon, 0);
}
nama.setText(item.getName());
kerjaan.setText(item.getJob());
fotoPP.setImageUrl(item.getProfilePic(), imageLoader);
status.setText(item.getStatus());
extra.setText(item.getExtras().replaceAll("\n",""));
opinion.setText(item.getOpini());
follow.setText(item.getIkuti());
share.setText(item.getSebarkan());
gambar.setImageUrl(item.getImage(), imageLoader);
if(mHighlightedPositions[position]) {
Ikuti.setBackgroundResource(R.color.ijo);
Ikuti.setTextColor(Color.WHITE);
}else{
Ikuti.setBackgroundResource(R.color.abu2);
Ikuti.setTextColor(Color.BLACK);
}
Opini.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddKomentar(v,position);
}
});
Ikuti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
Sebarkan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return row;
}
public void AddKomentar(View v,int pos){
FragmentActivity activity = (FragmentActivity)(mContext);
FragmentManager fm = activity.getSupportFragmentManager();
ListItemObject item = itemCards.get(pos);
DialogAddOpini dialog = new DialogAddOpini();
Bundle args = new Bundle();
args.putString("question",item.getId());
args.putString("owner",item.getOwner());
dialog.setArguments(args);
dialog.show(fm, "Dialog");
}
}
and this is the DialogFragment
public class DialogAddOpini extends DialogFragment{
ListItemAdapter theAdapter;
String question_id,owner_id;
EditText question_field;
ProgressDialog pDialog;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.addopini, null);
Bundle mArgs = getArguments();
question_id = mArgs.getString("question");
owner_id = mArgs.getString("owner");
builder.setTitle("Tambahkan Opini");
builder.setView(dialogView)
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
question_field = (EditText) dialogView.findViewById(R.id.content);
SendComment send = new SendComment();
send.execute(question_field.getText().toString());
}
});
Dialog dialog = builder.create();
return dialog;
}
private class SendComment extends AsyncTask<String, Void, Void>{
public SendComment() {
super();
}
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Submitting...");
pDialog.setIndeterminate(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... params) {
String content = params[0];
postData(content);
return null;
}
#Override
protected void onPostExecute(Void result) {
theAdapter.notifyDataSetChanged();
pDialog.dismiss();
}
}
public void postData(String content) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/api/opini/add");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("pb_question_id", question_id));
nameValuePairs.add(new BasicNameValuePair("owner_id", owner_id));
nameValuePairs.add(new BasicNameValuePair("opini_text", content));
nameValuePairs.add(new BasicNameValuePair("is_anonym", "1"));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
HttpResponse response = httpclient.execute(httppost);
Log.d("Http Response:", response.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I call notifyDataSetChanged() inside onPostExecute inside DialogFragment, but it give me NullPointerException.
Can anyone help me?
This the log
Thanks
theAdapter is not initialized in class DialogAddOpini, You need to initialized it before using it in OnPostExecute.
I will prefer to use Listener to return the data from DialogFragment and update List in the Adapter only.
public class DialogAddOpini extends DialogFragment {
private Listener mListener;
public void setListener(Listener listener) {
mListener = listener;
}
static interface Listener {
void returnData();
}
Set the listener while creating Dialog :
public void AddKomentar(View v,int pos){
FragmentActivity activity = (FragmentActivity)(mContext);
FragmentManager fm = activity.getSupportFragmentManager();
ListItemObject item = itemCards.get(pos);
DialogAddOpini dialog = new DialogAddOpini();
Bundle args = new Bundle();
args.putString("question",item.getId());
args.putString("owner",item.getOwner());
dialog.setArguments(args);
dialog.setListener(this);
dialog.show(fm, "Dialog");
}
And return the data like :
#Override
protected void onPostExecute(Void result) {
if (mListener != null) {
mListener.returnData();
}
pDialog.dismiss();
}
And override returnData in Adapter and update the list:
public class ListItemAdapter extends BaseAdapter implements DialogAddOpini.Listener {
#Override
public void returnData() {
notifyDataSetChanged();
}
}
Update :
You have to pass the data and set it in the Adapter's Arraylist to reflect the changes.
Track the position while you show the dialog :
Integer selected_position =-1 ;
public void AddKomentar(View v,int pos){
FragmentActivity activity = (FragmentActivity)(mContext);
FragmentManager fm = activity.getSupportFragmentManager();
ListItemObject item = itemCards.get(pos);
DialogAddOpini dialog = new DialogAddOpini();
Bundle args = new Bundle();
args.putString("question",item.getId());
args.putString("owner",item.getOwner());
dialog.setArguments(args);
selected_position = pos;
dialog.setListener(this);
dialog.show(fm, "Dialog");
}
#Override
public void returnData( String counter) {
itemCards.get(selected_position).setOpini(counter);
notifyDataSetChanged();
selected_position=-1;
}
Hope it helps ツ

AsyncTask and JSON - Android

I'm passing id form FirstFragment to SecondFragment. I need that I'd to send POST request to web service to retrieve JSON, which I need to create content of SecondFragment. SecondFragment is ListView with custom layout. I'm adding that layout with my custom adapter class (MyAdapter). For JSON I also have AsyncTask class (GetCategoryTas) The problem is that the SecondFragment is created before service give me result back. So content is always blank. How can I fix this.
FirstFragment:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Bundle bundle = new Bundle();
bundle.putString("id", menuList.get(position).getAlias());
categoryPage = new FragmentCategoryPage();
categoryPage.setArguments(bundle);
transaction = manager.beginTransaction();
transaction.replace(R.id.mainContainer, categoryPage, "CategoryPage");
transaction.addToBackStack("CategoryPage");
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.commit();
}
SecondFragment:
public class FragmentCategoryPage extends Fragment implements OnItemClickListener {
private ListView lvCategory;
private List<NameValuePair> pair;
private ArrayList<ItemCategory> itemCatList = new ArrayList<ItemCategory>();
private ItemCategory itemCat;
private MyAdapter myAdapter;
private Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_category, container, false);
context = getActivity();
String id = getArguments().getString("id");
pair = new ArrayList<NameValuePair>();
pair.add(new BasicNameValuePair("category", id));
new GetCategoryTask().execute();
lvCategory = (ListView) view.findViewById(R.id.lvCategory);
myAdapter = new MyAdapter();
lvCategory.setAdapter(myAdapter);
lvCategory.setOnItemClickListener(this);
return view;
}
// Creating own adapter for categories
class MyAdapter extends BaseAdapter {
#Override
public View getView(final int pos, View convertView, ViewGroup parent) {
View row = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.item_layout_category, parent, false);
} else {
row = convertView;
}
TextView tvCatTitle = (TextView) row.findViewById(R.id.tvCategoryTitle);
TextView tvCatDate = (TextView) row.findViewById(R.id.tvCategoryDate);
ImageView ivCatImage = (ImageView) row.findViewById(R.id.ivCategoryImage);
return row;
}
#Override
public int getCount() { return itemCatList.size(); }
#Override
public Object getItem(int pos) { return null; }
#Override
public long getItemId(int pos) { return 0; }
}
public class GetCategoryTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(Variables.URL_CATEGORY);
httpPost.setEntity(new UrlEncodedFormEntity(pair));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
String data = EntityUtils.toString(httpEntity);
int status = httpResponse.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_OK) {
JSONArray jArray = new JSONArray(data);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jRealObject = jArray.getJSONObject(i);
itemCat = new ItemCategory();
itemCat.setId(jRealObject.get("id").toString());
itemCat.setTitle(jRealObject.get("title").toString());
itemCat.setImage_name(jRealObject.get("image_name").toString());
itemCatList.add(itemCat);
}
return true;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if(result == false) {
Toast.makeText(context, Variables.ERROR_MESSAGE, Toast.LENGTH_SHORT).show();
}
}
}
}
How can I fix this problem?
You should refresh your adapter in onPostExecute() by calling;
myAdapter.notifyDataSetChanged();
I dont see anywhere in your code that you have connected your listview with the itemCatList. And you should do anything you wanna do with your listview in onPostExecute, not in onCreate, so you could be sure that the list exists in that point as AsyncTask runs on its own thread
in onPostExecute
lv = (ListView) findViewById(R.id.your_list_view_id);
List<String> your_array_list = new ArrayList<String>();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
your_array_list );
lv.setAdapter(arrayAdapter);

ListView shows wrong placement of images taken from URL

My listview doesn't show exact placement of images on its individual custom adapters. I am trying to load the images using AsyncTask. Sometimes the images duplicates and I don't have any idea why. Here is my ArrayAdapter code:
public class NewsPromoAdapter extends ArrayAdapter<NewsPromosDTO> {
private final Context context;
List<NewsPromosDTO> npList;
LayoutInflater inflater;
Bitmap src;
public NewsPromoAdapter(Context context, List<NewsPromosDTO> npList) {
super(context, R.layout.news_and_promos, npList);
this.context = context;
this.npList = npList;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public static class ViewHolder {
TextView nameText;
TextView date1Text;
ImageView imageView;
ProgressBar prg;
LoadImage loadImg;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.news_and_promos, parent,
false);
holder = new ViewHolder();
holder.nameText = (TextView) convertView
.findViewById(R.id.newspromo_name);
holder.date1Text = (TextView) convertView
.findViewById(R.id.newspromo_date);
holder.imageView = (ImageView) convertView
.findViewById(R.id.newspromo_imageView);
holder.prg = (ProgressBar) convertView
.findViewById(R.id.progressBar1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
holder.loadImg.cancel(true);
}
if (!(npList.get(position).getName().equals(""))) {
holder.nameText.setVisibility(View.VISIBLE);
holder.nameText.setText(npList.get(position).getName());
} else {
holder.nameText.setVisibility(View.GONE);
}
if (!(npList.get(position).getDate().equals(""))) {
holder.date1Text.setVisibility(View.VISIBLE);
holder.date1Text.setText(npList.get(position).getDate());
} else {
holder.date1Text.setVisibility(View.GONE);
}
if (!(npList.get(position).getImageURL().equals(""))) {
holder.imageView.setVisibility(View.VISIBLE);
holder.loadImg = new LoadImage(holder.imageView, npList.get(
position).getImageURL(), holder);
holder.loadImg.execute();
} else {
holder.imageView.setVisibility(View.GONE);
holder.prg.setVisibility(View.GONE);
}
return convertView;
}
class LoadImage extends AsyncTask<Object, Void, Bitmap> {
ViewHolder viewH;
private ImageView imv;
private String url;
public LoadImage(ImageView imv, String imageURL, ViewHolder viewH) {
this.imv = imv;
this.url = imageURL;
this.viewH = viewH;
}
#Override
protected Bitmap doInBackground(Object... params) {
BitmapFromURL bmpURL = new BitmapFromURL();
src = bmpURL.getBitmapFromURL(url);
return src;
}
#Override
protected void onPostExecute(Bitmap result) {
// imv.setImageBitmap(result);
// viewH.prg.setVisibility(View.GONE);
viewH.prg.setVisibility(View.GONE);
imv.setImageBitmap(result);
}
}
}
Here is the Activity that handles the ADAPTER. I am implementing the Endless listview approach that some big sites uses. Like Facebook, Twitter, etc..New Items loaded into the listview when scrolling into the bottom. I am not sure if I did it well.
public class ListNewsPromoActivity extends Activity {
List<NewsPromosDTO> npList;
String url, user_email;
Bundle extras;
int user_points;
List<Integer> npIDs;
private ProgressDialog progressDialog;
BitmapFromURL bmpURL;
JSONArray users = null;
String TAG_ID = "id";
String TAG_NAME = "name";
String TAG_PHOTO = "photo";
String TAG_DATE = "date";
String TAG_DESC = "description";
ListView list;
NewsPromoAdapter newsAdapter;
boolean loadingMore = false;
private Runnable returnRes;
int itemsPerPage = 3;
int currentIndex = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.news_promo_listview);
list = (ListView) findViewById(R.id.mainView);
extras = getIntent().getExtras();
if (extras != null) {
user_points = extras.getInt("user_points");
user_email = extras.getString("user_email");
}
url = getString(R.string.app_url_news_promos);
npIDs = new ArrayList<Integer>();
npList = new ArrayList<NewsPromosDTO>();
View footerView = ((LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.footer, null, false);
newsAdapter = new NewsPromoAdapter(ListNewsPromoActivity.this, npList);
list.addFooterView(footerView);
list.setAdapter(newsAdapter);
list.setOnScrollListener(new OnScrollListener() {
// useless here, skip!
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// what is the bottom item that is visible
int lastInScreen = firstVisibleItem + visibleItemCount;
// is the bottom item visible & not loading more already ? Load
if ((lastInScreen == totalItemCount) && !(loadingMore)) {
Thread thread = new Thread(null, getRunnable());
thread.start();
}
}
});
// Runnable to load the items
// Since we cant update our UI from a thread this Runnable takes care of
// that!
returnRes = new Runnable() {
#Override
public void run() {
// Loop thru the new items and add them to the adapter
for (NewsPromosDTO np : npList) {
System.out.println(np.getName() + " andito ako!!");
newsAdapter.add(np);
}
newsAdapter.notifyDataSetChanged();
// Done loading more.
loadingMore = false;
}
};
}
protected class loadNewsPromo extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(Void... params) {
// Creating JSON Parser instance
loadingMore = true;
JSONParser jParser = new JSONParser();
JSONObject json;
if (jParser.checkServer(url)) {
try {
// Getting Array of UserNews
json = jParser.getJSONFromUrl(url);
users = json.getJSONArray(user_email);
// looping through All UserNews
for (int i = currentIndex; i < itemsPerPage; i++) {
if (itemsPerPage == i) {
// currentIndex--;
break;
} else {
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
NewsPromosDTO npDTO = new NewsPromosDTO();
npDTO.setImageURL(c.getString(TAG_PHOTO));
npDTO.setId(c.getInt(TAG_ID));
npDTO.setName(c.getString(TAG_NAME));
npDTO.setDate(c.getString(TAG_DATE));
npDTO.setDescription(c.getString(TAG_DESC));
npList.add(npDTO);
currentIndex++;
}
}
} catch (JSONException e) {
e.printStackTrace();
return null;
} finally {
}
}
}
return null;
}
#Override
protected void onPostExecute(String result) { //
// progressDialog.dismiss();
loadingMore = false;
list();
}
}
public void list() {
// add the footer before adding the adapter, else the footer will not
// load!
View footerView = ((LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.footer, null, false);
newsAdapter = new NewsPromoAdapter(ListNewsPromoActivity.this, npList);
list.addFooterView(footerView);
list.setAdapter(newsAdapter);
}
public Runnable getRunnable() {
Runnable loadMoreListItems = new Runnable() {
#Override
public void run() {
// Set flag so we cant load new items 2 at the same time
loadingMore = true;
// Reset the array that holds the new items
// Simulate a delay, delete this on a production environment!
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
// Get 15 new listitems
JSONParser jParser = new JSONParser();
JSONObject json;
npList = new ArrayList<NewsPromosDTO>();
if (jParser.checkServer(url)) {
try {
// Getting Array of Contacts
json = jParser.getJSONFromUrl(url);
users = json.getJSONArray(user_email);
// looping through All Contacts
// if (itemsPerPage > users.length() - currentIndex) {
// itemsPerPage = users.length();
// }
npList = new ArrayList<NewsPromosDTO>();
System.out.println(users.length() + " Laman ng users");
int counter = 0;
for (int i = currentIndex; i < users.length(); i++) {
if (itemsPerPage == counter) {
break;
} else {
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
NewsPromosDTO npDTO = new NewsPromosDTO();
npDTO.setImageURL(c.getString(TAG_PHOTO));
npDTO.setId(c.getInt(TAG_ID));
npDTO.setName(c.getString(TAG_NAME));
npDTO.setDate(c.getString(TAG_DATE));
npDTO.setDescription(c.getString(TAG_DESC));
npList.add(npDTO);
currentIndex++;
}
counter++;
}
} catch (JSONException e) {
e.printStackTrace();
} finally {
}
}
// Done! now continue on the UI thread
runOnUiThread(returnRes);
}
};
return loadMoreListItems;
}
}

Categories

Resources