customAdapter not working properly with asynchronous image download - android

Hey guys i am trying to create a custom listview with text and images where images are coming from a url. i am trying to display them asynchronously with my list items. but as i scroll down the list, the image in list items changes and wrong images are displayed in listitems. Below is my code snippet:
CustomList.java,
it is implimenting my base adapter
public class CustomList extends BaseAdapter {
//private ArrayList listData;
private LayoutInflater layoutInflater;
private ArrayList<ListItem> listData;
public CustomList(Context context,ArrayList<ListItem> listData)
{
//Toast.makeText(History.this,"hey",Toast.LENGTH_LONG).show();
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
Log.e("mysize",String.valueOf(listData.size()));
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView,ViewGroup parent)
{
ViewHolder holder;
if(convertView == null)
{
convertView = layoutInflater.inflate(R.layout.history_row,null);
holder = new ViewHolder();
holder.so = (TextView)convertView.findViewById(R.id.SO);
holder.name = (TextView)convertView.findViewById(R.id.Name);
holder.process = (ImageView)convertView.findViewById(R.id.Process);
holder.cloth = (ImageView)convertView.findViewById(R.id.Cloth);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
ListItem data = (ListItem)listData.get(position);
holder.so.setText(data.getSo());
if(data.getProcess().equals("0"))
{
holder.process.setImageResource(R.drawable.tick);
}
else
holder.process.setImageResource(android.R.drawable.ic_delete);
if(holder.cloth !=null)
{
holder.name.setText(data.getName());
Log.e("urlsss",data.getUrl()+ data.getName());
new ImageDownload(holder.cloth).execute(data.getUrl());
}
return convertView;
}
static class ViewHolder
{
TextView so;
TextView name;
ImageView process;
ImageView cloth;
}
}
ImageDownload.class for downloading images
public class ImageDownload extends AsyncTask<String,Void,Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public ImageDownload(ImageView imageView)
{
imageViewReference = new WeakReference<ImageView>(imageView);
}
protected Bitmap doInBackground(String... params)
{
RequestHandler rh = new RequestHandler();
return rh.downloadBitmap(params[0]);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
Drawable placeholder = imageView.getContext().getResources().getDrawable(android.R.drawable.star_on);
imageView.setImageDrawable(placeholder);
}
}
}
}
}
ListItem.java that is producing my data for each row in listView
public class ListItem {
private String so,name,process,imgUrl;
public void setSo(String so)
{
this.so = so;
}
public void setName(String name)
{
this.name = name;
}
public void setProcess(String process)
{
this.process = process;
}
public void setUrl(String url)
{
this.imgUrl = url;
}
public String getSo()
{
return so;
}
public String getName()
{
return name;
}
public String getProcess()
{
return process;
}
public String getUrl()
{
return imgUrl; }
}
This is my main activity where custom-adapter is called
public class History extends AppCompatActivity {
//url to fetch data from
public static final String URL_HISTORY = "http://192.168.1.233/vendor/history.php";
//Json tags
public static final String TAG_JSON_ARRAY="result";
public static final String TAG_SO = "SO";
public static final String TAG_NAME = "CustomerName";
public static final String TAG_DESC = "ClothDescription";
public static final String TAG_DATE = "DeliveryDate";
public static final String TAG_PRODUCT_TYPE = "ProductType";
public static final String TAG_PRODUCT_DESC = "ProductDescription";
public static final String TAG_IMAGE_URL = "ImageUrl";
public static final String TAG_PROCESS = "Process";
HashMap<String,String> data = new HashMap<>();
ArrayList<ListItem> detail_list;
ListView listView;
//key to put in hashmap
public static final String VENDOR_NAME = "Username";
//to store fetched data
String[] so;
String[] customerName;
String[] clothesDesc;
String[] delivDate;
String[] prodType;
String[] prodDesc;
String[] imgUrl;
String[] process;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
listView =(ListView)findViewById(R.id.listView);
detail_list = new ArrayList<ListItem>();
//to get vendorname
SharedPreferences sharedPref = getSharedPreferences("vendorInfo", Context.MODE_PRIVATE);
String vendor_name =sharedPref.getString("username", "");
data.put(VENDOR_NAME, vendor_name);
fetchHistory();
}
public void fetchHistory()
{
class FetchHistory extends AsyncTask<Void,Void,String>
{
ProgressDialog loading;
protected void onPreExecute()
{
super.onPreExecute();
loading = ProgressDialog.show(History.this,"Fetching...","Wait",false,false);
}
protected String doInBackground(Void...params)
{
RequestHandler rh = new RequestHandler();
String result = rh.sendPostRequest(URL_HISTORY, data);
return result;
}
protected void onPostExecute(String s)
{
super.onPostExecute(s);
loading.dismiss();
Log.e("myjson",s);
showHistory(s);
}
}
FetchHistory fh = new FetchHistory();
fh.execute();
}
public void showHistory(String json)
{
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray result = jsonObject.getJSONArray(TAG_JSON_ARRAY);
int length = result.length();
so = new String[length];
customerName = new String[length];
clothesDesc = new String[length];
delivDate = new String[length];
prodType = new String[length];
prodDesc = new String[length];
imgUrl = new String[length];
process = new String[length];
for (int i = 0; i < result.length(); i++) {
JSONObject c = result.getJSONObject(i);
so[i] = c.getString(TAG_SO);
customerName[i] = c.getString(TAG_NAME);
clothesDesc[i] = c.getString(TAG_DESC);
delivDate[i] = c.getString(TAG_DATE);
prodType[i] = c.getString(TAG_PRODUCT_TYPE);
prodDesc[i] = c.getString(TAG_PRODUCT_DESC);
imgUrl[i] = c.getString(TAG_IMAGE_URL);
process[i] = c.getString(TAG_PROCESS);
}
}
catch(JSONException e)
{
Log.e("myexception",e.toString());
}
for(int i =0;i<customerName.length;i++)
{
//storing all value in hashmap
ListItem values = new ListItem();
values.setSo(so[i]);
values.setName(customerName[i]);
values.setUrl(imgUrl[i]);
Log.e("myurl", imgUrl[i]);
values.setProcess(process[i]);
detail_list.add(values);
}
Toast.makeText(this,"hey",Toast.LENGTH_LONG).show();
Log.e("hey", "hey00");
CustomList customList = new CustomList(this,detail_list);
listView.setAdapter(customList);
Toast.makeText(this,"you",Toast.LENGTH_LONG).show();
Log.e("you", "you00");
}
}
My layout file for each row is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/linear">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/SO"
android:layout_marginRight="10dp"
android:layout_weight="2" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/Name"
android:layout_marginRight="10dp"
android:layout_weight="2" />
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/Process"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/Cloth"
android:layout_weight="1"
android:scaleType="fitXY" />
</LinearLayout>
</LinearLayout>

