How to update data into an adapter class - java

What I want to do is to append a list item at the bottom Just Like "Load More" functionality.
What I've performed i appended an extra items with empty values into adapter for ArrayList.
It's working fine for the first time but when i load more items it's adding Load More ItemView two times after every 15 items While i didn't make any changes into original ArrayList. The Changes has been made only into adapter class's constructor.
Here's the adapter class:
public class ContactListAdaptor extends BaseAdapter {
private Context context;
private ArrayList<DirectroyDetails> items = new ArrayList<DirectroyDetails>();
private Activity activity = null;
boolean isSearch = false;
private View currentView = null;
private String categoryName = null;
private HashMap< String, String> bannerHash = new HashMap<String, String>();
ContactList ACTIVITY;
public ContactListAdaptor(Context context, final ArrayList<DirectroyDetails> items2, Activity activity, String categoryName, HashMap< String, String> bannerHash, ContactList ACTIVITY, boolean expand) {
// super(context, textViewResourceId, items);
items = items2;
if(expand)
{
DirectroyDetails dummy = new DirectroyDetails();
dummy.setId("-1");
items.add(dummy);
}
this.context = context;
this.activity = activity;
this.categoryName = categoryName;
this.bannerHash = bannerHash;
this.ACTIVITY = ACTIVITY;
}
/*public ContactListAdaptor(Context context, Vector<Directory> items,
Activity activity, boolean isSearch) {
// TODO Auto-generated constructor stub
this.items = items;
this.context = context;
this.activity = activity;
this.isSearch = isSearch;
}*/
// #Override
public View getView(final int position, View convertView, ViewGroup parent) {
final DirectroyDetails directroyDetails = items.get(position);
System.out.println("id======="+directroyDetails.getId().toString());
try {
if(convertView == null)
{
System.out.println("##THE POSITION IS=="+position);
LayoutInflater vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.item_directory, null);
if(directroyDetails.getId().toString().equals("-1"))
convertView.setId(-1);
else
convertView.setId(1);
}else {
currentView = convertView;
}
//To fatch the values from the Event object
TextView titleText = (TextView)convertView.findViewById(R.id.title);
TextView nameText = (TextView)convertView.findViewById(R.id.name);
TextView numberText = (TextView)convertView.findViewById(R.id.number);
ImageView profilePic = (ImageView)convertView.findViewById(R.id.eventimage);
System.out.println("the position is ==== " +position);
titleText.setText(directroyDetails.getCompanyname());
nameText.setText(directroyDetails.getFirstname() + " " + directroyDetails.getSurname());
numberText.setText(directroyDetails.getMobile());
System.out.println("id at position======="+directroyDetails.getId().toString()+" at=="+position);
RelativeLayout overlay = (RelativeLayout)convertView.findViewById(R.id.overlay);
if(directroyDetails.getId().toString().equals("-1"))
{
overlay.setVisibility(View.VISIBLE);
System.out.println("at here to make the Overl;ay visible");
}else {
overlay.setVisibility(View.INVISIBLE);
}
} catch (Exception e) {
// TODO: handle exception
System.out.println("the exception occurs at:-" + e.getMessage());
}
return convertView;
}
public int getCount() {
System.out.println("the item size====="+items.size());
return items.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
}
private void onScrollUpdateList() {
// TODO Auto-generated method stub
Handler onScrollList = new Handler();
onScrollList.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
setContactList();
}
}, 200);
}
& here is my calling code:-
if(contactDb.size()>0 && contactDb!=null)
{
System.out.println("theh responseData1 before new additions==="+responseData1.size());
responseData1 = addMoreData(contactDb,responseData1);
System.out.println("theh responseData1==="+responseData1.size());
if(responseData1 != null)
{
if(responseData1.size()>0)
{
ContactListAdaptor contactAdaptor = new ContactListAdaptor(getApplicationContext(), responseData1, this, CategoryName, bannerHash, ContactList.this, expand);
contactAdaptor.notifyDataSetChanged();
listview.setAdapter(contactAdaptor);
try {
listview.setSelection(getSelectedItems());
} catch (Exception e) {
// TODO: handle exception
System.out.println("the exception at scrolling and set :- " + e.getMessage());
}
}else
{
Toast.makeText(ContactList.this, "No Item found.", Toast.LENGTH_LONG).show();
}
}}

