I am using siegmann.nl/epublib to read epub file. My Activity code is mentioned here.
public class EpubReaderActivity extends Activity
{
private LayoutInflater inflater;
private List<RowData> contentDetails;
public static final String BOOK_NAME = "books/wodehouse.epub";
ListView titleListView;
ImageView imgButtonBack;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
titleListView = (ListView)findViewById(R.id.listView1);
inflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
contentDetails = new ArrayList<RowData>();
AssetManager assetManager = getAssets();
try
{
InputStream epubInputStream = assetManager.open(BOOK_NAME);
Book book = (new EpubReader()).readEpub(epubInputStream);
logContentsTable(book.getTableOfContents().getTocReferences(), 0);
}
catch (IOException e)
{
Log.e("epublib", e.getMessage());
}
CustomAdapter adapter = new CustomAdapter(this, R.layout.list,R.id.title, contentDetails);
titleListView.setAdapter(adapter);
titleListView.setTextFilterEnabled(true);
titleListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
RowData rowData = contentDetails.get(position);
Intent intent = new Intent(EpubReaderActivity.this, ContentViewActivity.class);
try
{
intent.putExtra("display", new String(rowData.getResource().getData()));
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
startActivity(intent);
}
});
imgButtonBack = (ImageView)findViewById(R.id.imagBackButton);
imgButtonBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(EpubReaderActivity.this, ListOfBook.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
overridePendingTransition(R.anim.slide_left,R.anim.slide_right);
}
});
}
private class CustomAdapter extends ArrayAdapter<RowData>
{
public CustomAdapter(Context context, int resource, int textViewResourceId, List<RowData> objects)
{
super(context, resource, textViewResourceId, objects);
}
private class ViewHolder
{
private View row;
private TextView titleHolder = null;
public ViewHolder(View row)
{
super();
this.row = row;
}
public TextView getTitle()
{
if(null == titleHolder)
titleHolder = (TextView) row.findViewById(R.id.title);
return titleHolder;
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
TextView title = null;
RowData rowData = getItem(position);
if(null == convertView)
{
convertView = inflater.inflate(R.layout.list, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
title = holder.getTitle();
title.setText(rowData.getTitle());
return convertView;
}
}
private void logContentsTable(List<TOCReference> tocReferences, int depth)
{
if (tocReferences == null)
{
return;
}
for (TOCReference tocReference:tocReferences)
{
StringBuilder tocString = new StringBuilder();
for (int i = 0; i < depth; i++)
{
tocString.append("\t");
}
tocString.append(tocReference.getTitle());
RowData row = new RowData();
row.setTitle(tocString.toString());
row.setResource(tocReference.getResource());
contentDetails.add(row);
logContentsTable(tocReference.getChildren(), depth + 1);
}
}
private class RowData
{
private String title;
private Resource resource;
public RowData()
{
super();
}
public String getTitle()
{
return title;
}
public Resource getResource()
{
return resource;
}
public void setTitle(String title)
{
this.title = title;
}
public void setResource(Resource resource)
{
this.resource = resource;
}
}
}
Here is read the content in webView
public class ContentViewActivity extends Activity {
WebView webView;
ImageView imgButtonBack;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.content);
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
String displayString = getIntent().getExtras().getString("display");
if(displayString != null)
webView.loadData(displayString, "text/html", "utf-8");
imgButtonBack = (ImageView)findViewById(R.id.imagBackButton);
imgButtonBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(ContentViewActivity.this, EpubReaderActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
overridePendingTransition(R.anim.slide_left,R.anim.slide_right);
}
});
}
}
I want get an image on the next Activity when i click on image of the book page from webview .And null is print on LogCat.Can someone help me how to do this.
Thanks to appreciate.
Related
I have a listview fetching data from sql database by Json.
I want to turn it into dynamic listview that at the end of scroll, a "load more items" appears in the footer of the list while loading more items and adding them to the adapter (for example 10 items each time). I have problem in implementing this feature. Please help me with it.Thankx.
Activity Class:
public class MoreVideos extends ListActivity {
int i =1;
private int dateCode = 1;
private ListArrayAdapter listAdapter = null;
private ProgressDialog pDialog = null;
private String id;
#SuppressWarnings("unused")
ArrayList<videoDto> aryLists =null;
String getDate;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.more_video);
id=getIntent().getStringExtra("id");
pDialog = new ProgressDialog(getApplicationContext());
pDialog.setMessage("Loading....");
pDialog.setCancelable(true);
loadCategoriesAsync();
};
// TODO Auto-generated method stub
protected void loadCategoriesAsync() {
loadCategoriesTaskHandler task = new loadCategoriesTaskHandler();
if (Build.VERSION.SDK_INT >= 11)
{
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
else
{
task.execute();
}
}
class loadCategoriesTaskHandler extends AsyncTask<videoDto, Void, String>
{
#Override
protected String doInBackground(videoDto... params)
{
String results= "";
try
{
videoDto videodto=new videoDto();
// healthDto.getInfom(strEail.trim(),strPassword,getApplicationContext());
aryLists = new ArrayList<videoDto>();
aryLists= videodto.getvideo(id);
}
catch (Exception e)
{
e.printStackTrace();
}
return results;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
if(aryLists!=null){
listAdapter = new ListArrayAdapter(getApplicationContext(), MoreVideos.this,
aryLists);
setListAdapter(listAdapter);
}else{
Toast.makeText(getApplicationContext(), "ArrayList is null ", Toast.LENGTH_SHORT).show();
}
}
}
Adapter Class:
public class ListArrayAdapter extends ArrayAdapter<videoDto> {
private final Context context;
private MoreVideos _parent;
public ListArrayAdapter(Context context, MoreVideos parent,
ArrayList<videoDto> aryLog) {
super(context, R.layout.video_listing, aryLog);
this.context = context;
this._parent = parent;
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflate = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflate.inflate(R.layout.video_listing,
null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.index = (TextView) rowView
.findViewById(R.id.index);
viewHolder.NameOfVideo = (TextView) rowView
.findViewById(R.id.txt_name_video);
viewHolder.img = (ImageView) rowView
.findViewById(R.id.img_video);
viewHolder.rel= (RelativeLayout) rowView.findViewById(R.id.click);
viewHolder.bookv = (ImageView)rowView.findViewById(R.id.bookv);
//viewHolder.download = (ImageView)rowView.findViewById(R.id.download);
rowView.setTag(viewHolder);
rowView.setTag(viewHolder);
}
ViewHolder holder = (ViewHolder) rowView.getTag();
final videoDto userLog = (this._parent != null) ? this._parent.listAdapter
.getItem(position) : null;
String currentPosition = Integer.toString(position);
if (userLog != null) {
try {
try {
/* if(currentPosition.equals(""))
{
holder.index.setText("-----");
}
else
{
holder.index.setText(Integer.toString(Integer.parseInt(currentPosition) + 1));
}*/
holder.rel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name =userLog.link ;
/*try {
MediaPlayer player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource("http://xty/MRESC/images/test/xy.mp3");
player.prepare();
player.start();
} catch (Exception e) {
// TODO: handle exception
}*/
//Log.v("String ", speaker.vid);
Intent mainIntent = new Intent(getApplicationContext(),VideoViewActivity.class);
mainIntent.putExtra("IMGNAME", name);
//Log.v("name",name);
// startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(name)));
startActivity(mainIntent);
}
});
holder.bookv.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// String jobId = (String) v.getTag();
String name =userLog.link ;
videoDto videodto = (videoDto) v.getTag();
Intent intentJobApplicants = new Intent(getApplicationContext(),VideoViewActivity.class);
intentJobApplicants.putExtra("IMGNAME",name);
// intentJobApplicants.putExtra("JobId", jobAp.id);
startActivity(intentJobApplicants);
}
});
if (userLog.VideoText.equals("")) {
holder.NameOfVideo.setText("-----");
} else {
holder.NameOfVideo.setText(userLog.VideoText);
}
i=i+1;
Log.v("i",String.valueOf(i));
} catch (Exception ex) {
// Toast.makeText(context, ex.getMessage(),
// Toast.LENGTH_SHORT).show();
}
if (position % 2 == 0) {
rowView.setBackgroundColor(Color.LTGRAY);
} else {
rowView.setBackgroundColor(Color.WHITE);
}
}catch(Exception ex){
ex.printStackTrace();
}
}
return rowView;
}
}
}
View Holder Class:
public static class ViewHolder {
protected TextView index;
protected ImageView bookv;
protected ImageView img;
protected ImageView download;
protected TextView NameOfVideo;
protected RelativeLayout rel;
}
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.
I have a custom BaseAdapter class that creates views for comments, usernames, and numbers. This BaseAdapter receives this information from An AsyncTask. The AsyncTask runs when the user reaches the bottom of the listView. The problem is the BaseAdapter wont add new data. When I try to add new data it deletes the current data in the list and then adds the new data. I want it to keep all the data and just add data to the bottom of the listView. All of these classes are in the same Activity. Here is my current code.
class CreateCommentLists extends BaseAdapter{
Context ctx_invitation;
String[] listComments;
String[] listNumbers;
String[] listUsernames;
public CreateCommentLists(String[] comments, String[] usernames, String[] numbers, DashboardActivity context)
{
super();
ctx_invitation = context;
listComments = comments;
listNumbers = usernames;
listUsernames = numbers;
}
#Override
public int getCount() {
if(null == listComments)
{
return 0;
}
// TODO Auto-generated method stub
return listComments.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listComments[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = null;
try
{
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
v = li.inflate(R.layout.list_item, null);
TextView commentView = (TextView)v.findViewById(R.id.listComment);
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
Button numberButton = (Button)v.findViewById(R.id.listNumberButton);
commentView.setText(listComments[position]);
NumbersView.setText(listNumbers[position]);
usernamesView.setText(listUsernames[position]);
usernameButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("usernameOfProfile",listUsernames[position]);
startActivity(i);
finish();
}
});
numberButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("NumberProfile",listNumbers[position]);
startActivity(i);
finish();
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return v;
}
public void add(String[] comments, String[] usernames,
String[] numbers) {
listComments = comments;
listNumbers = usernames;
listUsernames = numbers;
}
public int getCount1() {
if(null == listComments)
{
return 0;
}
// TODO Auto-generated method stub
return listComments.length;
}
public Object getItem1(int position) {
// TODO Auto-generated method stub
return listComments[position];
}
public long getItemId1(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView1(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = null;
try
{
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
v = li.inflate(R.layout.list_item, null);
TextView commentView = (TextView)v.findViewById(R.id.listComment);
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
Button numberButton = (Button)v.findViewById(R.id.listNumberButton);
commentView.setText(listComments[position]);
NumbersView.setText(listNumbers[position]);
usernamesView.setText(listUsernames[position]);
usernameButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("usernameOfProfile",listUsernames[position]);
startActivity(i);
finish();
}
});
numberButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("NumberProfile",listNumbers[position]);
startActivity(i);
finish();
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return v;
}
final CreateCommentLists mycmlist = new CreateCommentLists(comments, usernames, numbers, DashboardActivity.this);
lstComments = (ListView)findViewById(android.R.id.list);
lstComments.setAdapter(mycmlist);
final ProgressDialog progDailog = new ProgressDialog(DashboardActivity.this);
class loadComments extends AsyncTask<JSONObject, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progDailog.setIndeterminate(false);
progDailog.setCancelable(true);
progDailog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
progDailog.show();
progDailog.setContentView(R.layout.progress_circle);
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
protected JSONObject doInBackground(JSONObject... params) {
JSONObject json2 = CollectComments.collectComments(usernameforcomments, offsetNumber);
return json2;
}
#Override
protected void onPostExecute(JSONObject json2) {
try {
if (json2.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res2 = json2.getString(KEY_SUCCESS);
if(Integer.parseInt(res2) == 1){
JSONArray commentArray = json2.getJSONArray(KEY_COMMENT);
String comments[] = new String[commentArray.length()];
for ( int i=0; i<commentArray.length(); i++ ) {
comments[i] = commentArray.getString(i);
}
JSONArray numberArray = json2.getJSONArray(KEY_NUMBER);
String numbers[] = new String[numberArray.length()];
for ( int i=0; i<numberArray.length(); i++ ) {
numbers[i] = numberArray.getString(i);
}
JSONArray usernameArray = json2.getJSONArray(KEY_USERNAME);
String usernames[] = new String[usernameArray.length()];
for ( int i=0; i<usernameArray.length(); i++ ) {
usernames[i] = usernameArray.getString(i);
}
mycmlist.add(comments,usernames,numbers);
mycmlist.notifyDataSetChanged();
}//end if key is == 1
else{
// Error in registration
registerErrorMsg.setText(json2.getString(KEY_ERROR_MSG));
}//end else
}//end if
} //end try
catch (JSONException e) {
e.printStackTrace();
}//end catch
progDailog.dismiss();
}
}
mainListView = (ListView) findViewById(android.R.id.list);
class EndlessScrollListener implements OnScrollListener {
private int i = 0;
private int visibleThreshold = 5;
private int previousTotal = 0;
private boolean loading = true;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
new loadComments().execute();
mainListView.smoothScrollToPosition(0);
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
}
mainListView.setOnScrollListener(new EndlessScrollListener());
You try this :
public class Comment {
String username;
String content;
String number;
}
Class Adapter:
public class CommentAdapter extends BaseAdapter {
private List<Comment> listComment;
private Context context;
public CommentAdapter(List<Comment> listComment, Context context) {
super();
this.listComment = listComment;
this.context = context;
}
#Override
public int getCount() {
return listComment.size();
}
#Override
public Comment getItem(int position) {
return listComment.get(position);
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = mInflater.inflate(R.layout.comment_item, null);
}
final TextView textViewUsername = (TextView) v
.findViewById(R.id.comment_Username);
final TextView textViewNumber = (TextView) v
.findViewById(R.id.comment_number);
final TextView textViewContent = (TextView) v
.findViewById(R.id.comment_Content);
final String username = listComment.get(position).getUsername();
final String number= listComment.get(position).getNumber();
String content = listComment.get(position).getContent();
textViewUsername.setText(username);
textViewNumber.setText(number);
textViewContent.setText(content);
return v;
}
}
When you need to add new comment to list. just create new Comment and add to listComment(listComment.add(newComment)), after that, call adapter.notifyDataSetChanged();
package com.example.baseadapter;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity implements OnItemClickListener {
public static final String[] title = new String[] {
"image 1", "image 2", "image 3", "image 4"
};
public static final Integer[] images = {
R.drawable.aa, R.drawable.bb, R.drawable.cc, R.drawable.cc, R.drawable.dd
};
ListView listview;
List<RowItem> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < title.length; i++) {
RowItem item = new RowItem(images[i], title[i]);
rowItems.add(item);
}
listview = (ListView)findViewById(R.id.listview);
customBaseAdapter cba = new customBaseAdapter(this, rowItems);
listview.setAdapter(cba);
listview.setOnItemClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(getApplicationContext(), "item selected", Toast.LENGTH_LONG).show();
}
public class customBaseAdapter extends BaseAdapter {
Context context;
List<RowItem> rowItem;
public customBaseAdapter(Context context, List<RowItem> listItem) {
this.context = context;
rowItem = listItem;
Log.d("const", "const");
}
#Override
public int getCount() {
Log.d("count", "count");
return rowItem.size();
}
#Override
public Object getItem(int arg0) {
Log.d("item", "item");
return rowItem.get(arg0);
}
#Override
public long getItemId(int position) {
Log.d("const", "item id");
return rowItem.indexOf(getItem(position));
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.d("const", "getview");
LayoutInflater inflater = (LayoutInflater)context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
RowItem rowitem = (RowItem)getItem(position);
TextView textForTitle;
ImageView imgForImage;
convertView = inflater.inflate(R.layout.inflate, null);
textForTitle = (TextView)convertView.findViewById(R.id.textview);
imgForImage = (ImageView)convertView.findViewById(R.id.imageview);
textForTitle.setText(rowitem.getTitle());
imgForImage.setImageResource(rowitem.getImageId());
return convertView;
}
}
public class RowItem {
int imageId;
String title;
public RowItem(int imageId, String title) {
this.imageId = imageId;
this.title = title;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getTitle() {
return title;
}
public void setStringTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return title;
}
}
}
I have a class that extends ArrayAdapter. This class works but the problem is when I add an item to the List it doubles that item, so there are two Identical list items. Here is my current ArrayAdapter class,
class Item {
String username;
String number;
String content;
public Item (String username, String number, String content){
this.username = username;
this.number = number;
this.content = content;
}
public CharSequence getNumber() {
// TODO Auto-generated method stub
return username;
}
public CharSequence getUsername() {
// TODO Auto-generated method stub
return number;
}
public CharSequence getContent() {
// TODO Auto-generated method stub
return content;
}
}
class ListAdapter extends ArrayAdapter<Item> {
public ListAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
}
private List<Item> items;
public ListAdapter(Context context, int resource, List<Item> items) {
super(context, resource, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.list_item, null);
}
final Item p = items.get(position);
if (p != null) {
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
Button numberButton = (Button)v.findViewById(R.id.listNumberButton);
commentView.setText(p.getContent());
NumbersView.setText(p.getNumber());
usernamesView.setText(p.getUsername());
usernameButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("usernameOfProfile", p.username);
startActivity(i);
finish();
}
});
numberButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("NumberProfile", p.number);
startActivity(i);
finish();
}
});
}
return v;
}
}
final List <Item> tempList = new ArrayList <Item>();
ListView yourListView = (ListView) findViewById(android.R.id.list);
final ListAdapter customAdapter = new ListAdapter(DashboardActivity.this, R.layout.list_item, tempList);
yourListView.setAdapter(customAdapter);
Here is my AsyncTask that gathers the information in the background. In the onPostExecute is where I add the Items to my list.
final ProgressDialog progDailog = new ProgressDialog(DashboardActivity.this);
class loadComments extends AsyncTask<JSONObject, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progDailog.setIndeterminate(false);
progDailog.setCancelable(true);
progDailog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
progDailog.show();
progDailog.setContentView(R.layout.progress_circle);
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
protected JSONObject doInBackground(JSONObject... params) {
JSONObject json2 = CollectComments.collectComments(usernameforcomments, offsetNumber);
return json2;
}
#Override
protected void onPostExecute(JSONObject json2) {
try {
if (json2.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res2 = json2.getString(KEY_SUCCESS);
if(Integer.parseInt(res2) == 1){
String username = json2.getString(KEY_USERNAME);
String number = json2.getString(KEY_NUMBER);
String content = json2.getString(KEY_COMMENT);
tempList.add (new Item (username, number, content));
customAdapter.addAll(tempList);
}//end if key is == 1
else{
// Error in registration
registerErrorMsg.setText(json2.getString(KEY_ERROR_MSG));
}//end else
}//end if
} //end try
catch (JSONException e) {
e.printStackTrace();
}//end catch
progDailog.dismiss();
}
}
new loadComments().execute();
Try to clear contents of adapter before you do addAll
I have an application it have two activities. When press a button in the main activity, it shows customized listview, then I press hard back button and go to the main page of my application.
Then I again press the same button and go to the listview it shows the repeated values in the listview.
Any one have any sloution please???
CookList = new ArrayList<HashMap<String, String>>();
try {
url = new URI(cookUri);
List<DataModels> list1 = new ArrayList<DataModels>();
CookListServer cookServer = new CookListServer();
StringBuilder responseString = cookServer.CookConnect(url, "hi");
System.out.println("responseString---------"+responseString);
for(int i=0; i< itemId.size(); i++){
HashMap<String, String> Cook = new HashMap<String, String>();
Cook.put("ItemId", itemId.get(i));
System.out.println("itemId--------"+itemId.get(i));
Cook.put("ItemName", itemName.get(i));
Cook.put("ItemQty", itemQty.get(i));
CookList.add(Cook);
list1.add(get(i));
}
adapter = new MySimpleArrayAdapter(context, CookList, R.layout.cooklist_item, list1);
setListAdapter(adapter);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private DataModels get(int s) {
return new DataModels(s);
}
#Override
public void onResume() {
super.onResume();
adapter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
// Adapter to list the Albums
public class MySimpleArrayAdapter extends ArrayAdapter<HashMap<String, String>> implements SectionIndexer {
private final Context context;
private final ArrayList<HashMap<String, String>> values;
List<DataModels> modellist;
public MySimpleArrayAdapter(Context context, ArrayList<HashMap<String, String>> values, int layout, List<DataModels> modellist) {
super(context, R.layout.cooklist_item, values);
this.context = context;
this.values = values;
this.modellist = modellist;
}
private final class ViewHolder {
public TextView Nametext;
public TextView Qntytext;
public Button prepareButton;
}
private LayoutInflater mLayoutInflater = null;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
if (mLayoutInflater == null) {
mLayoutInflater = LayoutInflater.from(context);
}
convertView = mLayoutInflater.inflate(R.layout.cooklist_item, null);
viewHolder = new ViewHolder();
viewHolder.Nametext = (TextView) convertView.findViewById(R.id.label);
viewHolder.Qntytext = (TextView) convertView.findViewById(R.id.textView1);
viewHolder.prepareButton = (Button) convertView.findViewById(R.id.prepareButton1);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
((ViewHolder) convertView.getTag()).prepareButton.setTag(modellist.get(position));
}
final HashMap<String, String> cooklist = values.get(position);
final ViewHolder holder = (ViewHolder) convertView.getTag();
final String ItemId = cooklist.get("ItemId");
final String ItemName = cooklist.get("ItemName");
final String ItemQty = cooklist.get("ItemQty");
System.out.println("ItemId---------"+ItemId);
System.out.println("ItemName---------"+ItemName);
System.out.println("ItemQty---------"+ItemQty);
holder.Nametext.setText(ItemName);
holder.Qntytext.setText(ItemQty);
registerForContextMenu(convertView);
holder.prepareButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DataModels element = (DataModels) viewHolder.prepareButton.getTag();
holder.prepareButton.setEnabled(false);
}
});
return convertView;
}
#Override
public int getPositionForSection(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getSectionForPosition(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object[] getSections() {
// TODO Auto-generated method stub
return null;
}
}
Thanks...
I got a solution
#Override
protected void onDestroy() {
itemId.clear();
itemName.clear();
itemQty.clear();
super.onDestroy();
}
Thanks....