This is a common mistake. Your listView recycles views, so instead of creating views for the 100 items in your listView, it just creates enough to fill up the screen.
As you scroll down, that ImageView that was used for position #1, is now the same ImageView being used for position #11, and #21, and so on...
The fix require tracking what positions are currently being displayed to the user, and only setting images for those positions, and clearing the associated imageview (or cancelling the pending download) when it falls off the screen.
You can figure out when your imageView gets reassigned because it will be called in getView again, and from there you can figure out if it has a pending download you need to cancel.
Consider using one of the existing solutions or just checking out how others have done it for a full example. https://github.com/nostra13/Android-Universal-Image-Loader

Related

Json parsing using Listview in Android using Ayntask

Hi there I want to get data from a table through API using following query
select * from Order as O where username=O.username;
my Asyntask code is :
protected String doInBackground(Void... params) {
String data = "";
//login doesnt exist
final String url = Data.server + "/Order.aspx";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("username", mEmail));
UrlEncodedFormEntity uefa = null;
try {
uefa = new UrlEncodedFormEntity(param);
post.setEntity(uefa);
HttpResponse response;
response = client.execute(post);
HttpEntity entity = response.getEntity();
data = EntityUtils.toString(entity);
} catch (IOException e) {
// TODO Auto-generated catch block
data = e.toString();
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String success) {
mAuthTask = null;
showProgress(false);
if (success.contains("[{") && (success.length() > 5)) {
//start the profile activity if json is returned
LocalRegistryreg(success);
try {
JSONArray jarr = new JSONArray(res);
ArrayAdapter<jarr> adapter = new ArrayAdapter<jarr>(this,
android.R.layout.simple_list_item_1, items);
scourseslist.setAdapter(adapter);
for (int i = 0; i < jarr.length(); ++i) {
// Extract values from JSON row:
JSONObject jsonObject = jarr.getJSONObject(i);
String PID = jsonObject.has("PID ") ? jsonObject.getString("PID ") : "";
String PTitle = jsonObject.has("PTitle ") ? jsonObject.getString("PTitle ") : "";
String Quantity = jsonObject.has("Quantity ") ? jsonObject.getString("Quantity ") : "";
String Price = jsonObject.has("Price ") ? jsonObject.getString("Price ") : "";
}
} catch (JSONException e) {
e.printStackTrace();
}
finish();
//Utility.shoAlert(success,LoginActivity.this);
} else {
Utility.shoAlert(success, Order.this);
}
}
im storing return json in a string variable String data;and my data look like this
and the data is multi row. i want to show up all my data row using listview. i treied but i got error. so kindly provide a piece of code to show my data in listview?
You need to define a class to hold the data:
public class Order {
private String pID;
private String pTitle;
private String quantity;
private String price;
public Order(String pID, String pTitle, String quantity, String price) {
this.pID = pID;
this.pTitle = pTitle;
this.quantity = quantity;
this.price = price;
}
public String getpID() {
return pID;
}
public void setpID(String pID) {
this.pID = pID;
}
public String getpTitle() {
return pTitle;
}
public void setpTitle(String pTitle) {
this.pTitle = pTitle;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
you need to create a custom adapter class:
public class OrderAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<Order> orderList = new ArrayList<Order>();
private static LayoutInflater inflater = null;
public OrderAdapter(Activity activity, ArrayList<Order> orderList,
Resources res) {
this.activity = activity;
this.orderList = orderList;
// Layout inflator to call external xml layout ()
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return orderList.size();
}
#Override
public Order getItem(int arg0) {
// TODO Auto-generated method stub
return orderList.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder {
public TextView text1;
public TextView text2;
public TextView text3;
public TextView text4;
public TextView text5;
}
/****** Depends upon data size called for each row , Create each ListView row *****/
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder;
if (convertView == null) {
view = inflater.inflate(R.layout.tabitem, null);
holder = new ViewHolder();
holder.text1 = (TextView) view.findViewById(R.id.text1);
holder.text1 = (TextView) view.findViewById(R.id.text2);
holder.text2 = (TextView) view.findViewById(R.id.text3);
holder.text4 = (TextView) view.findViewById(R.id.text4);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
Order order = (Order) orderList.get(position);
/************ Set Model values in Holder elements ***********/
holder.text1.setText(order.getpID());
holder.text2.setText(order.getPrice());
holder.text3.setText(order.getpTitle());
holder.text4.setText(order.getQuantity());
return view;
}
}
create a custom row layout with name tabitem:
<?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="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TextView>
<TextView
android:id="#+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TextView>
<TextView
android:id="#+id/text3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TextView>
<TextView
android:id="#+id/text4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TextView>
</LinearLayout>
Define ListView to show data:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</RelativeLayout>
Than you need to create instance of the class and set the data in your on onPostExecute method.
Order order = new Order(PID, PTitle,Quantity, Price);
List<Order> orderList = new ArrayList<Order>();
and than pass that list of order data to activity, and activity can than apply adapter to show the data:
ListView list= (ListView) findViewById(R.id.list); // List defined in XML
OrderAdapter orderAdapter = OrderAdapter(activity, orderList);
list.setAdapter(orderAdapter );
I don't want to make it harder for you, but it could save you a lot of work and provide more flexibility in the future: Retrofit

displaying picture using JSON and Coverflow Library

I have problem while diplayin pictures , nothing is dsplayed in the sceen , seems empty only data are displayed no pictures. I think that the problem while parsing JSON Data in pictures.
here in the Fragment of the hotel where i want to display picture gallery.
public class ViewHotels extends AppCompatActivity {
private Bitmap bitmap;
private TextView nom1;
private TextView grade;
private TextView tele;
private ImageView image;
private TextView sit;
private TextView add1;
private TextView email1;
private FloatingActionButton fab;
LinearLayout layout;
private String id;
public static final String URL="http://gabes.comlu.com/Base_Controle/getEmpdetail.php";
private FeatureCoverFlow coverFlow;
private CoverFlowAdapter adapter;
private ArrayList<Game> games;
String image2;
String addresses;
String subject;
public static final String TAG_JSON_ARRAY="result";
ImageView im;
private int imageSource;
public String stringUrl;
public String stringUrl1;
public String stringUrl2;
public String stringUrl3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hotelsdetails);
final Intent intent = getIntent();
layout=(LinearLayout) findViewById(R.id.layout);
coverFlow = (FeatureCoverFlow) findViewById(R.id.coverflow);
settingDummyData();
adapter = new CoverFlowAdapter(this, games);
coverFlow.setAdapter(adapter);
coverFlow.setOnScrollPositionListener(onScrollListener());
id = intent.getStringExtra("Type");
nom1 = (TextView) findViewById(R.id. nom);
grade = (TextView) findViewById(R.id. grade);
tele = (TextView) findViewById(R.id. tele);
image= (ImageView)findViewById(R.id.imageView);
sit=(TextView) findViewById(R.id.site);
add1=(TextView) findViewById(R.id.adde);
email1=(TextView)findViewById(R.id.email);
nom1.setText(id);
im =new ImageView (this);
getEmployee();
}
private void getEmployee(){
final String login11 = nom1.getText().toString().trim();
class GetEmployee extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ViewHotels.this,"Fetching...","Wait...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
showEmployee(s);
}
#Override
protected String doInBackground(Void... v) {
HashMap<String,String> params = new HashMap<>();
params.put("id",login11)
RequestHandler rh = new RequestHandler();
String res= rh.sendPostRequest(URL, params);
return res;
}
}
GetEmployee ge = new GetEmployee();
ge.execute();
}
private void showEmployee(String json){
try {
JSONArray result = new JSONArray(json);
JSONObject c = result.getJSONObject(0);
String name = c.getString("nom");
String tel = c.getString("tele");
String grade1 = c.getString("grade");
String image1 = c.getString("image");
image2 = c.getString("img1");
String image3 = c.getString("img2");
String image4 = c.getString("img3");
String site= c.getString("site");
String add11= c.getString("add");
String email11= c.getString("email");
tele.setText("Tel : \t"+tel);
grade.setText("Grade : \t"+grade1);
sit.setText("site: \t"+site);
add1.setText("adresse :\t" + add11);
email1.setText("email :\t"+ email11);
final ImageView im1 =new ImageView (this);
final ImageView im2 =new ImageView (this);
final ImageView im3 =new ImageView (this);
stringUrl = ("http://gabes.comlu.com/Base_Controle/ImageBD/"+image1+".jpg");
stringUrl1 = ("http://gabes.comlu.com/Base_Controle/ImageBD/"+image2+".jpg");
stringUrl2 = ("http://gabes.comlu.com/Base_Controle/ImageBD/"+image3+".jpg");
stringUrl3 = ("http://gabes.comlu.com/Base_Controle/ImageBD/"+image4+".jpg");
} catch (JSONException e) {
e.printStackTrace();
}
}
private FeatureCoverFlow.OnScrollPositionListener onScrollListener() {
return new FeatureCoverFlow.OnScrollPositionListener() {
#Override
public void onScrolledToPosition(int position) {
Log.v("ViewHotels", "position: " + position);
}
#Override
public void onScrolling() {
Log.i("ViewHotels", "scrolling");
}
};
}
private void settingDummyData() {
games = new ArrayList<>();
Game game1 = new Game("stringUrl","");
Game game2 = new Game("stringUrl1","");
Game game3 = new Game("stringUrl2","");
games.add(game1);
games.add(game2);
games.add(game3);
}
}
Here is the coverFlow adapter :
public class CoverFlowAdapter extends BaseAdapter {
private ArrayList<Game> data;
private AppCompatActivity activity;
public CoverFlowAdapter(AppCompatActivity context, ArrayList<Game> objects) {
this.activity = context;
this.data = objects;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Game getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_flow_view, null, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
try {
URL myFileUrl = new URL(data.get(position).getImageSource());
Log.e("TAG stringUri",myFileUrl+"" );
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
viewHolder.gameImage.setImageBitmap(BitmapFactory.decodeStream(is));
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
//viewHolder.gameImage.setImageResource(data.get(position).getImageSource());
viewHolder.gameName.setText(data.get(position).getName());
return convertView;
}
private static class ViewHolder {
private TextView gameName;
private ImageView gameImage;
public ViewHolder(View v) {
gameImage = (ImageView) v.findViewById(R.id.image);
gameName = (TextView) v.findViewById(R.id.name);
}
}
}
And this the Game class :
public class Game {
private String name;
private String imageSource;
public Game (String imageSource, String name) {
this.name = name;
this.imageSource = imageSource;
}
public String getName() {
return name;
}
public String getImageSource() {
return imageSource;
}
}
I think (one of) your problem(s) is this part:
Game game1 = new Game("stringUrl","");
Game game2 = new Game("stringUrl1","");
Game game3 = new Game("stringUrl2","");
You are handing over the String "stringUrlx" to your Game-constructor.
In Java, quotation marks("") are used to explicitly define a string, which means that you are handing over "stringUrl" instead of the variable stringUrl, which would have the correct content ("http://gabes.comlu.com/Base_Controle/ImageBD/"+image1+".jpg").
so replace e.g.
Game game1 = new Game("stringUrl","");
by
Game game1 = new Game(stringUrl,"");
That should solve that one issue.
Other than that, you will also run into issues downloading your files and with memory management. I advise you to look into java specific tutorials, which use pre-built asynchronous image loading and caching libraries (such as Glide or Picasso !)

Can not understand how to get the value from setters and getters class

I am parsing json data and displaying in custom ListView using BaseAdapter. I have no problem in parsing the data. Also don't have any problem setting the data to ModelClass.java (setters and getters class) only question is how to get the data from ModelClass.java. Please help.
This is my MainActivity.java
public class MainActivity extends ActionBarActivity {
// url to make request(to get the latest 20 feeds).
private static String url = "http;.....";
// JSON Node names
private static final String TAG_BODY = "body";
private static final String TAG_CREATED_AT = "created_at";
private static final String TAG_DATE_TIME = "date_time";
private static final String TAG_DEPARTEMENT = "department";
private static final String TAG_ID = "id";
private static final String TAG_INCLUDE = "include";
private static final String TAG_MEDI_TYPE = "mediaType";
private static final String TAG_PRIORITY = "priority";
private static final String TAG_TITLE = "title";
private static final String TAG_UPDATED_AT = "updated_at";
private static final String TAG_USER_ID = "user_id";
ProgressDialog progressDialog;
ListView listViewFeeds;
// String mTitle, mBody;
List<ModelClass> model = new ArrayList<ModelClass>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* To display the feed */
listViewFeeds = (ListView) findViewById(R.id.listViewFeeds);
listViewFeeds.setAdapter(new NewAdapter(this));
Feeds feeds = new Feeds();
feeds.execute();
}
public class Feeds extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("Loading ...");
progressDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Accept", "application/json");
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
StatusLine statusLine = httpResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode != 200) {
return null;
}
HttpEntity httpEntity = httpResponse.getEntity();
InputStream inputStream = httpEntity.getContent();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
String jsonData = stringBuilder.toString();
// Displaying json data in logcat.
Log.d("Latest 20 feeds", jsonData);
JSONArray array = new JSONArray(jsonData);
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
String mTitle = object.getString("title");
String mBody = object.getString("body");
System.out.println("Titlte: " + mTitle);
System.out.println("Body: " + mBody);
// Setting the data to ModelClass
ModelClass mc = new ModelClass(mTitle, mBody);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
super.onPostExecute(result);
}
}
}
class NewAdapter extends BaseAdapter {
ArrayList<ModelClass> list;
Context context;
NewAdapter(Context c) {
context = c;
}
#Override
public int getCount() {
return 0;
// 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) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_row_feed_view, parent,
false);
TextView title = (TextView) row.findViewById(R.id.textViewTitleFeeds);
TextView body = (TextView) row.findViewById(R.id.textViewBody);
ModelClass temp = list.get(position);
title.setText(temp.title);
body.setText(temp.body);
return row;
}
}
This is my ModelClass.java
public class ModelClass {
String title;
String body;
ModelClass(String title, String body) {
this.title = title;
this.body = body;
}
}
activity_main.xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/listViewFeeds"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
single_row_feed_view.xml file(row appears in ListView)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textViewTitleFeeds"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/viewColor"
android:ellipsize="end"
android:maxLines="2"
android:text="TextView"
android:textSize="12dp" />
<TextView
android:id="#+id/textViewBody"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textViewTitleFeeds"
android:layout_marginTop="3dp"
android:ellipsize="end"
android:maxLines="2"
android:text="TextView"
android:textSize="8dp" />
</RelativeLayout>
Its a bit hard to work out the exact question because you are asking how to get the value from setters and getters class but your ModelClass has no getters or setters.
You can put getters into your ModelClass, but you may not technically need them if its in the same package.
You should look at this tutorial. It helped me a lot.
http://www.vogella.com/tutorials/AndroidListView/article.html
Is this what you're asking for?
//Inside your Model class:
public String getTitle(){
return this.title;
}
public String setTitle(String givenTitle){
this.title = givenTitle;
}
public String getBody(){
return this.body;
}
public String setTitle(String givenBody){
this.body = givenBody;
}
As others have mentioned you need to put getters and setters in your model class. In terms of putting the values in a list and formatting the list item, then you need a custom list adapter. Then create a list of the items you want to put in the list adapter.. then show the list. Below is an example.
enter code here
public class ExampleListAdapter extends ArrayAdapter<ExampleModel> {
private Context context;
private ArrayList<ExampleModel> items;
public ExampleListAdapter(Context context, ArrayList<ExampleModel> items) {
super(context, R.id.result_list_item_direction_icon, items);
this.context = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = null;
View rowView = convertView;
//Get rowView from inflater
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.id.yourcustom_layout, parent, false);
// Get reference ids from the rowView
//example
TextView item = (TextView) rowView.findViewById(R.id.itemID);
// Set the values for items in custom list view
item.setText(items.get(position).yourGetter());
return rowView;
}
}
then in the in the class you want to use it…
enter code here
ArrayList<t> yourList = new ArrayList<t>();
yourList = getValuesFromDBOROtherSource;//make sure the return value is list!
yourCustomAdapter = new ExampleListAdapter(getActivity(), yourList);
setListAdapter(yourCustomAdapter);