Please review below link code and try to resolve your issue with load more data dynamically with list view..
http://www.developerfusion.com/article/145373/android-listviews-with-dynamic-data/
If you have any query then let me know..

Related

Sql query in Java Android

I have lots of questions that I didn't find answers to.
First of all, I have two tables in MS Sql server, one is called country that contains country id and country name, and one is called family which contains country id, family id, family name and family info. The problem I am facing is how can I write a query in Java Android that gets the id of the country and compare it with the id of the country in the families table and then for each country there is its own family.
I have tried inner joins but couldn't know how to do it.
Here is my code so far:
public class InsideCountries extends AppCompatActivity {
private ArrayList<ClassListItems> itemArrayList; //List items Array
private MyAppAdapter myAppAdapter; //Array Adapter
private ListView listView;
private TextView ttl;// Listview
private boolean success = false; // boolean
private ConnectionClass connectionClass; //Connection Class Variable
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inside_countries);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
ttl = (TextView) findViewById(R.id.title) ;
ttl.setText(getIntent().getStringExtra("CountriesName"));
listView = (ListView) findViewById(R.id.listvieww); //Listview Declaration
connectionClass = new ConnectionClass(); // Connection Class Initialization
itemArrayList = new ArrayList<ClassListItems>(); // Arraylist Initialization
// Calling Async Task
SyncData orderData = new SyncData();
orderData.execute("");
}
// Async Task has three overrided methods,
private class SyncData extends AsyncTask<String, String, String> {
String msg = "No Data Found";
ProgressDialog progress;
#Override
protected void onPreExecute() //Starts the progress dailog
{
progress = ProgressDialog.show(InsideCountries.this, "Synchronising",
"Please Wait...", true);
}
#Override
protected String doInBackground(String... strings) // Connect to the database, write query and add items to array list
{
try {
Connection conn = connectionClass.CONN(); //Connection Object
if (conn == null) {
msg = "Please Check Your Connection";
success = false;
} else {
// Change below query according to your own database.
String query = "query here";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) // if resultset not null, I add items to itemArraylist using class created
{
while (rs.next()) {
try {
itemArrayList.add(new ClassListItems(rs.getString("name")));
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch(Exception e)
{
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
success = false;
}
return msg;
}
#Override
protected void onPostExecute (String
msg) // disimissing progress dialoge, showing error and setting up my listview
{
progress.dismiss();
Toast.makeText(InsideCountries.this, msg + "", Toast.LENGTH_LONG).show();
if (success == false) {
} else {
try {
myAppAdapter = new MyAppAdapter(itemArrayList, InsideCountries.this);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(myAppAdapter);
} catch (Exception ex) {
}
}
}
}
public class MyAppAdapter extends BaseAdapter //has a class viewholder which holds
{
public class ViewHolder
{
TextView textName;
}
public List<ClassListItems> parkingList;
public Context context;
ArrayList<ClassListItems> arraylist;
private MyAppAdapter(List<ClassListItems> apps, Context context)
{
this.parkingList = apps;
this.context = context;
arraylist = new ArrayList<ClassListItems>();
arraylist.addAll(parkingList);
}
#Override
public int getCount() {
return parkingList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) // inflating the layout and initializing widgets
{
View rowView = convertView;
ViewHolder viewHolder= null;
if (rowView == null)
{
LayoutInflater inflater = getLayoutInflater();
rowView = inflater.inflate(R.layout.list_content, parent, false);
viewHolder = new ViewHolder();
viewHolder.textName = (TextView) rowView.findViewById(R.id.textName);
rowView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder) convertView.getTag();
}
// here setting up names and images
viewHolder.textName.setText(parkingList.get(position).getName()+"");
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(InsideCountries.this,Inside_Families.class);
intent.putExtra("Family",parkingList.get(position).getName());
startActivity(intent);
}
});
return rowView;
}
}
}
Any help would be apreciated!?

Parse Data from XML into List with Custom Adapter

