android listview set background of some items (problems when scrolling) - android

I´m new to Android and i´ve a problem with my items-background in my listview... it seems to work (items with "premium = 1" should have a yellow background), but when i scroll down and then back up everytime other items have the yellow background-color?!
And i can´t find my mistake :(
Pois.java (the important part)
protected void ausgeben()
{
ausgabestring = ausgabestring.trim();
ausgabestring = ausgabestring.substring(1);
rowItems = new ArrayList<PoiRowItem>();
try{
jsonArray = new JSONArray(ausgabestring);
Log.i("ausgabe", "teilsuccess");
for(int i=0; i < jsonArray.length(); i++)
{
JSONObject jsonObj = jsonArray.getJSONObject(i);
PoiRowItem item = new PoiRowItem(jsonObj.getString("POI_NAME"), jsonObj.getString("POI_ID"), jsonObj.getString("POI_PREMIUM"));
rowItems.add(item);
}
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
}
listView = (ListView) findViewById(R.id.list);
PoiListViewAdapter adapter = new PoiListViewAdapter(this, R.layout.poi_list_item, rowItems);
listView.setAdapter(adapter);
//listView.setOnItemClickListener(this);
}
PoiListViewAdapter.java (Where i think is my problem)
import java.util.List;
import at.visualstudioteschl.dguide.PoiRowItem;
import at.visualstudioteschl.dguide.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class PoiListViewAdapter extends ArrayAdapter<PoiRowItem> {
Context context;
public PoiListViewAdapter(Context context, int resourceId, List<PoiRowItem> items) {
super(context, resourceId, items);
this.context = context;
}
private class ViewHolder {
TextView txtTitle;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
PoiRowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.poi_list_item, null);
holder = new ViewHolder();
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtTitle.setText(rowItem.getTitle());
// TODO HIER GIBTS NOCH NEN FEHLER... ES WERDEN BEIM SCROLLEN NACH KURZER ZEIT ALLE GELB
if (rowItem.getPremium().contains("1")){
holder.txtTitle.setBackgroundColor(Color.YELLOW);
}
return convertView;
}
}
PoiRowItem.java
public class PoiRowItem {
private String title;
private String kat_id;
private String premium;
public PoiRowItem(String title, String kat_id, String premium) {
this.title = title;
this.kat_id = kat_id;
this.premium = premium;
}
public String getID() {
return kat_id;
}
public void setID(String id) {
this.kat_id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return kat_id;
}
public String getPremium() {
return premium;
}
public void setPremium(String premium) {
this.premium = premium;
}
}
*poi_list_item.xml*
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:padding="5dp"
android:textSize="20sp"
android:singleLine="true"/>
</RelativeLayout>

The views are re-used.. So you need to set the original color back when you don't want the yellow color.
// TODO HIER GIBTS NOCH NEN FEHLER... ES WERDEN BEIM SCROLLEN NACH KURZER ZEIT ALLE GELB
if (rowItem.getPremium().contains("1")){
holder.txtTitle.setBackgroundColor(Color.YELLOW);
}
else{
holder.txtTitle.setBackgroundColor(Color.WHITE); // the original color here
}

Your list items are reused when scrolling, so you need to force the normal color in case of non-premium, e.g:
if (rowItem.getPremium().contains("1")){
holder.txtTitle.setBackgroundColor(Color.YELLOW);
}
else {
holder.txtTitle.setBackgroundColor(Color.WHITE);
}

Related

ListView not getting populated from the Adapter

