I am working on android projects. In my application I am getting the data from php webservice. I added my data to different arraylists and set them to listadapter. But my problem is it is taking very long time to display the data in list. Hence now I want to display first 10 items and want to keep a loadmore button at the bottom of the screen. Once the load more button is clicked the next 10 items need to display. Please can anybody help me in this regard. I would really appreciate for this help.
Thank you in advance.
Code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
Longop op = new Longop();
op.execute("");
}
public void loadSomeDummyData() {
try {
response = CustomHttpClient
.executeHttpPost(
"http://website.com/folder/testfile.php",
postParameters);
for (int i = 1; i < arr1.length - 1; i++) {
id.add(new String(arr[0]));
name.add(new String(arr[1]));
dateofbirth.add(new String(arr[2]));
status.add(new String(arr[3]));
}
} catch (Exception e) {
e.printStackTrace();
}
}
private class Longop extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
loadSomeDummyData();
return "Executed";
}
#Override
protected void onPostExecute(String result) {
mdialog.dismiss();
myListView.setAdapter(new MyArrayAdapter(Sample.this,
R.layout.list, id, name, dateofbirth,
status));
}
#Override
protected void onPreExecute() {
mdialog = ProgressDialog.show(Sample.this, "Please wait...",
"Retrieving data ...", true);
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
private class MyArrayAdapter extends ArrayAdapter<String> {
// this list hold the data that we will see in listview
private List<String> myData = new ArrayList<String>();
private List<String> myData1 = new ArrayList<String>();
private List<String> myData2 = new ArrayList<String>();
private List<String> myData3 = new ArrayList<String>();
public MyArrayAdapter(Context context, int textViewResourceId,
List<String> objects, List<String> objects1,
List<String> objects2, List<String> objects3) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
context = getContext();
myData = objects;
myData1 = objects1;
myData2 = objects2;
myData3 = objects3;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.list, null);
// Log.d(EKSI, "Getting the inflater from the system context");
}
String sid = myData.get(position);
String sname = myData1.get(position);
String dob = myData2.get(position);
String sstatus = myData3.get(position);
TextView entryTextView = (TextView) v.findViewById(R.id.id1);
entryTextView.setText(sid);
TextView entryTextView1 = (TextView) v
.findViewById(R.id.id2);
entryTextView1.setText(sname);
TextView entryTextView2 = (TextView) v
.findViewById(R.id.id3);
entryTextView2.setText(dob);
TextView entryTextView3 = (TextView) v
.findViewById(R.id.id4);
entryTextView3.setText(sstatus);
return v;
}
}
You could also use this lib
https://github.com/chrisbanes/Android-PullToRefresh.
I implement this function not base ListView that can do this;
Custom loading view,override onDraw menthod
Add loading view at the end of LinearLayout view. When loading view is show, it should call some methods to get data from server by HTTP.
you just need to inflate an xml in
lstView.addFooterView(R.layout.footer);
and handle onclick of the button residing in footer
Related
I am facing a problem, i have a listView that i fill using a custom array adapter, the issue is that when i use the custom array adapter, the data stored in the ArrayList won't show but if i use a normal ArrayAdapter the data will be shown. I need to use a custom array adapter to style the listview since i can't style it in the normal ArrayAdapter
here is the code:-
CustomAdapter adapter;
Context context;
ArrayList<String> data;
ListView listView;
private static String newline = System.getProperty("line.separator");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_production_comments);
//defining list view
listView = (ListView)findViewById(R.id.listView);
//defining data array list to store retrieved data from database
data = new ArrayList<String>();
adapter = new CustomAdapter(this,android.R.layout.simple_list_item_1, data);
listView.setAdapter(adapter);
context = this;
Toast.makeText(this,"Loading Please Wait..",Toast.LENGTH_LONG).show();
new AsyncLoadProdComments().execute();
}
protected class AsyncLoadProdComments extends AsyncTask<Void, JSONObject,
ArrayList<ProductionCommentsTable>> {
ArrayList<ProductionCommentsTable> ProductionCommentsTable = null;
#Override
protected ArrayList<ProductionCommentsTable> doInBackground(Void... params) {
// TODO Auto-generated method stub
RestAPI api = new RestAPI();
try {
JSONObject jsonObj = api.GetProductionComments();
JSONParser parser = new JSONParser();
ProductionCommentsTable = parser.parseProductionComments(jsonObj);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncLoadProdDetails", e.getMessage());
}
return ProductionCommentsTable;
}
#Override
protected void onPostExecute(ArrayList<ProductionCommentsTable> result) {
// TODO Auto-generated method stub
for (int i = 0; i < result.size(); i++) {
//Log.d("Data1", String.valueOf(result));
data.add("Date: " + result.get(i).getDate().substring(0, 10) + newline + newline +
"Item: " + result.get(i).getItem() + newline + newline +
result.get(i).getComments());
}
adapter.notifyDataSetChanged();
Toast.makeText(context,"Loading Completed", Toast.LENGTH_SHORT).show();
}
}
private class CustomAdapter extends ArrayAdapter {
private Context mContext;
private int id;
private List <String>items ;
public CustomAdapter(Context context, int textViewResourceId , ArrayList<String> list )
{
super(context, textViewResourceId, list);
mContext = context;
id = textViewResourceId;
items = list ;
}
#Override
public View getView(int position, View v, ViewGroup parent)
{
View mView = v ;
if(mView == null){
LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = vi.inflate(id, null);
}
if(position % 2 == 0){
mView.setBackgroundColor(Color.CYAN);
}else{
mView.setBackgroundColor(Color.YELLOW);
}
return mView;
}
}
Your using of array adapter is wrong. It has own array to store data, so instead of adding your data to data array list you shoud add it to adapter. It has method add (T object)
I have research a lot on this but nothing satisfy me .Everyone give me the a solution put the adapter.notifyDataSetChanged() in runOnUiThread which i have already done bit didi not give me the solution.
My Code is below
public class FragmentActivity3 extends Fragment {
// Hashmap for ListView
ArrayList<Item> imageArry = new ArrayList<Item>();
CustomQuoteAdapter adapter;
String jsonstring;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView=inflater.inflate(R.layout.activity_fragment_activity1, container,false);
jsonstring=JsonClass.readData();
Log.d("JSon String ",jsonstring);
new GetQuotesInfo().execute();
adapter = new CustomQuoteAdapter(getActivity(), R.layout.list, imageArry);
ListView dataList = (ListView) rootView. findViewById(R.id.list);
dataList.setAdapter(adapter);
return rootView;
}
//Async Task to load data
class GetQuotesInfo extends AsyncTask<Void, Void, Void>
{
int count;
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
try {
JSONArray jsonarr=new JSONArray(Globals.jsonText);
count=jsonarr.length();
for(int i=0;i<count;i++)
{
HashMap<String, String> quoteinfo = new HashMap<String, String>();
String author="";
Log.d("Json","Reading");
JSONObject jsonobj=jsonarr.getJSONObject(i);
String name=jsonobj.getString("name");
quoteinfo.put("name", name);
JSONArray jarr=jsonobj.getJSONArray("quotes");
String[] myarr=new String[jarr.length()];
String[] myarr1=new String[jarr.length()];
for(int j=0;j<jarr.length();j++)
{
JSONObject jobj=jarr.getJSONObject(j);
author=jobj.getString("author");
String text=jobj.getString("text");
Log.d("Author ",author);
Log.d("Text ",text);
myarr[j]=text;
myarr1[j]=author;
}
imageArry.add(new Item(name,myarr1, myarr));
}
}
catch(Exception ex)
{
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
getActivity().runOnUiThread(new Runnable(){
public void run() {
adapter.notifyDataSetChanged();
}
});
}
}
}
My Adapter class is below
public class CustomQuoteAdapter extends ArrayAdapter<Item> {
Context context;
int layoutResourceId;
LinearLayout linearMain;
ArrayList<Item> data = new ArrayList<Item>();
public CustomQuoteAdapter(Context context, int layoutResourceId,
ArrayList<Item> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = ((FragmentActivity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
linearMain = (LinearLayout) row.findViewById(R.id.lineraMain);
Item myImage = data.get(position);
TextView txtview=new TextView(context);
String heading=myImage.heading;
txtview.setText(heading);
txtview.setTextColor(Color.BLUE);
txtview.setTextSize(20);
linearMain.addView(txtview);
for (int j = 0; j < myImage.getName().length; j++) {
TextView label1 = new TextView(context);
label1.setText(myImage.author[j]);
linearMain.addView(label1);
TextView label2 = new TextView(context);
label2.setText(myImage.name[j]);
linearMain.addView(label2);
}
// ImageView image = new ImageView(context);
// int outImage = myImage.image;
// image.setImageResource(outImage);
// linearMain.addView(image);
}
return row;
}
}
Can anyone give me the solution to resolve my error
onPostExecute() is automatically called on the UI thread, so you don't need the runOnUIThread()
Have you checked to make sure the data in your list is actually changing? Also I didn't go through the logic of your entire adapter, but this line looks like there's a typo. I'm guessing your IDE would have caught it if that typo weren't also in your resources file too though
linearMain = (LinearLayout) row.findViewById(R.id.lineraMain);
Not sure if that typo R.id.lineraMain is causing you problems.
I'm having some troubles with correct identification of items in a ListView.
There are 4 classes that matter, it's a lot of code so at first I'm going to explain the logic of those classes.
Enter the ListActivity and initialize its ListView
execute an AsyncTask that downloads JSON response from the server, parses it, populates the ListView with Objects and sets the adapter while showing a ProgressDialog
the PlaylistItem class includes methods which simply get the data from a single JSONObject. It is used to parameterize the ArrayList with its Objects
after the AsyncTask is done the list is filled with items and looks like |Button| Artist(TextView) - Title(TextView)
UPDATE
resolved 1st issue but still can't figure out what's wrong with buttons
2). I set an OnClickListener to my buttons in the Adapter's getView() method. To find out if the button is identified correctly I did nothing but just changed its background. BUT a click on a certain button forces the background of every 11th or 12th button to be changed. Can't figure it out so far.
I can't proceed to getting url and streaming audio until those problems are resolved, so any help is greatly appreciated. My classes go below, please ask if something appears unclear.
AudioList
public class AudioList extends ListActivity {
private ListView lv;
private PlaylistLoader loader;
private AudioListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_list);
init(); // initialize the ListView
/*--- populate the list with user's audio in case network connection is available ---*/
loader = new PlaylistLoader(this, lv, adapter);
if (Utils.isNetworkAvailable(this)) {
loader.execute();
} else {
APP_CONSTANTS.NO_DATA_CONNECTION(this);
}
}
#Override
protected void onResume() {
super.onResume();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getApplicationContext(), Integer.toString(arg2),
Toast.LENGTH_SHORT).show();
}
});
}
private void init() {
lv = getListView();
lv.setTranscriptMode(0x00000000);
lv.setDividerHeight(1);
lv.setSmoothScrollbarEnabled(true);
lv.setVerticalFadingEdgeEnabled(true);
}
PlaylistLoader
public class PlaylistLoader extends AsyncTask<Void, Void, Void> {
private JSONObject usersPlaylist, singleJSONItem;
private JSONArray responseJSONArray;
private ListView lv;
private ArrayList<PlaylistItem> playlist;
private Activity a;
private PlaylistItem audioList;
private SharedPreferences prefs;
private ProgressDialog pd;
AudioListAdapter adapter;
public PlaylistLoader(Activity a, ListView lv, AudioListAdapter adapter) {
this.lv = lv;
this.a = a;
this.adapter = adapter;
}
#Override
protected Void doInBackground(Void... arg0) {
/*--- create new ArrayList of PlaylistItem Objects ---*/
playlist = new ArrayList<PlaylistItem>();
/*--- get the preferences using context of calling activity ---*/
prefs = PreferenceManager.getDefaultSharedPreferences(a);
try {
/*--- download the response JSONObject from server // access_token and
* user_id come from activity's defaultSharedPreferences ---*/
usersPlaylist = Utils.retrieveJsonObjectFromUrl(new URL(
APP_CONSTANTS.REQUEST_AUDIO_LIST(prefs)), a);
/*--- get the response array from received object ---*/
responseJSONArray = usersPlaylist.getJSONArray("response");
/*--- populate the ArrayList with Objects from the response array ---*/
for (int i = 0; i < responseJSONArray.length(); i++) {
singleJSONItem = responseJSONArray.getJSONObject(i);
audioList = new PlaylistItem(singleJSONItem);
playlist.add(audioList);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(a);
pd.setTitle("Please wait");
pd.setMessage("Retrieving audio list...");
pd.show();
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
lv.setVisibility(View.VISIBLE);
pd.dismiss();
/*--- set the adapter passed in constructor as an adapter for passed ListView ---*/
adapter = new AudioListAdapter(a, R.layout.playlist_item, playlist);
lv.setAdapter(adapter);
}
}
AudioListAdapter
public class AudioListAdapter extends ArrayAdapter<PlaylistItem> {
private PlaylistItem pl;
private Context context;
private int layoutResourceId;
private PlaylistItem aud;
private ArrayList<PlaylistItem> data = null;
public AudioListAdapter(Context context, int layoutResourceId,
ArrayList<PlaylistItem> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public PlaylistItem getItem(int position) {
return super.getItem(position);
}
#Override
public int getCount() {
return data.size();
}
#Override
public int getPosition(PlaylistItem item) {
return super.getPosition(item);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
pl = new PlaylistItem();
aud = getItem(position);
if (convertView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(layoutResourceId, parent, false);
pl.btnPlay = (Button) convertView.findViewById(R.id.btn_list_play);
pl.imgSaved = (ImageView) convertView
.findViewById(R.id.img_list_audio_saved);
pl.tvArtist = (TextView) convertView
.findViewById(R.id.tvListItemArtist);
pl.tvTitle = (TextView) convertView
.findViewById(R.id.tvListItemSong);
convertView.setTag(pl);
} else {
pl = (PlaylistItem) convertView.getTag();
pl.btnPlay.setBackgroundResource(R.drawable.list_button_play);
}
pl.tvArtist.setText(aud.getArtist() + " " + "-");
pl.tvTitle.setText(aud.getTitle());
pl.btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*--- vibrate if this option is enabled in the preferences ---*/
if (APP_CONSTANTS.isHapticFeedbackEnabled(getContext())) {
APP_CONSTANTS.doVibrate(getContext());
}
pl.btnPlay.setBackgroundResource(R.drawable.list_button_pause);
}
});
return convertView;
}
PlayListItem
public class PlaylistItem {
private String artist, title;
private JSONObject obj;
public Button btnPlay;
public TextView tvArtist, tvTitle;
public ImageView imgSaved;
public int duration;
public int audio_id;
public String url;
/*--- the constructor takes a single JSONObject from the response array ---*/
public PlaylistItem(JSONObject obj) {
this.obj = obj;
}
public PlaylistItem() {
// default constructor
}
/*--- the methods below return values by key from the passed JSONObject ---*/
public String getArtist() {
try {
artist = obj.getString("artist");
} catch (JSONException e) {
e.printStackTrace();
}
return artist;
}
public String getTitle() {
try {
title = obj.getString("title");
} catch (JSONException e) {
e.printStackTrace();
}
return title;
}
public int getID() {
try {
audio_id = obj.getInt("aid");
} catch (JSONException e) {
e.printStackTrace();
}
return audio_id;
}
public String getURL() {
try {
url = obj.getString("url");
} catch (JSONException e) {
e.printStackTrace();
}
return url;
}
}
Edit:
Try this
Take a custom Selector in your drawable
button_play.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/pause_button"
android:state_selected="true" />
<item android:drawable="#drawable/play_button" />
</selector>
Modifty your adapter like this
public class AudioListAdapter extends ArrayAdapter<PlaylistItem> {
private PlaylistItem pl;
private Context context;
private int layoutResourceId;
private PlaylistItem aud;
private ArrayList<PlaylistItem> data = null;
Button previous;
public AudioListAdapter(Context context, int layoutResourceId,
ArrayList<PlaylistItem> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
previous=new Button(context);
this.context = context;
this.data = data;
}
....
....
#Override
public View getView(int position, View convertView, ViewGroup parent) {
pl = new PlaylistItem();
aud = getItem(position);
if (convertView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(layoutResourceId, parent, false);
pl.btnPlay = (Button) convertView.findViewById(R.id.btn_list_play);
pl.btnPlay.setBackGroundResouce(R.drawable.button_play); //you can set here or in xml
pl.imgSaved = (ImageView) convertView
.findViewById(R.id.img_list_audio_saved);
pl.tvArtist = (TextView) convertView
.findViewById(R.id.tvListItemArtist);
pl.tvTitle = (TextView) convertView
.findViewById(R.id.tvListItemSong);
convertView.setTag(pl);
} else {
pl = (PlaylistItem) convertView.getTag();
}
pl.tvArtist.setText(aud.getArtist() + " " + "-");
pl.tvTitle.setText(aud.getTitle());
pl.btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*--- vibrate if this option is enabled in the preferences ---*/
if (APP_CONSTANTS.isHapticFeedbackEnabled(getContext())) {
APP_CONSTANTS.doVibrate(getContext());
}
//for some reason, the background gets changed for every 11th or 12th button in the list
Button current=((Button)v);
current.setSelected(true);
previous.setSelected(false);
previous=current;
}
});
return convertView;
}
}
The reason why your button and listitem not clickable is because Your list have a focus item button, so you need to setFocusable=false for your button.
Try setting focusable=false for your button in the xml. If it is not worked for you than do like this
In your row xml file
1.set focusable=true for your button.
2.In the same set android:descendantFocusability="blocksDescendants" for your parent item.(i.e parent layout in which your views lie).
In getView() method after setting the onclickListener for the button, set focusable false for the button.
It will work for sure. I hope this will help you..
BUT a click on a certain button forces the background of every 11th or 12th button to be changed. Can't figure it out so far.
You are fighting the way ListViews recycle the row layouts.
Think of it this way: if you have a ListView with 10,000 rows but can only fit 9 of them on the screen, then it doesn't make sense to create 10,000 unique layouts. This just waste resources, instead ListView only creates ~10 layouts and reuses them.
Solution: return each row to it's default state when it is reused. In getView() add:
} else {
pl = (PlaylistItem) convertView.getTag();
pl.btnPlay.setBackgroundResource(R.drawable.list_button_play);
// I guessed at the resource's name ^^^^^^^^^^^^^^^^
}
(Also you can make a few small changes to speed up your code. For instance, you only need one OnClickListener since they all contain the same code, make this a class variable and pass this to each play Button. There are more.)
I am making a sectional listview in which to section first is pending request list and second is already friend there are two button accept and reject in first section of list view.
When I click on accept hit server and change stautus and now my List should be update and first section accepted list should showing in friendlist in second section of listview.
I am using following code:-
public class EntryAdapter extends ArrayAdapter<Item> {
private Context context;
private List<Item> items;
private LayoutInflater objlayoutinflator;
private PostJobImageLoader objimageLoader;
private ConnectionFriendListModle objmodle=null;
public EntryAdapter(Context context,List<Item> items) {
super(context, 0, items);
this.context = context;
this.items = items;
objlayoutinflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
objimageLoader = new PostJobImageLoader(context.getApplicationContext());
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View myview = convertView;
final Item objitem = items.get(position);
if (objitem != null) {
if (objitem.isSection()) {
SectionItem objsection = (SectionItem) objitem;
myview = objlayoutinflator.inflate(R.layout.listviewsection,
null);
myview.setOnClickListener(null);
myview.setOnLongClickListener(null);
myview.setLongClickable(false);
final TextView sectionView = (TextView) myview
.findViewById(R.id.txtsection);
sectionView.setText(objsection.getTitle());
} else {
objmodle = (ConnectionFriendListModle) objitem;
myview = objlayoutinflator.inflate(R.layout.connectionlistrow,
null);
final TextView title = (TextView) myview
.findViewById(R.id.jobtitleinjobbidalert);
final TextView subtitle = (TextView) myview
.findViewById(R.id.jobsubtitle);
final ImageView objimageview = (ImageView) myview
.findViewById(R.id.user_image);
final Button objaccept = (Button) myview
.findViewById(R.id.btnaccept);
final Button objreject = (Button) myview
.findViewById(R.id.btnreject);
if (objmodle.getStatus().equalsIgnoreCase("pending")) {
objaccept.setVisibility(View.VISIBLE);
objreject.setVisibility(View.VISIBLE);
title.setText(objmodle.getUsername());
subtitle.setText(objmodle.getName());
String url = objmodle.getPicture();
objimageLoader.DisplayImage(AppConstants.IMAGE_BASE_URL
+ url, objimageview);
} else {
objaccept.setVisibility(View.INVISIBLE);
objreject.setVisibility(View.INVISIBLE);
title.setText(objmodle.getUsername());
subtitle.setText(objmodle.getName());
String url = objmodle.getPicture();
objimageLoader.DisplayImage(AppConstants.IMAGE_BASE_URL+url, objimageview);
}
objaccept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new AcceptFriendRequest().execute(objmodle.getId(),"accepted");
}
});
objreject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
}
});
}
}
return myview;
}
private class AcceptFriendRequest extends AsyncTask<String,Void,String>
{
ProgressDialog objprogress = new ProgressDialog(EntryAdapter.this.context);
AppRequestHandler objApprequest = new AppRequestHandler();
String objresponce="";
#Override
protected void onPreExecute() {
objprogress.setMessage("Please Wait While Loading...");
objprogress.show();
}
#Override
protected String doInBackground(String... params) {
objresponce = objApprequest.acceptRequest(params[0],params[1]);
return objresponce;
}
#Override
protected void onPostExecute(String result) {
if(objprogress.isShowing())
{
objprogress.dismiss();
}
if(result.equals("0"))
{
SharedPreferences myPrefs = EntryAdapter.this.context.getSharedPreferences(
AppConstants.MYPREF, EntryAdapter.this.context.MODE_WORLD_READABLE);
String userid = myPrefs.getString(AppConstants.USER_ID, "");
//but when controll reach this line not execute this asynctask and niether update listview
new GetAllConnectionDetail().equals("86");
}
}
}
private class GetAllConnectionDetail extends AsyncTask<String,Void,List<Item>>
{
ProgressDialog objprogress = new ProgressDialog(EntryAdapter.this.context);
AppRequestHandler objApprequest = new AppRequestHandler();
List<Item> objlistitem=null;
#Override
protected void onPreExecute() {
objprogress.setMessage("Please Wait While Loading...");
objprogress.show();
}
#Override
protected List<Item> doInBackground(String... params) {
objlistitem = objApprequest.connectionDetails(params[0]);
return objlistitem;
}
#Override
protected void onPostExecute(List<Item> result) {
if(objprogress.isShowing())
{
objprogress.dismiss();
}
items.clear();
items.addAll(result);
notifyDataSetChanged();
}
}
}
Is am going right way or wrong please any one help me why it is not working...
You have to start your GetAllConnectionDetail task by calling its execute method, seems you don't do that.
I've got a ListView with a 'show next results' button. The list is filled by a custom adapter extending BaseAdapter. Using it as shown below, only the new results are shown.
How can I append the new results to the list?
ListView listView = (ListView)findViewById(android.R.id.list);
// Show next results button
View footerView = ((LayoutInflater)ItemList.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_listview, null, false);
listView.addFooterView(footerView);
footerView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = getIntent();
i.putExtra("firstIndex", mFirstIndex + NRES_PER_PAGE);
i.putExtra("itemCount", NRES_PER_PAGE);
startActivity(i);
}
});
mItems = json.getJSONArray("data");
setListAdapter(new ItemAdapter(ItemList.this, mType, mItems));
FIX
ListActivity
public class ItemList extends MenuListActivity{
ItemAdapter mItemAdapter;
Integer mFirstIndex = 0;
JSONArray mItems = new JSONArray();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.item_list);
// Set data adapter
mItemAdapter = new ItemAdapter(ItemList.this, mType, mItems);
ListView listView = (ListView)findViewById(android.R.id.list);
View footerView = ((LayoutInflater)ItemList.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_listview, null, false);
listView.addFooterView(footerView);
footerView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
progressDialog = MyProgressDialog.show(ItemList.this, null, null);
mFirstIndex = mFirstIndex + ITEM_COUNT;
new GetItemInfoList().execute();
}
});
setListAdapter(mItemAdapter);
new GetItemInfoList().execute();
}
private class GetItemInfoList extends AsyncTask<Void, Void, JSONObject> {
protected JSONObject doInBackground(Void... params) {
// Set POST data to send to web service
List<NameValuePair> postData = new ArrayList<NameValuePair>(2);
postData.add(new BasicNameValuePair("firstindex", Integer.toString(mFirstIndex)));
postData.add(new BasicNameValuePair("itemscount", Integer.toString(ITEM_COUNT)));
JSONObject json = RestJsonClient.getJSONObject(URL_ITEMINFOLIST, postData);
return json;
}
protected void onPostExecute(JSONObject json) {
try {
// Get data from json object and set to list adapter
JSONArray jsonArray = json.getJSONArray("data");
for(int i=0; i<jsonArray.length(); i++)
mItems.put(jsonArray.get(i));
mItemAdapter.notifyDataSetChanged();
ListView listView = (ListView)findViewById(android.R.id.list);
View footerView = ((LayoutInflater)ItemList.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_listview, null, false);
listView.addFooterView(footerView);
footerView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
progressDialog = MyProgressDialog.show(ItemList.this, null, null);
mFirstIndex = mFirstIndex + ITEM_COUNT;
new GetItemInfoList().execute();
}
});
} catch (JSONException e) {
}
}
}
}
Adapter
public class ItemAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
private JSONArray mItems;
private ImageLoader mImageLoader;
private int mCategory;
public ItemAdapter(Context context, int category, JSONArray items) {
mContext = context;
mInflater = LayoutInflater.from(context);
mItems = items;
mCategory = category;
this.mImageLoader = new ImageLoader(context, true);
}
public int getCount() {
return mItems.length();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_row, null);
holder = new ViewHolder();
holder.listitem_pic = (ImageView) convertView.findViewById(R.id.listitem_pic);
holder.listitem_desc = (TextView) convertView.findViewById(R.id.listitem_desc);
holder.listitem_title = (TextView) convertView.findViewById(R.id.listitem_title);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
JSONObject item = mItems.getJSONObject(position);
String listitem_pic = item.getString("picture");
holder.listitem_pic.setTag(listitem_pic);
mImageLoader.DisplayImage(listitem_pic, (Activity)mContext, holder.listitem_pic);
holder.listitem_title.setText(item.getString("title"));
holder.listitem_desc.setText(item.getString("desc"));
}
catch (JSONException e) {
}
return convertView;
}
static class ViewHolder {
TextView listitem_title;
ImageView listitem_pic;
TextView listitem_desc;
}
}
It depends on your implementation of ItemAdapter, I'd recommend holding a reference to ItemAdapter, then updating the data set behind it and then calling notifyDataSetChanged() on it. something like:
ItemAdapter ia = new ItemAdapter(ItemList.this, mType, mItems);
setListAdapter(ia);
footerView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mItems.append(newItems);
ia.notifyDataSetChanged();
}
});
It is tricky without knowing what data you are using or whether you have the entire data set available at the start.