I am getting data from an XML uploaded on a website. I want to display the text from the XML in a custom ListView, which has two TextViews. The 'title' should go into the upper TextView and the 'guid' into the lower TextView. I'm not sure how I should go about doing this. I've written the following Custom Adapter.
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
private ArrayList list;
private LayoutInflater layoutInflater;
public CustomAdapter(Context context, ArrayList list) {
this.list= list;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.layout_list_row, null);
holder = new ViewHolder();
holder.backgroundImage = (ImageView) convertView.findViewById(R.id.backgroundImage);
holder.topText = (TextView) convertView.findViewById(R.id.topText);
holder.bottomText = (TextView) convertView.findViewById(R.id.bottomText);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
DiscourseItem discourseItem = (DiscourseItem) discourseList.get(position);
holder.topText.setText(discourseItem.getTopText());
holder.bottomText.setText(discourseItem.getBottomText());
return convertView;
}
static class ViewHolder {
ImageView backgroundImage;
TextView topText; //This should display the text in the 'title' field
TextView bottomText; //This should display the text in the 'guid' field
}
}
I'm currently able to display the two separately in separate ListViews with normal ArrayAdapters. Here's the code I've written.
XMLParser.java
public class XMLParser extends AsyncTask {
private URL url;
public ArrayList<String> title = new ArrayList<>();
public ArrayList<String> guid = new ArrayList<>();
#Override
protected Object doInBackground(Object[] objects) {
try {
url = new URL(removed);
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(getInputStream(url), null);
boolean insideItem = false;
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("item")){
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("title")){
if (insideItem)
title.add(xpp.nextText());
} else if (xpp.getName().equalsIgnoreCase("guid")){
if (insideItem)
guid.add(xpp.nextText());
}
} else if (eventType == XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")){
insideItem = false;
}
eventType = xpp.next();
}
} catch (MalformedURLException e){
e.printStackTrace();
} catch (XmlPullParserException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return title;
}
public InputStream getInputStream(URL url){
try {
return url.openConnection().getInputStream();
} catch (IOException e){
e.printStackTrace();
}
return null;
}
public ArrayList<String> titles(){
return title;
}
public ArrayList<String> guids(){
return guid;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
parser = new XMLParser();
parser.execute();
title = parser.titles();
guid = parser.guids();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
discourseList = getDiscourseList();
}
}, 2000);
}
});
ListView listView = (ListView) findViewById(R.id.discourseList);
listView.setAdapter(new CustomAdapter(this, discourseList));
}
private ArrayList<DiscourseItem> getDiscourseList() {
ArrayList<DiscourseItem> listData = new ArrayList<DiscourseItem>();
String[] topText = new String[title.size()];
topText = title.toArray(topText);
String[] bottomText = new String[guid.size()];
bottomText = guid.toArray(bottomText);
for (int i = 0; i <= title.size(); i++) {
try {
DiscourseItem discourseItem = new DiscourseItem();
discourseItem.setTopText(topText[i]);
discourseItem.setBottomText(bottomText[i]);
listData.add(discourseItem);
} catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
}
return listData;
}
}
Edit :
I've made the above changes. Now when the parser runs and calls getDiscourseList(), it throws the following error at discourseItem.setTopText(topText[i]); :
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
You can create wrapper class for your upper and bottom values ( something like this, consider another name as I don't know the context of your data):
public class TitleGuidPair {
private final String title;
private final String guid;
public TitleGuidPair(String title, String guid) {
this.title = title;
this.guid = guid;
}
//getters
}
And then parse your result to ArrayList of TitleGuidPair. If you want to keep your parsing algorithm you can make some post-processing and build your TitleGuidPairs afterwards from the two lists that you have.
Having that step behind just pass to your adapter List of TitleGuidPairs and in the getView method set top and bottom text like
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.layout_list_row, null);
holder = new ViewHolder();
holder.backgroundImage = (ImageView) convertView.findViewById(R.id.backgroundImage);
holder.topText = (TextView) convertView.findViewById(R.id.topText);
holder.bottomText = (TextView) convertView.findViewById(R.id.bottomText);
TitleGuidPair titleGuidPair = list.get(position);
holder.topText.setText(titleGuidPair.getTitle());
holder.bottomText.setText(titleGuidPair.getGuid());
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}

Android ListView items disappear when scrolling