This app is used to fetch the books as JSON using Google Books API and on research I also found that the JSON data is loading fine and the Book Title, Author is parsed correctly and I tested that using toasts. But the listView is not showing up even from setting the listView with the adapter. What must be the error? The app also doesn't crash making it little difficult to troubleshoot. Thanks in advance!
Main Activity
package com.praveent.booklisting;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Scanner;
public class MainActivity extends AppCompatActivity {
public String rootUrl = "https://www.googleapis.com/books/v1/volumes";
public String queryParameter = "q";
Button search_button;
EditText search_string;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list_view);
search_button = (Button) findViewById(R.id.search_button);
search_string = (EditText) findViewById(R.id.search_string);
search_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String query = search_string.getText().toString();
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if(activeNetworkInfo != null && activeNetworkInfo.isConnected()){
new BackgroundTask().execute(query);
}
else{
Toast.makeText(MainActivity.this, "Please switch on the internet!", Toast.LENGTH_SHORT).show();
}
}
});
}
public void populate(BookAdapter adapter){
listView.setAdapter(adapter);
}
public class BackgroundTask extends AsyncTask<String, JSONArray, String> {
#Override
protected String doInBackground(String... strings) {
String query = strings[0];
URL url = null;
Uri uri = Uri.parse(rootUrl).buildUpon().appendQueryParameter(queryParameter, query).build();
try {
url = new URL(uri.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
String data = null;
try {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
if(scanner.hasNext()){
data = scanner.next();
}
} catch (IOException e1) {
e1.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
BookAdapter bookAdapter;
JSONObject jsonObject = null;
JSONArray jsonArray = null;
JSONObject jsonArrayObject = null;
JSONObject volumeInfo = null;
JSONArray authorInfo = null;
JSONObject imageInfo = null;
String imageUrl = null;
String bookTitle = null;
String bookAuthor = null;
try {
jsonObject = new JSONObject(s);
jsonArray = jsonObject.getJSONArray("items");
ArrayList<Book> books= new ArrayList<Book>();
for(int i = 0; i <= jsonArray.length(); i++){
jsonArrayObject = jsonArray.getJSONObject(i);
volumeInfo = jsonArrayObject.getJSONObject("volumeInfo");
bookTitle = volumeInfo.getString("title");
authorInfo = volumeInfo.getJSONArray("authors");
bookAuthor = " ";
if (authorInfo != null){
bookAuthor = authorInfo.getString(0);
}
//imageInfo = volumeInfo.getJSONObject("imageLinks");
//imageUrl = imageInfo.getString("smallThumbnail");
books.add(new Book(bookTitle, bookAuthor));
Toast.makeText(MainActivity.this, bookAuthor, Toast.LENGTH_SHORT).show();
}
bookAdapter = new BookAdapter(MainActivity.this, books);
populate(bookAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Book Adapter
package com.praveent.booklisting;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class BookAdapter extends ArrayAdapter<Book>{
Context c = null;
public BookAdapter(Context context, ArrayList<Book> books) {
super(context, 0, books);
c = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
Book currentBook = getItem(position);
TextView bookTextView = (TextView) listItemView.findViewById(R.id.book_name);
bookTextView.setText(currentBook.getBookName());
TextView authorTextView = (TextView) listItemView.findViewById(R.id.book_author);
authorTextView.setText(currentBook.getAuthorName());
//ImageView coverImageView = (ImageView) listItemView.findViewById(R.id.cover_image);
//Picasso.with(c).load(currentBook.getImageURL()).into(coverImageView);
return listItemView;
}
}
Book Class
package com.praveent.booklisting;
public class Book {
private String bookName;
private String authorName;
private String imageURL;
public Book(String name, String author){
bookName = name;
authorName = author;
//imageURL = url;
}
public String getBookName() {
return bookName;
}
public String getAuthorName() {
return authorName;
}
public String getImageURL() {
return imageURL;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context="com.praveent.booklisting.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:id="#+id/search_string"
android:textAlignment="center"
android:gravity="center"
android:hint="#string/search_hint"/>
<Button
android:layout_width="match_parent"
android:id="#+id/search_button"
android:layout_height="wrap_content"
android:text="#string/search_button" />
<ListView
android:layout_width="fill_parent"
android:id="#+id/list_view"
android:layout_height="fill_parent">
</ListView>
</LinearLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:padding="8dp"
android:layout_height="wrap_content">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/cover_image"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/book_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textColor="#000"
android:id="#+id/book_author"/>
</LinearLayout>
</LinearLayout>
On PostExecute Change
for(int i = 0; i <=jsonArray.length(); i++)
to for(int i = 0;i<jsonArray.length(); i++)
On list_item.xml change the text color to white
you need to call getCount() in adapter.
public class BookAdapter extends ArrayAdapter<Book>{
Context c = null;
ArrayList<Book> bookslist = new ArrayList();
public BookAdapter(Context context, ArrayList<Book> books) {
super(context, 0, books);
c = context;
bookslist = books;
}
#Override
public int getCount() {
return bookslist.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
Book currentBook = getItem(position);
TextView bookTextView = (TextView) listItemView.findViewById(R.id.book_name);
bookTextView.setText(currentBook.getBookName());
TextView authorTextView = (TextView) listItemView.findViewById(R.id.book_author);
authorTextView.setText(currentBook.getAuthorName());
//ImageView coverImageView = (ImageView) listItemView.findViewById(R.id.cover_image);
//Picasso.with(c).load(currentBook.getImageURL()).into(coverImageView);
return listItemView;
}
}
Change your adapter to this
public class BookAdapter extends ArrayAdapter<Book> {
Context c = null;
private List<Book> bookList;
public BookAdapter(Context context, ArrayList<Book> books) {
super(context, 0, books);
c = context;
bookList = new ArrayList<>();
bookList = books;
}
#Override
public int getCount() {
return bookList.size();
}
#Nullable
#Override
public Book getItem(int position) {
return bookList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
Book currentBook = getItem(position);
TextView bookTextView = (TextView) listItemView.findViewById(R.id.book_name);
bookTextView.setText(currentBook.getBookName());
TextView authorTextView = (TextView) listItemView.findViewById(R.id.book_author);
authorTextView.setText(currentBook.getAuthorName());
//ImageView coverImageView = (ImageView) listItemView.findViewById(R.id.cover_image);
//Picasso.with(c).load(currentBook.getImageURL()).into(coverImageView);
return listItemView;
}
}
I checked your code Error is in the AsyncTask onPostExecute method, change your for loop condition to this
for(int i = 0; i < jsonArray.length(); i++)
It is now working.

My list view is not showing anything i have use array adapter and no error in logcat

I am not getting anything in the listview when i am running this code.
I am trying to get value from server in text view,i am getting value from server in payload object.but still my list view is not showing anything and there is no error in logcat.
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.zalonstyles.app.zalon.Model.Services;
import com.zalonstyles.app.zalon.Model.ViewHolder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
This is the class where i am getting data from server
public class popup_massage extends AppCompatActivity {
public static final String URL = "http://52.41.72.46:8080/service/get_category";
public final String serviceid = "6";
private ListView mainListView;
private Button check;
private List<Services> massagelist = new ArrayList<>();
private Services massageservice[];
private Context context;
public ArrayAdapter<Services> listAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popup_massage);
SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String value=(mSharedPreference.getString("AppConstant.AUTH_TOKEN", "DEFAULT"));
Log.e("accesslog",value);
mainListView = (ListView) findViewById(R.id.listView4);
check = (Button) findViewById(R.id.button4);
final JSONObject params = new JSONObject();
try {
params.put("service_id",serviceid);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("access_token", value);
} catch (JSONException e) {
e.printStackTrace();
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>(){
#Override
public void onResponse(String response) {
Log.v("updateUPVolleyRes1",response);
try {
JSONObject jobject = new JSONObject(response);
JSONArray payload = jobject.getJSONArray("payload");
Log.e("payloaddata", String.valueOf(payload));
for (int i = 0; i < payload.length(); i++) {
try{
JSONObject obj = payload.getJSONObject(i);
Services service = new Services();
service.setName(obj.getString("name"));
service.setcategotry_id(obj.getString("id"));
massagelist.add(service);
}finally {
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.v("updateUPVolleyErr", error.toString());
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params1 = new HashMap<String, String>();
params1.put("payload", params.toString());
Log.v("updateUPVolleyParams", params1.toString());
return params1;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
mainListView
.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View item,
int position, long id)
{
Services massageservice = listAdapter.getItem(position);
Log.e("CHECKADAPTOR", String.valueOf(massageservice));
massageservice.toggleChecked();
ViewHolder viewHolder =(ViewHolder) item
.getTag();
viewHolder.getCheckBox().setChecked(massageservice.isChecked());
}
});
//Services[] massageService = (Services[]) getLastNonConfigurationInstance();ArrayList<Services> massagelist = new ArrayList<Services>();
//massagelist.addAll(Arrays.asList(massageService));
// Set our custom array adapter as the ListView's adapter.
listAdapter = new massageArrayAdapter(this,massagelist);
mainListView.setAdapter(listAdapter);
check.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
for (int i = 0; i < listAdapter.getCount(); i++)
{
Services massage = listAdapter.getItem(i);
if (massage.isChecked())
{
Toast.makeText(getApplicationContext(),
massage.getName() + " is Checked!!",
Toast.LENGTH_SHORT).show();
Log.v("My Custom Tag", massage.getName());
}
}
}
});
}
//arrayadapter class//
private static class massageArrayAdapter extends ArrayAdapter<Services>
{
private LayoutInflater inflater;
public massageArrayAdapter(Context context, List<Services> massagelist)
{
super(context, R.layout.customlist_massage, R.id.massagetextview, massagelist);
// Cache the LayoutInflate to avoid asking for a new one each time.
inflater = LayoutInflater.from((Context) context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
// services to display
Services massage = (Services) this.getItem(position);
// The child views in each row.
CheckBox checkBox;
TextView textView;
// Create a new row view
if (convertView == null)
{
convertView = inflater.inflate(R.layout.customlist_massage,null );
// Find the child views.
textView = (TextView) convertView
.findViewById(R.id.massagetextview);
checkBox = (CheckBox) `enter code here`convertView.findViewById(R.id.checkBox4);
// Optimization: Tag the row with it's child views, so we don't
// have to
// call findViewById() later when we reuse the row.
convertView.setTag(new ViewHolder(textView, checkBox));
// If CheckBox is toggled, update the planet it is tagged with.
checkBox.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
CheckBox cb = (CheckBox) v;
Services massage = (Services) cb.getTag();
massage.setChecked(cb.isChecked());
}
});
}
// Reuse existing row view
else
{
// Because we use a ViewHolder, we avoid having to call
// findViewById().
ViewHolder viewHolder = (ViewHolder) convertView
.getTag();
checkBox = viewHolder.getCheckBox();
textView = viewHolder.getTextView();
}
// Tag the CheckBox with the service it is displaying,
// access the planet in onClick() when the CheckBox is toggled.
checkBox.setTag(massage);
// Display planet data
checkBox.setChecked(massage.isChecked());
textView.setText(massage.getName());
return convertView;
}
}
}
My Service class used to store services
public class Services
{
private String name = "";
private boolean checked = false;
private String categotry_id="";
public Services()
{
}
public Services(String name)
{
this.name = name;
}
public Services(String name, boolean checked,String categotry_id)
{
this.name = name;
this.categotry_id = categotry_id;
this.checked = checked;
}
public Services(String name,String categotry_id)
{
this.name = name;
this.categotry_id = categotry_id;
}
public String getCategory_id(String id)
{
return categotry_id;
}
public void setcategotry_id(String categotry_id)
{
this.name = categotry_id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public boolean isChecked()
{
return checked;
}
public void setChecked(boolean checked)
{
this.checked = checked;
}
public String toString()
{
return name;
}
public void toggleChecked()
{
checked = !checked;
}
}
View holder class for storing views
public class ViewHolder
{
private CheckBox checkBox;
private TextView textView;
public ViewHolder()
{
}
public ViewHolder(TextView textView, CheckBox checkBox)
{
this.checkBox = checkBox;
this.textView = textView;
}
public CheckBox getCheckBox()
{
return checkBox;
}
public void setCheckBox(CheckBox checkBox)
{
this.checkBox = checkBox;
}
public TextView getTextView()
{
return textView;
}
public void setTextView(TextView textView)
{
this.textView = textView;
}
}
my xml class where list view is there
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#3F51B5">
<ListView
android:id="#+id/listView4"
android:layout_width="match_parent"
android:layout_height="0px"
android:background="#fff"
android:layout_weight="1" >
</ListView>
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="313dp"
android:text="Continue" />
</LinearLayout>
Please help me through this I need to submit this by tomorrow.
Use this
convertView = inflater.inflate(R.layout.customlist_massage,null ,false );
Instead this
convertView = inflater.inflate(R.layout.customlist_massage,null );
Why you are extending the adapter class ArrayAdapter.
If You want to show something on listview you have to extend it to BaseAdapter OR Recyclerview Adapter.
You dont have any getCount() method in ArrayAdapter see this example::
public class Adapter extends BaseAdapter {
LayoutInflater li;
ArrayList<String> title, details;
Context con;
DataBaseHelper db;
TextView txttitle, txtdetails, txtDate;
Intent in;
public static int i = 1;
View view;
public Adapter (Context cont, ArrayList<String> news_id, ArrayList<String> news) {
this.title = news_id;
this.details = news;
this.con = cont;
li = (LayoutInflater) con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
System.out.println("title.size() " + title.size());
return title.size();
}
#Override
public Object getItem(int arg0) {
return arg0;
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
if (arg1 == null) {
arg1 = li.inflate(R.layout.adapter_daycare, null);
txttitle = (TextView) arg1.findViewById(R.id.title);
txtdetails = (TextView) arg1.findViewById(R.id.details);
txtDate = (TextView) arg1.findViewById(R.id.txtdate);
view = (View) arg1.findViewById(R.id.view);
}
String date = new SimpleDateFormat("dd/MM/yyyy").format(new Date());
System.out.println(" formattedDate " + date);
txttitle.setText(title.get(arg0).toString());
txtdetails.setText(details.get(arg0).toString());
txtDate.setText(date);
return arg1;
}
}

image loading using url in android

i was tring to load image using url.a single url is working properly. but i need to add a few more images to this page.i need to add this image s to a list view.pls tell me how can i add a string array to this code.
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class FareCrd extends Activity {
String image_url="http://movito.nervov.com/img/ace-hd.png";
String[] mString ={"http://movito.nervov.com/img/ace-hd.png",
"http://movito.nervov.com/img/Movito_Logo_M.png"};
JSONArray jsonary;
ListView list;
private Activity activity;
private String[] data;
private static View inflater=null;
//private String[] mStrings={"http://movito.nervov.com/img/ace-hd.png"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fare_crd);
list=(ListView)findViewById(R.id.farelist);
new ServConn().execute();
}
private void parsedata(String data){
//System.out.println(data);
try {
JSONObject json = new JSONObject(data);
jsonary = json.getJSONArray("data");
ListView list = (ListView) findViewById(R.id.farelist);
list.setAdapter(new DriverOrderList(getApplicationContext(),
R.layout.farecrd, new JSONObject[jsonary.length()]));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class DriverOrderList extends ArrayAdapter<JSONObject> {
int listViewResource;
public DriverOrderList(Context context, int resource, JSONObject[] s) {
super(context, resource, s);
listViewResource = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(listViewResource, parent, false);
ImageLoader imgLoader = new ImageLoader(getApplicationContext());
JSONObject rowdata = new JSONObject();
int loader = R.drawable.stub;
try {
rowdata = jsonary.getJSONObject(position);
System.out.println(rowdata);
ImageLoader imgLoader1 = new ImageLoader(getApplicationContext());
ImageView img=(ImageView) row.findViewById(R.id.imgid);
imgLoader.DisplayImage(image_url, loader, img);
TextView nameTxt = (TextView) row.findViewById(R.id.truckname);
TextView idTxt = (TextView) row.findViewById(R.id.id);
TextView minrttv =(TextView) row.findViewById(R.id.minimumRate);
TextView kmrttxt =(TextView) row.findViewById(R.id.kilometerRate);
TextView mindurtv=(TextView) row.findViewById(R.id.minimumDuration);
TextView freewatintim = (TextView) row.findViewById(R.id.freeWaitingTime);
TextView minuterttxt =(TextView) row.findViewById(R.id.minuteRate);
TextView watingchrttv =(TextView)row.findViewById(R.id.waitingCharge);
double freewt=(Double) rowdata.get("freeWaitingTime");
double kmratetxt=(Double) rowdata.get("kilometerRate");
double mindurtxt=(Double) rowdata.get("minimumDuration");
double mindur= mindurtxt/60;
double minkmrttxt=(Double) rowdata.get("minimumKilometer");
double minrttxt=(Double) rowdata.get("minimumRate");
double mintrate=(Double) rowdata.get("minuteRate");
double minutrat=mintrate/60;
double watingchrtxt=(Double) rowdata.get("waitingCharge");
double waitchgunittxt=(Double) rowdata.get("waitingChargeUnit");
nameTxt.setText(rowdata.getString("truckModel"));
minrttv.setText("Rs."+minrttxt+" /-");
kmrttxt.setText("Rs."+kmratetxt+"/km after "+minkmrttxt+"km");
mindurtv.setText("first"+mindur+"hr and "+minkmrttxt+"km");
//minuterttxt.setText(minutrat+"/-");
freewatintim.setText("first "+freewt+"min free");
watingchrttv.setText("RS"+watingchrtxt+"after every "+waitchgunittxt+"min");
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return row;
}
}
private class ServConn extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
System.out.println("do in backgrnd");
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://movito.nervov.com/v1/trucks/miniTruckCategories");
httpget.setHeader(HTTP.CONTENT_TYPE, "application/json");
String replyString = "";
try {
HttpResponse response = httpclient.execute(httpget);
replyString = EntityUtils.toString(response
.getEntity());
} catch (ClientProtocolException e) {
System.out.println("ex: " + e);
} catch (IOException e) {
System.out.println("e: " + e);
}
return replyString;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
System.out.println(result);
result = "{\"data\":"+result+"}";
parsedata(result);
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
}
Try to use Glide libreries instead od picasso .It might help full for you.Please look at following link which might help you out.
http://inthecheesefactory.com/blog/get-to-know-glide-recommended-by-google/en
try this code I am using Picasso library to populate ImageView,
if you are using android studio add this library using following code into your gradle file
compile 'com.squareup.picasso:picasso:2.5.2'
use following code,
It is complete example of how you can make a custom ListView, I didn't include code where you have to get he JSON data from WebService as i didn't want to make the code complicated, I will write a separate code where i will show how to read the data you are interested in.
XML
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#+id/CustomListViewActivity_listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
single_item.xml layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">
<TextView
android:id="#+id/single_item_textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:layout_weight="0.5"
android:text="New Text" />
<ImageView
android:id="#+id/single_item_imageView"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="4dp"
android:layout_weight="0.5" />
</LinearLayout>
Code
public class CustomListViewActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_list_view);
ArrayList<SingleItem> singleItems = new ArrayList<>();
singleItems.add(new SingleItem("http://movito.nervov.com/img/ace-hd.png","first Text"));
singleItems.add(new SingleItem("http://movito.nervov.com/img/Movito_Logo_M.png","Second Text"));
singleItems.add(new SingleItem("http://movito.nervov.com/img/ace-hd.png","third Text"));
singleItems.add(new SingleItem("http://movito.nervov.com/img/Movito_Logo_M.png","fourth Text"));
ListView listView = (ListView)findViewById(R.id.CustomListViewActivity_listView);
MyAdapter adapter = new MyAdapter(getApplicationContext(), R.layout.single_item,singleItems);
listView.setAdapter(adapter);
}
private class MyAdapter extends ArrayAdapter {
private ArrayList<SingleItem> singleItems;
private LayoutInflater layoutInflater;
private Context context;
private View single_View;
public MyAdapter(Context context, int resource, ArrayList<SingleItem> singleItems) {
super(context, resource, singleItems);
this.context = context;
this.singleItems = singleItems;
layoutInflater = LayoutInflater.from(this.context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
row = layoutInflater.inflate(R.layout.single_item, parent, false);
holder = new ViewHolder();
holder.textView = (TextView) row.findViewById(R.id.single_item_textView);
holder.imageView = (ImageView) row.findViewById(R.id.single_item_imageView);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final SingleItem singleItem = singleItems.get(position);
holder.textView.setText("" + singleItem.getText());
Picasso.with(context).load(""+singleItem.getUrl()).into(holder.imageView);
return row;
}
private class ViewHolder {
// Instance Variable (state or data)
TextView textView;
ImageView imageView;
}
}
public class SingleItem {
private String url;
private String text;
public SingleItem() {
}
public SingleItem(String url, String text) {
this.url = url;
this.text = text;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
}
Output
As you will see the loading the images from the URL provided to the appropriate ImageView is taken care by Picasso, do make sure you add the permission for the internet in the AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />

Updated views in list item don't stay updated when scrolling through listview[IMG + SOURCE]

The short version of my question: If I have a listview where each item has a button and that button causes a textview on that listitem to be updated, how do I make changes I make to the list row from a onClickListener in getView permanent?
Detailed description of problem: I have a listview and that listview has a "bump" button (equivalent to a "like" button on Facebook) and when a user presses this like button 3 things happen:
A async request is made to my api which records the "bump" by adding a record to one of my db tables. If the request is successful the api issues a response with 2 fields ( is_bumped(boolean) & bump_count(int) )
If the api request was successful then we grab bumpCount from the response and use it to update the bumpTv to reflect the new total number of times that list item has been "bumped".... example: "3 Bumps"
If the API request was successful and isBumped=true then we update the image resource to a version of my bump icon that looks selected/pressed.
All of this works just fine at first glance, but if you "bump" a list item and then scroll all the way to the bottom of the list and then back to the top, the list item you just bumped will no longer appear to be bumped unless you refresh the entire activity. I know this has to have something to do with the data that I bind to the adapter not being updated, but how do I go about updating without refreshing the entire update?
package com.quothor.helpers;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class NewLazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public FragmentManager frag_manager;
static class ViewHolder {
TextView name;
TextView div3;
TextView div2;
TextView bumpTv;
TextView message;
TextView commentsTv;
SmartImageView thumb_image;
ImageButton bumpBtn;
ImageButton requestBtn;
ImageButton settingsBtn;
TextView created ;
int position;
}
public NewLazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public NewLazyAdapter(Activity a, ArrayList<HashMap<String, String>> d, FragmentManager manager) {
activity = a;
frag_manager=manager;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
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;
HashMap<String, String> update = new HashMap<String, String>();
update = data.get(position);
if(convertView==null){
convertView = inflater.inflate(R.layout.list_row, null);
holder = new ViewHolder();
holder.name = (TextView)convertView.findViewById(R.id.name); // title
holder.div3 = (TextView)convertView.findViewById(R.id.divider3); // title
holder.div2 = (TextView)convertView.findViewById(R.id.divider2); // title
holder.bumpTv = (TextView)convertView.findViewById(R.id.bump); // title
holder.message = (TextView)convertView.findViewById(R.id.message); // artist name
holder.commentsTv = (TextView)convertView.findViewById(R.id.comments); // artist name
holder.thumb_image = (SmartImageView) convertView.findViewById(R.id.list_image);
holder.bumpBtn= (ImageButton)convertView.findViewById(R.id.bump_btn);
holder.requestBtn = (ImageButton)convertView.findViewById(R.id.hidden_btn);
holder.settingsBtn = (ImageButton)convertView.findViewById(R.id.settings_btn);
holder.created = (TextView)convertView.findViewById(R.id.created); // duration
holder.bumpBtn.setTag(holder);
holder.bumpBtn.setOnClickListener(new Bump(position, update));
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Log.i("LazyAdapter data", String.valueOf(position)+" "+update.toString());
if(update.get("bump_count") != null){
holder.bumpBtn.setVisibility(holder.bumpBtn.VISIBLE);
//holder.bumpBtn.setOnClickListener(new Bump(position, update));
String bump_count=update.get("bump_count");
String is_bumped=update.get("is_bumped");
//sets bump textview
if(bump_count.equals("0")){
}else if(bump_count.equals("1")){
holder.div3.setVisibility(holder.div3.VISIBLE);
holder.bumpTv.setVisibility(holder.bumpTv.VISIBLE);
holder.bumpBtn.setVisibility(holder.bumpBtn.VISIBLE);
holder.bumpTv.setText(bump_count+" bump");
}else{
holder.div3.setVisibility(holder.div3.VISIBLE);
holder.bumpTv.setVisibility(holder.bumpTv.VISIBLE);
holder.bumpBtn.setVisibility(holder.bumpBtn.VISIBLE);
holder.bumpTv.setText(bump_count+" bumps");
}
if(is_bumped.equals("true")){
holder.bumpBtn.setImageResource(R.drawable.quothor_thumb_blue);
//bumpBtn.setBackgroundResource(R.drawable.quothor_bump_btn_bg_black);
}else{
holder.bumpBtn.setImageResource(R.drawable.quothor_bump_icon_black);
//bumpBtn.setBackgroundResource(android.R.drawable.btn_default);
}
}
if(update.get("relationship_view")!=null){
if(update.get("uid")!=TabHostFragmentActivity.loggedin_uid){
if(update.get("relation_to_user")!=null){
holder.requestBtn.setVisibility(holder.requestBtn.VISIBLE);
String relation= update.get("relation_to_user");
if(relation.equals("Friend")){
holder.settingsBtn.setVisibility(holder.settingsBtn.VISIBLE);
holder.requestBtn.setImageResource(R.drawable.friend_btn);
}else if(relation.equals("Familiar")){
holder.settingsBtn.setVisibility(holder.settingsBtn.VISIBLE);
holder.requestBtn.setImageResource(R.drawable.familiar_btn);
}
holder.requestBtn.setOnClickListener(new myOnClickListener(position));
holder.settingsBtn.setOnClickListener(new myOnClickListener(position));
}
}
}
if(update.get("created") != null){
TextView created = (TextView)convertView.findViewById(R.id.created); // duration
String str_created=update.get("created");
long created_l = Long.parseLong(str_created);
String time_ago=TimeAgo.fromPhpTime(created_l);
created.setVisibility(convertView.VISIBLE);
created.setText(time_ago);
}
if(update.get("comment_count")!=null){
holder.div2.setVisibility(holder.div2.VISIBLE);
holder.commentsTv.setVisibility(holder.commentsTv.VISIBLE);
String comments = update.get("comment_count");
if(comments.equals("0")){
holder.commentsTv.setText("no comments");
}else if(comments.equals("1")){
holder.commentsTv.setText("1 comment");
}else{
holder.commentsTv.setText(comments+ " comments");
}
}else{
holder.commentsTv.setVisibility(holder.commentsTv.INVISIBLE);
}
// Setting all values in listview
holder.name.setText(update.get("name"));
if(update.get("message") != null){
holder.message.setText(update.get("message"));
}else{
holder.message.setVisibility(holder.message.INVISIBLE);
}
holder.thumb_image.setImageUrl(update.get("thumb_img"));
/*
name.setOnClickListener(new myOnClickListener(position));
thumb_image.setOnClickListener(new myOnClickListener(position));
*/
return convertView;
}
public class myOnClickListener implements OnClickListener{
private int position;
private String clicked_uid;
public myOnClickListener(int position){
this.position=position;
}
#Override
public void onClick(View v) {
HashMap<String, String> update = new HashMap<String, String>();
update = data.get(position);
Log.i("Update Position:", update.toString());
clicked_uid=update.get("uid");
Log.d("Clicked UID:", clicked_uid+"");
String relation= update.get("relation_to_user");
String uid = update.get("uid");
String name = update.get("name");
String thumb_img = update.get("thumb_img");
FragmentManager fm = frag_manager;
EditRelationshipDialog editRelationshipDialog = new EditRelationshipDialog().newInstance(uid,relation,name,thumb_img);
editRelationshipDialog.show(fm, "relationshipsdialog");
}
}
public class Bump implements OnClickListener{
private int position;
private String clicked_uid;
public Bump(int position, HashMap<String, String> update){
this.position=position;
}
#Override
public void onClick(View v) {
HashMap<String, String> update = new HashMap<String, String>();
update = data.get(position);
final View theview=v;
Log.i("Update Position:", update.toString());
String msg_id=update.get("msg_id");
//ViewHolder mH = (ViewHolder) theview.getTag();
// mH.message.setText("clicked");
RequestParams params = new RequestParams();
params.put("msg_id", msg_id);
params.put("loggedin_uid", TabHostFragmentActivity.loggedin_uid);
RestClient.post(TabHostFragmentActivity.token,"http://api/bump", params, new JsonHttpResponseHandler() {
#Override
public void onFailure(Throwable arg0, JSONObject arg1) {
// TODO Auto-generated method stub
super.onFailure(arg0, arg1);
Log.i("bump request failed in lazy adapter", arg1.toString());
Toast.makeText(activity.getApplicationContext(), arg1.toString() , Toast.LENGTH_LONG).show();
}
#Override
public void onSuccess(JSONObject json) {
ViewHolder mH = (ViewHolder) theview.getTag();
try {
String is_bumped=json.getString("is_bumped");
String bump_count=json.getString("bump_count");
if(bump_count != null){
if(bump_count.equals("0")){
}else if(bump_count.equals("1")){
mH.div3.setVisibility(mH.div3.VISIBLE);
mH.bumpTv.setVisibility(mH.bumpTv.VISIBLE);
mH.bumpBtn.setVisibility(mH.bumpBtn.VISIBLE);
mH.bumpTv.setText(bump_count+" bump");
}else{
mH.div3.setVisibility(mH.div3.VISIBLE);
mH.bumpTv.setVisibility(mH.bumpTv.VISIBLE);
mH.bumpBtn.setVisibility(mH.bumpBtn.VISIBLE);
mH.bumpTv.setText(bump_count+" bumps");
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
String is_bumped=json.getString("is_bumped");
if(is_bumped.equals("true")){
mH.bumpBtn.setImageResource(R.drawable.quothor_thumb_blue);
//bumpBtn.setBackgroundResource(R.drawable.quothor_bump_btn_bg_black);
}else{
mH.bumpBtn.setImageResource(R.drawable.quothor_bump_icon_black);
//bumpBtn.setBackgroundResource(android.R.drawable.btn_default);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
}
EDIT: After taking the advice in the comments i was sure my list would begin functioning the way I had intended it to , but it only opened up a whole new can of hell....now for some reason if a user clicks the "bump" button anywhere in the first 6 items it works just fine, but beyond that something weird starts happening. when a user hits the bump button on one of the list items below the first 6 items it sends the wrong position and its a position somewhere between 0 and 6 ?!?!?
package com.quothor.helpers;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class NewLazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public FragmentManager frag_manager;
static class ViewHolder {
TextView name;
TextView div3;
TextView div2;
TextView bumpTv;
TextView message;
TextView commentsTv;
SmartImageView thumb_image;
ImageButton bumpBtn;
ImageButton requestBtn;
ImageButton settingsBtn;
TextView created ;
int position;
}
public NewLazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public NewLazyAdapter(Activity a, ArrayList<HashMap<String, String>> d, FragmentManager manager) {
activity = a;
frag_manager=manager;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
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;
HashMap<String, String> update = new HashMap<String, String>();
update = data.get(position);
Log.i("position being scrolled over", String.valueOf(position));
if(convertView==null){
convertView = inflater.inflate(R.layout.list_row, null);
holder = new ViewHolder();
holder.name = (TextView)convertView.findViewById(R.id.name); // title
holder.div3 = (TextView)convertView.findViewById(R.id.divider3); // title
holder.div2 = (TextView)convertView.findViewById(R.id.divider2); // title
holder.bumpTv = (TextView)convertView.findViewById(R.id.bump); // title
holder.message = (TextView)convertView.findViewById(R.id.message); // artist name
holder.commentsTv = (TextView)convertView.findViewById(R.id.comments); // artist name
holder.thumb_image = (SmartImageView) convertView.findViewById(R.id.list_image);
holder.bumpBtn= (ImageButton)convertView.findViewById(R.id.bump_btn);
holder.requestBtn = (ImageButton)convertView.findViewById(R.id.hidden_btn);
holder.settingsBtn = (ImageButton)convertView.findViewById(R.id.settings_btn);
holder.created = (TextView)convertView.findViewById(R.id.created); // duration
holder.bumpBtn.setTag(holder);
holder.bumpBtn.setOnClickListener(new Bump(position, update));
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Log.i("LazyAdapter data", String.valueOf(position)+" "+update.toString());
if(update.get("bump_count") != null){
holder.bumpBtn.setVisibility(holder.bumpBtn.VISIBLE);
//holder.bumpBtn.setOnClickListener(new Bump(position, update));
String bump_count=update.get("bump_count");
String is_bumped=update.get("is_bumped");
//sets bump textview
if(bump_count.equals("0")){
}else if(bump_count.equals("1")){
holder.div3.setVisibility(holder.div3.VISIBLE);
holder.bumpTv.setVisibility(holder.bumpTv.VISIBLE);
holder.bumpBtn.setVisibility(holder.bumpBtn.VISIBLE);
holder.bumpTv.setText(bump_count+" bump");
}else{
holder.div3.setVisibility(holder.div3.VISIBLE);
holder.bumpTv.setVisibility(holder.bumpTv.VISIBLE);
holder.bumpBtn.setVisibility(holder.bumpBtn.VISIBLE);
holder.bumpTv.setText(bump_count+" bumps");
}
if(is_bumped.equals("true")){
holder.bumpBtn.setImageResource(R.drawable.quothor_thumb_blue);
//bumpBtn.setBackgroundResource(R.drawable.quothor_bump_btn_bg_black);
}else{
holder.bumpBtn.setImageResource(R.drawable.quothor_bump_icon_black);
//bumpBtn.setBackgroundResource(android.R.drawable.btn_default);
}
}
if(update.get("relationship_view")!=null){
if(update.get("uid")!=TabHostFragmentActivity.loggedin_uid){
if(update.get("relation_to_user")!=null){
holder.requestBtn.setVisibility(holder.requestBtn.VISIBLE);
String relation= update.get("relation_to_user");
if(relation.equals("Friend")){
holder.settingsBtn.setVisibility(holder.settingsBtn.VISIBLE);
holder.requestBtn.setImageResource(R.drawable.friend_btn);
}else if(relation.equals("Familiar")){
holder.settingsBtn.setVisibility(holder.settingsBtn.VISIBLE);
holder.requestBtn.setImageResource(R.drawable.familiar_btn);
}
holder.requestBtn.setOnClickListener(new myOnClickListener(position));
holder.settingsBtn.setOnClickListener(new myOnClickListener(position));
}
}
}
if(update.get("created") != null){
TextView created = (TextView)convertView.findViewById(R.id.created); // duration
String str_created=update.get("created");
long created_l = Long.parseLong(str_created);
String time_ago=TimeAgo.fromPhpTime(created_l);
created.setVisibility(convertView.VISIBLE);
created.setText(time_ago);
}
if(update.get("comment_count")!=null){
holder.div2.setVisibility(holder.div2.VISIBLE);
holder.commentsTv.setVisibility(holder.commentsTv.VISIBLE);
String comments = update.get("comment_count");
if(comments.equals("0")){
holder.commentsTv.setText("no comments");
}else if(comments.equals("1")){
holder.commentsTv.setText("1 comment");
}else{
holder.commentsTv.setText(comments+ " comments");
}
}else{
holder.commentsTv.setVisibility(holder.commentsTv.INVISIBLE);
}
// Setting all values in listview
holder.name.setText(update.get("msg_id"));
if(update.get("message") != null){
holder.message.setText(update.get("message"));
}else{
holder.message.setVisibility(holder.message.INVISIBLE);
}
holder.thumb_image.setImageUrl(update.get("thumb_img"));
/*
name.setOnClickListener(new myOnClickListener(position));
thumb_image.setOnClickListener(new myOnClickListener(position));
*/
return convertView;
}
public class myOnClickListener implements OnClickListener{
private int position;
private String clicked_uid;
public myOnClickListener(int position){
this.position=position;
}
#Override
public void onClick(View v) {
HashMap<String, String> update = new HashMap<String, String>();
update = data.get(position);
Log.i("Update Position:", update.toString());
clicked_uid=update.get("uid");
Log.d("Clicked UID:", clicked_uid+"");
String relation= update.get("relation_to_user");
String uid = update.get("uid");
String name = update.get("name");
String thumb_img = update.get("thumb_img");
FragmentManager fm = frag_manager;
EditRelationshipDialog editRelationshipDialog = new EditRelationshipDialog().newInstance(uid,relation,name,thumb_img);
editRelationshipDialog.show(fm, "relationshipsdialog");
}
}
public class Bump implements OnClickListener{
private int position;
private String clicked_uid;
public Bump(int position, HashMap<String, String> update){
this.position=position;
}
#Override
public void onClick(View v) {
HashMap<String, String> update = new HashMap<String, String>();
update = data.get(position);
final View theview=v;
Log.i("POSITION BEING CLICKED",String.valueOf(position));
Log.i("Update Position:", update.toString());
String msg_id=update.get("msg_id");
Log.i("msg_id",msg_id);
//ViewHolder mH = (ViewHolder) theview.getTag();
// mH.message.setText("clicked");
RequestParams params = new RequestParams();
params.put("msg_id", msg_id);
params.put("loggedin_uid", TabHostFragmentActivity.loggedin_uid);
RestClient.post(TabHostFragmentActivity.token,"http://api/content/bump", params, new JsonHttpResponseHandler() {
#Override
public void onFailure(Throwable arg0, JSONObject arg1) {
// TODO Auto-generated method stub
super.onFailure(arg0, arg1);
Log.i("bump request failed in lazy adapter", arg1.toString());
Toast.makeText(activity.getApplicationContext(), arg1.toString() , Toast.LENGTH_LONG).show();
}
#Override
public void onSuccess(JSONObject json) {
ViewHolder mH = (ViewHolder) theview.getTag();
HashMap<String, String> latestUpdate = new HashMap<String, String>();
latestUpdate = data.get(position);
Log.i("list item being edited", latestUpdate.toString());
try {
String bump_count=json.getString("bump_count");
if(bump_count != null){
latestUpdate.put("bump_count", bump_count);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
String is_bumped=json.getString("is_bumped");
latestUpdate.put("is_bumped", is_bumped);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
data.remove(position);
data.add(position, latestUpdate);
notifyDataSetChanged();
}
});
}
}
}
In the question's comments, it was established that even though the UI was being updated (based on user interaction), the underlying data used by adapter's getView() weren't.
Solution: Update the data source and call notifyDataSetChanged() on the adapter. Let getView() handle UI updates.
Read through the comments for more information.

Android unsorted List

I have created a listActivity with my own ListAdapter. The problem is that the list is viewed in order once launched. But When I scroll down, or go back from another activity, the listView is completely out of order.
I thought the problem was in ArrayList but no, the list is sorted and i'm sure of it because when I loop over all elements in the ArrayList they are printed in the log the same way I inserted them.
I pasted the adapter code below in case anyone would like to check it.
package com.anubis.mail;
import java.util.ArrayList;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
public class EmailAdapter extends BaseAdapter {
private ArrayList<EmailModel> elements;
private Context c;
public EmailAdapter(Context c, ArrayList<EmailModel> Emails) {
this.elements = Emails;
this.c = c;
}
public int getCount() {
return elements.size();
}
public Object getItem(int position) {
return elements.get(position);
}
public long getItemId(int id) {
return id;
}
public void Remove(int id) {
notifyDataSetChanged();
}
public void Add(EmailModel email) {
this.elements.add(email);
for (EmailModel e : elements){
Log.v("EmailAdapter", e.getSubject());
}
notifyDataSetChanged();
}
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout rowLayout;
EmailModel email = elements.get(position);
if (convertView == null) {
rowLayout = (LinearLayout) LayoutInflater.from(c).inflate (R.layout.inbox_item, parent, false);
TextView subject_textview = (TextView)rowLayout.findViewById(R.id.subject_textview);
subject_textview.setText(email.getSubject());
String body_hint = " - " + email.getBodyHint();
TextView bodyhint_textview = (TextView)rowLayout.findViewById(R.id.body_hint_textview);
bodyhint_textview.setText(body_hint);
String sender_name = get_sender_name(email.getSender());
TextView sender_name_textview = (TextView)rowLayout.findViewById(R.id.sender_textview);
sender_name_textview.setText(sender_name);
TextView date_time_textview = (TextView)rowLayout.findViewById(R.id.date_time_textview);
date_time_textview.setText(email.getTime());
} else {
rowLayout = (LinearLayout) convertView;
}
return rowLayout;
}
private String get_sender_name(String from) {
String[] sender = from.split("<");
String sender_name;
try {
sender_name = sender[0];
} catch (Exception e) {
sender_name = sender[1];
}
return sender_name;
}
}
You need to move code after the IF
if (convertView == null) {
rowLayout = (LinearLayout) LayoutInflater.from(c).inflate (R.layout.inbox_item, parent, false);
} else {
rowLayout = (LinearLayout) convertView;
}
TextView subject_textview = (TextView)rowLayout.findViewById(R.id.subject_textview);
subject_textview.setText(email.getSubject());
String body_hint = " - " + email.getBodyHint();
TextView bodyhint_textview = (TextView)rowLayout.findViewById(R.id.body_hint_textview);
bodyhint_textview.setText(body_hint);
String sender_name = get_sender_name(email.getSender());
TextView sender_name_textview = (TextView)rowLayout.findViewById(R.id.sender_textview);
sender_name_textview.setText(sender_name);
TextView date_time_textview = (TextView)rowLayout.findViewById(R.id.date_time_textview);
date_time_textview.setText(email.getTime());
return rowLayout;

Categories

Resources