Android GridView Adapter using ArrayList

I'm stuck creating an Adapter for my Griview that accepts an ArrayList. I think the bad line in the Adapter class is: viewHldr.wcbc_image_iv.setImageResource(urlStrArrList.get(position)); and it appears that the call .setImageResource is the problem.
public class JGrid66 extends Activity {
JSONObject jsonOb;
JSONArray JSArrGallery = null;;
GridView grid65_gv;
JGrid66Adapter2 jGr7Adap;
ProgressDialog mProgressDialog;
ArrayList<String> idStrArrList = new ArrayList<String>();
ArrayList<String> urlStrArrList = new ArrayList<String>();
ArrayList<String> descrStrArrList = new ArrayList<String>();
// JSON Node names
private static final String TAG_GALLERY = "gallery";
private static final String TAG_GALLERYURL = "galleryurl";
private static final String TAG_ID = "id";
private static final String TAG_GALLERYDESCR = "gallerydescr";
static String FLAG = "flag";
private String jsonUrl = "http://www.mysite.com/apps/wcbc/galleryuil.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jgrid66);
grid65_gv = (GridView) findViewById(R.id.jgrid66_gv);
}//--- END onCreate
//--- DownloadJSON Class
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
JGrid4Adapter jParser = new JGrid4Adapter();
// getting JSON string from URL
JSONObject jsonOb = jParser.getJSONFromUrl(jsonUrl);
try {
JSArrGallery = jsonOb.getJSONArray(TAG_GALLERY);
// looping through All gallery images
for (int i = 0; i < JSArrGallery.length(); i++) {
JSONObject galleryJO = JSArrGallery.getJSONObject(i);
String idStr = galleryJO.getString(TAG_ID);
String urlStr = galleryJO.getString(TAG_GALLERYURL);
String descrStr = galleryJO.getString(TAG_GALLERYDESCR);
idStrArrList.add(idStr);
urlStrArrList.add(urlStr);
descrStrArrList.add(descrStr);
}// -- END for loop
} catch (JSONException e) {
e.printStackTrace();
}// --- END Try
return null;
}
#Override
protected void onPostExecute(Void args) {
jGr7Adap = new JGrid66Adapter2(JGrid66.this, urlStrArrList);
grid65_gv.setAdapter(jGr7Adap);
jGr7Adap.notifyDataSetChanged();
}
}
//--- END DownloadJSON Class
}
Here;s the Adapter:
public class JGrid66Adapter2 extends BaseAdapter {
private ArrayList<String> urlStrArrList;
Context context;
public JGrid66Adapter2(Context context,ArrayList<String> urlStrArrList) {
super();
this.urlStrArrList = urlStrArrList;
}
#Override
public int getCount() {
return urlStrArrList.size();
}
#Override
public String getItem(int position) {
return urlStrArrList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public static class ViewHolder
{
public ImageView wcbc_image_iv;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHldr;
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
if(convertView==null){
viewHldr = new ViewHolder();
convertView = inflater.inflate(R.layout.jgrid66_item, null);
viewHldr.wcbc_image_iv = (ImageView) convertView.findViewById (R.id.jgrid66_iv);
convertView.setTag(viewHldr);
}
else
{
viewHldr = (ViewHolder) convertView.getTag();
}
//--- I commented this out because this is where it breaks.
//viewHldr.wcbc_image_iv.setImageResource(urlStrArrList.get(position));
return convertView;
}
}
Any help would be great!
private ArrayList<String> urlStrArrList;
is arraylist of strings. If you have the url you need to download the images and then set it to imageview.
setImageResource takes a resource id as a param which is an int value.
public void setImageResource (int resId)
Added in API level 1
Sets a drawable as the content of this ImageView.
You may consider using Lazy Loading Universal Image Loader or using picasso
Caching images and displaying

Listview doesnot scroll in tabhost

In my app i have tabhost in which i am displaying list view.I cant scroll my listview and when i try to scroll color of listview changes but doesnot scroll.Here are pictures
when i try to scroll its color changes
My SearchDictionaryActivity.java is
public class SearchDictionaryActivity extends Activity{
Intent intent;
// Progress Dia//Log
private ProgressDialog pDialog;
DataHolder obj;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
private boolean enablePopup = true;
// Listview Adapter
ArrayAdapter<String> adapter;
//ArrayList<String> categories=new ArrayList<String>();
// catgories JSON url
private static String url_all_products;
// JSON Node names It should be same on srver(encodeing) and client(decoding)
private static final String TAG_SUCCESS = "success";
private static final String TAG_products = "Products";
private static final String TAG_Image = "Image";
private static final String TAG_NAME = "name";
// category JSONArray
JSONArray category = null;
// flag for Internet connection status
Boolean isInternetPresent = false;
EditText edittext;
ListView listview;
ArrayList<String> text_sort = new ArrayList<String>();
ArrayList<Bitmap> image_sort = new ArrayList<Bitmap>();
String ITEMTITLE ="HasMapValue";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_dictionary);
url_all_products=getString(R.string.url_ip);
url_all_products=url_all_products+"get_list_of_name_of_products.php";
new LoadCategories().execute();
edittext = (EditText) findViewById(R.id.EditText01);
listview = (ListView) findViewById(R.id.ListView01);
}
/**
* Background Async Task to Load all catgories by making HTTP Request
* */
class LoadCategories extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
Bitmap decodedByte;
//ArrayList<HashMap<String, Object>> productsList=new ArrayList<HashMap<String,Object>>();
String[] text = new String[0];
Bitmap[] image = new Bitmap[0];
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchDictionaryActivity.this);
pDialog.setMessage("Loading ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting catgories JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
//Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Categorys
category = json.getJSONArray(TAG_products);
//Log.i("category ", category.toString());
//Log.i("Lengt Category"," " +category.length());
// looping through All Categories
for (int i = 0; i < category.length(); i++) {
JSONObject c = category.getJSONObject(i);
//Log.i("JSONObject ", c.toString());
// Storing each json item in variable
String name = c.getString(TAG_NAME);
String ProductImage = c.getString(TAG_Image);
//Log.i("StrineName ", name);
byte[] decodedString = Base64.decode(ProductImage, Base64.DEFAULT);
decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
//HashMap<String, Object> map = new HashMap<String, Object>();
text=reallocation(text);
image=reallocation_BitMap(image);
text[i]=name.toString().toLowerCase();
image[i]=decodedByte;
}
} else {
// no products found
// Launch Add New product Activity
/*Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);*/
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
//
if (pDialog.isShowing()) {
pDialog.dismiss();
// progressDialog.setCancelable(true);
}
edittext.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
int textlength = edittext.getText().length();
text_sort.clear();
image_sort.clear();
if (s.length() >= 1 && enablePopup) {
//Log.i("Length of SorttEX111"," "+ text_sort.size());
for( int i=0;i<text.length;i++)
{
if((s.toString().toLowerCase()).equalsIgnoreCase(((String) text[i].subSequence(0, textlength))))
{
text_sort.add(text[i]);
image_sort.add(image[i]);
}
}
}
listview.setAdapter(new MyCustomAdapter(text_sort, image_sort));
enablePopup = true;
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = this.getMenuInflater();
menuInflater.inflate(R.menu.item_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (((String) item.getTitle()).compareTo("About") == 0) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class DataHolder
{
String ProductName;
Bitmap Productimage;
public void setData(String ProductName,Bitmap image)
{
this.ProductName=ProductName;
this.Productimage=image;
}
public String GetProductName()
{return ProductName;}
public Bitmap Getimage()
{return Productimage;}
}
public class DataHolder1
{
String ProductName;
Bitmap Productimage;
public void setData1(String ProductName,Bitmap image)
{
this.ProductName=ProductName;
this.Productimage=image;
}
public String GetProductName1()
{return ProductName;}
public Bitmap Getimage1()
{return Productimage;}
}
class MyCustomAdapter extends BaseAdapter
{
String[] data_text;
Bitmap[] data_image;
MyCustomAdapter()
{
data_text=null;
data_image=null;
}
MyCustomAdapter(String[] text, Bitmap[] image)
{
data_text = text;
data_image = image;
}
MyCustomAdapter(ArrayList<String> text, ArrayList<Bitmap> image)
{
data_text = new String[text.size()];
data_image = new Bitmap[image.size()];
for(int i=0;i<text.size();i++)
{
data_text[i] = text.get(i);
data_image[i] = image.get(i);
}
}
public int getCount()
{
return data_text.length;
}
public String getItem(int position)
{
return null;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.search_dictionary_item, null);
}
TextView textview = (TextView) convertView.findViewById(R.id.TextView01);
ImageView imageview = (ImageView) convertView.findViewById(R.id.ImageView01);
textview.setText(data_text[position]);
imageview.setImageBitmap(data_image[position]);
return convertView;
}
}
public static String[] reallocation(String s[])
{
String t[]=new String[s.length+1];
for(int i=0; i<s.length;i++)
{
t[i]=s[i];
}
return t;
}
public static Bitmap[] reallocation_BitMap(Bitmap s[])
{
Bitmap t[]=new Bitmap[s.length+1];
for(int i=0; i<s.length;i++)
{
t[i]=s[i];
}
return t;
}
}
and search_dictionary.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#color/green">
<EditText
android:id="#+id/EditText01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search" >
</EditText>
<ListView
android:id="#+id/ListView01"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="50">
</ListView>
I found the answer by placing android:cacheColorHint="#00000000" in xml
<ListView
android:id="#+id/List_Of_Categories"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:cacheColorHint="#00000000"
android:divider="#android:color/transparent"
android:dividerHeight="1dp"
/>

Categories

Resources