I've loaded some pictures into a ListView using an adapter. When a user clicks on any row of the list I'm showing a checkmark at the end:
public class LazyImageLoadAdapter extends BaseAdapter implements OnClickListener{
private Activity activity;
List<String> names,facebookbid;
String sent;
private LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyImageLoadAdapter(Activity a, List<String> n,List<String> fid,String s) {
activity = a;
names=n;
facebookbid=fid;
sent=s;
inflater = (LayoutInflater)activity.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext(),"p");
}
#Override
public int getViewTypeCount() {
if (getCount() != 0)
return getCount();
return 1;
}
public int getCount() {
return facebookbid.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder Class to contain inflated xml file elements *********/
public class ViewHolder{
public TextView text;
public ImageView image;
public ImageView checkmark;
public RelativeLayout friendsrow;
}
public View getView(final int position, View convertView, ViewGroup parent) {
convertView=null;
final ViewHolder holder;
if(convertView==null){
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
convertView = inflater.inflate(R.layout.planners_friends_listrow, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.planner_friend_name);
(ImageView)convertView.findViewById(R.id.planner_friend_image);
holder.checkmark=(ImageView)convertView.findViewById(R.id.checkmark);
holder.friendsrow=(RelativeLayout)convertView.findViewById(R.id.friendsrow);
/************ Set holder with LayoutInflater ************/
convertView.setTag( holder );
}
else
holder=(ViewHolder)convertView.getTag();
holder.text.setText(names.get(position));
Typeface face = Typeface.createFromAsset(convertView.getContext().getAssets(),
"fonts/MAXWELL REGULAR.ttf");
holder.text.setTypeface(face);
ImageView image = holder.image;
String link;
if(sent.equals("planners"))
{link=facebookbid.get(position);
}
else
{
link="https://graph.facebook.com/"+facebookbid.get(position)+"/picture?type=large";
}
//DisplayImage function from ImageLoader Class
imageLoader.DisplayImage(link, image);
holder.friendsrow.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
boolean a=isNetworkConnected();
if(a==true)
{
if(sender.equals("settings"))
{
}
else if(sender.equals("savethedate"))
{
if(sid.contains(facebookbid.get(position)))
{
if(sid.contains("_"))
{
sid=sid.replace("_"+facebookbid.get(position), "");
}
else
{
sid=sid.replace(facebookbid.get(position), "");
}
nb_selections--;
selectedids.remove(selectedids.size()-1);
sidetitle.setText("Invite ("+String.valueOf(nb_selections)+") friends");
holder.checkmark.setVisibility(View.GONE);
}
else
{
if(sid.isEmpty())
{
sid=sid+facebookbid.get(position);
}
else
{
sid=sid+"_"+facebookbid.get(position);
}
nb_selections++;
selectedids.add(facebookbid.get(position));
sidetitle.setText("Invite ("+String.valueOf(nb_selections)+") friends");
holder.checkmark.setVisibility(View.VISIBLE);
}
}
else
{
String friendname=names.get(position);
String friendid=facebookbid.get(position);
String friendgender=gender.get(position);
Intent resultIntent = new Intent(Friends.this,Newmarriage.class);
resultIntent.putExtra("facebookbid", friendid);
resultIntent.putExtra("name", friendname);
resultIntent.putExtra("gender", friendgender);
if(sender.equals("planner"))
{
resultIntent.putExtra("plannerid",friendid);
resultIntent.putExtra("imageurl","https://graph.facebook.com/"+friendid+"/picture?type=large");
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
else
{
resultIntent.putExtra("plannerid","");
resultIntent.putExtra("imageurl","");
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
}
}
else
{
Toast.makeText(getApplicationContext(),"No internet connection",Toast.LENGTH_LONG).show();
}
}
});
/******** Set Item Click Listner for LayoutInflater for each row ***********/
// vi.setOnClickListener(new OnItemClickListener(position));
return convertView;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
The problem is: When the ListView is scrolled, the checkmark icon simply disappears. What am I doing wrong?
Looking at your code you set the Visibility of the checkmark when the user clicks on one of the items which then shows / hides the item. Now when the user scrolls the items are recycled and you dont have any code to check if the item has been checked or not.
So in short you need something that basically says
if (checked) {
//set visibility of the checkmark to visible
} else {
//set visibility of the checkmark to gone
}
First you need to change getView method as don't reinitialize convertView as null remove below line from getView
public class LazyImageLoadAdapter extends BaseAdapter implements OnClickListener {
private Activity activity;
List<String> names, facebookbid;
String sent;
public ImageLoader imageLoader;
private int size = 0;
private HashMap<String, Boolean> mapClickStatus;
public LazyImageLoadAdapter(Activity a, List<String> n, List<String> fid, String s) {
activity = a;
names = n;
facebookbid = fid;
sent = s;
mapClickStatus = new HashMap<String, Boolean>();
if (facebookbid != null)
size = facebookbid.size();
// Give total size of the list item to getCount method
imageLoader = new ImageLoader(activity, "p");
}
#Override
public int getCount() {
return size;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
/*********
* Create a holder Class to contain inflated xml file elements
*********/
public class ViewHolder {
public TextView text;
public ImageView image;
public ImageView checkmark;
public RelativeLayout friendsrow;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// convertView=null;
//It should not be null every time
final ViewHolder holder;
if (convertView == null) {
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
convertView = LayoutInflater.from(activity).inflate(R.layout.planners_friends_listrow, parent, false);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.planner_friend_name);
(ImageView) convertView.findViewById(R.id.planner_friend_image);
holder.checkmark = (ImageView) convertView.findViewById(R.id.checkmark);
holder.friendsrow = (RelativeLayout) convertView.findViewById(R.id.friendsrow);
/************ Set holder with LayoutInflater ************/
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.text.setText(names.get(position));
Typeface face = Typeface.createFromAsset(convertView.getContext().getAssets(),
"fonts/MAXWELL REGULAR.ttf");
holder.text.setTypeface(face);
ImageView image = holder.image;
String link;
if (sent.equals("planners")) {
link = facebookbid.get(position);
} else {
link = "https://graph.facebook.com/" + facebookbid.get(position) + "/picture?type=large";
}
//DisplayImage function from ImageLoader Class
imageLoader.DisplayImage(link, image);
// set the visibility of CheckMark ImageView based on the click status.
if (mapClickStatus.get(facebookbid.get(position)))
holder.checkmark.setVisibility(View.VISIBLE);
else
holder.checkmark.setVisibility(View.GONE);
holder.friendsrow.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
boolean a = isNetworkConnected();
/// I dont know about the unique ID field in this so i took facebookbid.get(position) as a key
// To set click status of row item in hashmap.
mapClickStatus.put(facebookbid.get(position),
mapClickStatus.containsKey(facebookbid.get(position)) ? false : true);
if (a == true) {
if (sender.equals("settings")) {
} else if (sender.equals("savethedate")) {
if (sid.contains(facebookbid.get(position))) {
if (sid.contains("_")) {
sid = sid.replace("_" + facebookbid.get(position), "");
} else {
sid = sid.replace(facebookbid.get(position), "");
}
nb_selections--;
selectedids.remove(selectedids.size() - 1);
sidetitle.setText("Invite (" + String.valueOf(nb_selections) + ") friends");
// holder.checkmark.setVisibility(View.GONE);
} else {
if (sid.isEmpty()) {
sid = sid + facebookbid.get(position);
} else {
sid = sid + "_" + facebookbid.get(position);
}
nb_selections++;
selectedids.add(facebookbid.get(position));
sidetitle.setText("Invite (" + String.valueOf(nb_selections) + ") friends");
// holder.checkmark.setVisibility(View.VISIBLE);
}
// TO refresh view with updated checkmark status
notifyDataSetChanged();
} else {
String friendname = names.get(position);
String friendid = facebookbid.get(position);
String friendgender = gender.get(position);
Intent resultIntent = new Intent(Friends.this, Newmarriage.class);
resultIntent.putExtra("facebookbid", friendid);
resultIntent.putExtra("name", friendname);
resultIntent.putExtra("gender", friendgender);
if (sender.equals("planner")) {
resultIntent.putExtra("plannerid", friendid);
resultIntent.putExtra("imageurl", "https://graph.facebook.com/" + friendid + "/picture?type=large");
setResult(Activity.RESULT_OK, resultIntent);
finish();
} else {
resultIntent.putExtra("plannerid", "");
resultIntent.putExtra("imageurl", "");
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
}
} else {
Toast.makeText(getApplicationContext(), "No internet connection", Toast.LENGTH_LONG).show();
}
}
});
/******** Set Item Click Listner for LayoutInflater for each row ***********/
// vi.setOnClickListener(new OnItemClickListener(position));
return convertView;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
Suggestions
Inflate layout with parent attaching like below
.
convertView = LayoutInflater.from(activity).inflate(R.layout.planners_friends_listrow, parent, false);
Avoid mantaining status by using multiple collection(Arraylist or
like that to display data) use Model Class or JSON or Arraylist of
map etc.

How to refresh list view whenever data is updated in back end by other users

I have a list view containing few fields coming from back end. One feed is 'number of likes'.
When I click on any list row it opens one activity for that row, there like button in that activity. When user presses like it get appended on server.
Now the problem is it should show incremented value in the list view when user go back to list view activity. How to do that?
NOTE: Like counter is incremented if I close the app and start it again.
I tried to call on Create method again from on Resume method but it produces duplicate copy of rows every time list view activity is remusmed.
Here is my list activity code.
public class MainActivity extends Activity {
// Session Manager Class
SessionManager session;
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "MY_URL";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
{
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setThumbnailUrl(obj.getString("image"));
movie.setTitle(obj.getString("title"));
movie.setDate(obj.getString("date"));
movie.setVideo(obj.getString("video"));
movie.setLikes(obj.getInt("likes"));
movie.setId(obj.getInt("id"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//creating unique ID
final String deviceId = Settings.Secure.getString(this.getContentResolver(),
Settings.Secure.ANDROID_ID);
Toast.makeText(this, deviceId, Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG).show();
/**
* Call this function whenever you want to check user login
* This will redirect user to LoginActivity is he is not
* logged in
* */
session.checkLogin();
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
// ImageView thumbNail = (ImageView)view.findViewById(R.id.thumbnail);
String title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String likes = ((TextView)view.findViewById(R.id.likes)).getText().toString();
String date = ((TextView)view.findViewById(R.id.date)).getText().toString();
String video = ((TextView) view.findViewById(R.id.video)).getText().toString();
String idd = ((TextView) view.findViewById(R.id.idd)).getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(), MovieDetailActivity.class);
// in.putExtra("THUMB", thumbNail.toString());
in.putExtra("TITLE", title);
in.putExtra("LIKES", likes);
in.putExtra("DATE", date);
in.putExtra("VIDEO", video);
in.putExtra("IDD", idd);
in.putExtra("UNIQUEID",deviceId);
//in.putExtra(TAG_URL,"url");
// in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
}
);
// Creating volley request obj
enter code here
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setThumbnailUrl(obj.getString("image"));
movie.setTitle(obj.getString("title"));
movie.setDate(obj.getString("date"));
movie.setVideo(obj.getString("video"));
movie.setLikes(obj.getInt("likes"));
movie.setId(obj.getInt("id"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Movie> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView likes = (TextView) convertView.findViewById(R.id.likes);
TextView date = (TextView) convertView.findViewById(R.id.date);
TextView video = (TextView) convertView.findViewById(R.id.video);
TextView id = (TextView) convertView.findViewById(R.id.idd);
//TextView year = (TextView) convertView.findViewById(R.id.releaseYear);
// getting movie data for the row
Movie m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
// rating
date.setText(m.getDate());
video.setText(m.getVideo());
likes.setText(String.valueOf(m.getLikes()));
id.setText(String.valueOf(m.getId()));
return convertView;
// Listview on item click listener
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
Requested implementation using a SortedList and RecyclerView:
Here is the example I used to build mine.
This is my slightly more complex code that includes sorting via a SearchView in the toolbar. You can use the example in the above link if you want the example without the sorting. The control logic is in my Presenter class that manages this adapter and the Fragment:
public class AdapterInstitutionList extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
// lists to control all items and items visible after sorting
private SortedList<MInstitutionInfo> visibleList;
private ArrayList<MInstitutionInfo> allItems;
// my fragment and the presenter
private FInstitutionSelection fInstitutionSelection;
private PInstitutionList presenter;
public AdapterInstitutionList(PInstitutionList pInstitutionSelection, FInstitutionSelection fInstitutionSelection) {
// get ref to fragment, presenter, and create new callback for sortedlist
this.fInstitutionSelection = fInstitutionSelection;
presenter = pInstitutionSelection;
visibleList = new SortedList<>(MInstitutionInfo.class, new InstitutionListCallback());
allItems = new ArrayList<>();
}
// inflate your list item view here
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.listitem_institution, parent, false);
return new InstitutionViewHolder(view);
}
// on binding, you populate your list item with the values, onclickhandle, etc
#Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
InstitutionViewHolder institutionViewHolder = (InstitutionViewHolder) viewHolder;
final MInstitutionInfo institutionInfo = visibleList.get(position);
institutionViewHolder.setInstitutionInfo(institutionInfo);
institutionViewHolder.populateTextView();
institutionViewHolder.parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
presenter.onInstitutionSelected(institutionInfo);
}
});
}
#Override
public int getItemCount() {
return visibleList.size();
}
// my utility function for the presenter/fragment
public MInstitutionInfo get(int position) {
return visibleList.get(position);
}
public int add(MInstitutionInfo item) {
return visibleList.add(item);
}
public int indexOf(MInstitutionInfo item) {
return visibleList.indexOf(item);
}
public void updateItemAt(int index, MInstitutionInfo item) {
visibleList.updateItemAt(index, item);
}
public void addAll(List<MInstitutionInfo> items) {
visibleList.beginBatchedUpdates();
try {
for (MInstitutionInfo item : items) {
visibleList.add(item);
allItems.add(item);
}
} finally {
visibleList.endBatchedUpdates();
}
}
public void addAll(MInstitutionInfo[] items) {
addAll(Arrays.asList(items));
}
public boolean remove(MInstitutionInfo item) {
return visibleList.remove(item);
}
public MInstitutionInfo removeItemAt(int index) {
return visibleList.removeItemAt(index);
}
public void clearVisibleList() {
visibleList.beginBatchedUpdates();
try {
// remove items at end to remove unnecessary array shifting
while (visibleList.size() > 0) {
visibleList.removeItemAt(visibleList.size() - 1);
}
} finally {
visibleList.endBatchedUpdates();
}
}
public void clearAllItemsList() {
allItems.clear();
}
public void filterList(String queryText) {
clearVisibleList();
visibleList.beginBatchedUpdates();
try {
String constraint = queryText.toLowerCase();
for (MInstitutionInfo institutionInfo : allItems) {
if (institutionInfo.getName() != null && institutionInfo.getName().toLowerCase().contains(constraint)) {
visibleList.add(institutionInfo);
}
}
} finally {
visibleList.endBatchedUpdates();
}
}
public void clearFilter() {
if (visibleList.size() == allItems.size()) {
return;
}
clearVisibleList();
visibleList.beginBatchedUpdates();
try {
for (MInstitutionInfo institutionInfo : allItems) {
visibleList.add(institutionInfo);
}
} finally {
visibleList.endBatchedUpdates();
}
}
// the callback for the SortedList
// this manages the way in which items are added/removed/changed/etc
// mine is pretty simple
private class InstitutionListCallback extends SortedList.Callback<MInstitutionInfo> {
#Override
public int compare(MInstitutionInfo o1, MInstitutionInfo o2) {
return o1.getName().compareTo(o2.getName());
}
#Override
public void onInserted(int position, int count) {
notifyItemRangeInserted(position, count);
}
#Override
public void onRemoved(int position, int count) {
notifyItemRangeRemoved(position, count);
}
#Override
public void onMoved(int fromPosition, int toPosition) {
notifyItemMoved(fromPosition, toPosition);
}
#Override
public void onChanged(int position, int count) {
notifyItemRangeChanged(position, count);
}
#Override
public boolean areContentsTheSame(MInstitutionInfo oldItem, MInstitutionInfo newItem) {
return oldItem.getName().equals(newItem.getName());
}
#Override
public boolean areItemsTheSame(MInstitutionInfo item1, MInstitutionInfo item2) {
return item1.getName().equals(item2.getName());
}
}
// this is the view holder that is used for the list items
private class InstitutionViewHolder extends RecyclerView.ViewHolder {
public View parent;
public TextView tvName;
public MInstitutionInfo institutionInfo;
public InstitutionViewHolder(View itemView) {
super(itemView);
parent = itemView;
tvName = (TextView) itemView.findViewById(R.id.tv_institution_listitem_name);
}
public MInstitutionInfo getInstitutionInfo() {
return institutionInfo;
}
public void setInstitutionInfo(MInstitutionInfo institutionInfo) {
this.institutionInfo = institutionInfo;
}
public void populateTextView() {
if (tvName != null && institutionInfo != null && institutionInfo.getName() != null) {
tvName.setText(institutionInfo.getName());
}
}
}
You simply instantiate this adapter and assign it to your RecyclerView
myRecyclerView.setAdapter(myAdapter);
When you call any of the batched updates, the list will automatically update itself in the UI. So when you get your initial data, just call addAll(yourData) and the RecyclerView will auto populate the list. When you get updated data, you just call addAll(yourNewData) and the RecyclerView will automatically add new items and remove the new non-existent items leaving you with a fully updated list. You will need to be sure to implement the SorteList.Callback methods compare(...), areContentsTheSame(...), areItemsTheSame(...) properly to ensure that this behaves as you want it to when adding/removing items.
Please let me know if you need any more help. Frankly, this implementation type for updated and sorted data is extremely smooth.

Not able to display the image on listview

I am trying to display a image downloading from the url and displaying it in the listview.
This is my source code. The output has a blank spot.. that's all...
This is my java from which I am calling.
ABC s = ABC.getSingletonObject();
String[][] full_data = s.getString();
private ListView listView1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
//second one is always the type of data...
Weather weather_data[] = new Weather[]
{ // full_data[1][0] contains the URL String..
new Weather(full_data[1][0],full_data[1][2],full_data[1][3]),
new Weather(full_data[2][0],full_data[2][2],full_data[2][3]),
};
WeatherAdapter adapter = new WeatherAdapter(this,R.layout.listview_header_row, weather_data);
listView1 = (ListView)findViewById(R.id.listView1);
View header = (View)getLayoutInflater().inflate(R.layout.listview_header_row, null);
listView1.addHeaderView(header);
listView1.setAdapter(adapter);
}
This is my adapter ..
public class WeatherAdapter extends ArrayAdapter<Weather> {
Context context;
int layoutResourceId;
Weather data[] = null;
public WeatherAdapter(Context context, int layoutResourceId, Weather[] 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;
WeatherHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new WeatherHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imageView1);
holder.txtTitle = (TextView)row.findViewById(R.id.txt1);
holder.txtRating=(TextView)row.findViewById(R.id.rtxt1);
row.setTag(holder);
}
else
{
holder = (WeatherHolder)row.getTag();
}
Weather weather = data[position];
holder.txtTitle.setText(weather.wtitle);
holder.imgIcon.setImageDrawable(weather.wicon);
holder.txtRating.setText(weather.wrating);
//holder.imgIcon.setImageResource(R.drawable.ic_launcher);
//holder.imgIcon.setImageBitmap(weather.wicon);
return row;
}
static class WeatherHolder
{
//Bitmap imgIcon;
ImageView imgIcon;
TextView txtTitle;
TextView txtRating;
}
}
this is the other java file
public class Weather {
public Drawable publicdraw;
public Drawable wicon;
public String wtitle;
public String wrating;
public Weather(){
super();
}
public Weather(String icon, String title,String rating) {
super();
LoadImageFromWebOperations(icon);
this.wtitle = title;
this.wrating=rating;
this.wicon=publicdraw;
}
public void LoadImageFromWebOperations(String url_string) {
try {
grabImage(url_string);
} catch (Exception e) {
}
}
public void grabImage(String url) {
new GrabURL1().execute(url);
}
private class GrabURL1 extends AsyncTask<String, Void, Void> {
public Drawable d;
InputStream is;
protected Void doInBackground(String... urls) {
try {
is = (InputStream) new URL(urls[0]).getContent();
d = Drawable.createFromStream(is, "src name");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void unused) {
publicdraw=d;
}
}
}
I recommend you to go through this tutorial. Straight forward, not difficult and very efficient. I am using it for my projects where I load images on listview.If you get stucked somewhere please ask.
Try adding following condition before assigning image to your list.
if (holder.imgIcon != null && position < weather_data.size()) {
Weather weather = data[position];
holder.imgIcon.setImageDrawable(weather.wicon);
}
I have the same problem and this trick worked like a charm for me.
Thanks.

Categories