CustomAdapter extends BaseAdapter showing wrong images - android

I have a problem here, this is my customAdapter for ListView.
I was trying to get an XML file and show it using this adapter.
I have few source of XML files and one of them has an image link.
Using this code, I have shown all the images, but somehow it was not placed in the correct imageView.
Can anyone see why this is not working correctly?
package dotmanga.classes;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import example.dotmanga.R;
public class TestAdapter extends BaseAdapter {
private Context con;
private List<Entry> entries;
private LayoutInflater inflater;
private Handler hand = new Handler();
static class ViewHolder {
TextView title;
TextView link;
ImageView imv;
}
public TestAdapter(Context c, List<Entry> e) {
this.con = c;
this.entries = e;
this.inflater = LayoutInflater.from(this.con);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return entries.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return entries.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
View vi = convertView;
if (convertView == null) {
vi = this.inflater.inflate(R.layout.activity_list_row, null);
holder = new ViewHolder();
holder.title = (TextView) vi.findViewById(R.id.title);
holder.link = (TextView) vi.findViewById(R.id.link);
holder.imv = (ImageView) vi.findViewById(R.id.imageView1);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
Entry entry = entries.get(position);
holder.title.setText(entry.title);
holder.link.setText(entry.link);
if (entry.img != null) {
final String myurl = entry.img;
new Thread(new Runnable() {
public void run() {
try {
URL url = new URL(myurl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
final Bitmap myBitmap = BitmapFactory.decodeStream(input);
hand.post(new Runnable() {
public void run() {
holder.imv.setImageBitmap(myBitmap);
}
});
connection.disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
return vi;
}
}

Your issue is probably due to an empty imageView, if some image are empty, getView will display wrong image. You need to catch some "ErrorRessource".
like :
if (entry.img != null) {
//do some stuff
}
else {
holder.imv.setImageResource(R.drawable.theErrorImage);
}
But more deeply, i don't think you use the best practice to display images from Url, i strongly advice you to use some libs like https://github.com/lexs/webimageloader , who allow you to cache these images and do your job in an easy ans useful way.

Related

How to create Heterogenous Layouts from json response

Hi please help me inflate layout based on json response type
I am trying to merge http://androidcss.com/android/fetch-json-data-android/ this tutorial with this https://github.com/codepath/android_guides/wiki/Heterogenous-Layouts-inside-RecyclerView
But i'm facing some issues
my json response form
[
{ "type":"sports",
"image":"http://example.com/image.jpg",
"name":"Super Commando Dhruva"
},
{
"type":"health",
"image":"http://example.com/image.jp",
"name":"Parmanu"
}
]
MainActivity
package com.androidcss.jsonexample;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
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.List;
public class MainActivity extends AppCompatActivity {
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVFishPrice;
private AdapterFish mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Make call to AsyncTask
new AsyncLogin().execute();
}
private class AsyncLogin extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
url = new URL("http://example.com/response.json");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
List<DataFeed> data=new ArrayList<>();
pdLoading.dismiss();
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
DataFeed fishData = new DataFeed();
fishData.fishImage= json_data.getString("image");
fishData.fishName= json_data.getString("type");
fishData.catName= json_data.getString("name");
// fishData.sizeName= json_data.getString("size_name");
//fishData.price= json_data.getInt("price");
data.add(fishData);
}
// Setup and Handover data to recyclerview
mRVFishPrice = (RecyclerView)findViewById(R.id.fishPriceList);
mAdapter = new AdapterFish(MainActivity.this, data);
mRVFishPrice.setAdapter(mAdapter);
mRVFishPrice.setLayoutManager(new LinearLayoutManager(MainActivity.this));
} catch (JSONException e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
My adapter
package com.androidcss.jsonexample;
import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.squareup.picasso.Picasso;
import java.util.Collections;
import java.util.List;
public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private LayoutInflater inflater;
List<DataFeed> data= Collections.emptyList();
DataFeed current;
int currentPos=0;
private final int USER = 0, IMAGE = 1;
// create constructor to innitilize context and data sent from MainActivity
public AdapterFish(Context context, List<DataFeed> data){
this.context=context;
inflater= LayoutInflater.from(context);
this.data=data;
}
// return total item from List
#Override
public int getItemCount() {
return data.size();
}
#Override
public int getItemViewType(int position) {
DataFeed current=data.get(position);
if (data.get(position) instanceof DataFeed) {
return USER;
} else if (data.get(position) instanceof String) {
return IMAGE;
}
return -1;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
RecyclerView.ViewHolder viewHolder;
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
switch (viewType) {
case USER:
View v1 = inflater.inflate(R.layout.layout_viewholder1, viewGroup, false);
viewHolder = new ViewHolder1(v1);
break;
case IMAGE:
View v2 = inflater.inflate(R.layout.layout_viewholder2, viewGroup, false);
viewHolder = new ViewHolder2(v2);
break;
default:
View v = inflater.inflate(R.layout.container_fish, viewGroup, false);
viewHolder = new MyHolder(v);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
switch (viewHolder.getItemViewType()) {
case USER:
ViewHolder1 vh1 = (ViewHolder1) viewHolder;
configureViewHolder1(vh1, position);
break;
case IMAGE:
ViewHolder2 vh2 = (ViewHolder2) viewHolder;
configureViewHolder2 (vh2, position, int);
break;
//default:
// RecyclerViewSimpleTextViewHolder vh = (RecyclerViewSimpleTextViewHolder) viewHolder;
// configureDefaultViewHolder(vh, position);
// break;
}
}
//private void configureDefaultViewHolder(RecyclerViewSimpleTextViewHolder vh, int position) {
// vh.getLabel().setText((CharSequence) items.get(position));
//}
private void configureViewHolder1(ViewHolder1 vh1, int position) {
DataFeed current = data.get(position);
if (current != null) {
vh1.getLabel1().setText("Name: " + current.fishName);
//vh1.getLabel2().setText("Hometown: " + current.hometown);
}
}
private void configureViewHolder2(ViewHolder2 vh2) {
vh2.getImageView().setImageResource(R.drawable.robbie);
}
class MyHolder extends RecyclerView.ViewHolder{
TextView textFishName;
ImageView ivFish;
TextView textSize;
TextView textType;
TextView textPrice;
// create constructor to get widget reference
public MyHolder(View itemView) {
super(itemView);
textFishName= (TextView) itemView.findViewById(R.id.textFishName);
ivFish= (ImageView) itemView.findViewById(R.id.banner);
}
}
}
Try this
String type="sports";
String type1="health";
JSONObject json_data = jArray.getJSONObject(i);
type = json_data.getString("type");
if (Objects.equals(type,type)){
fishData.fishImage= json_data.getString("image");
}
else if (Objects.equals(type,type1)){
fishData.fishImage= json_data.getString("image");
}

How to sort adapter (BaseAdapter) based on current its field

I have listviewadapter , it contains some fields like : status, notes, salesname, insertdate (txtTgglInsert), image. I want to do sorting based insertdate(txtTgglInsert) descending(based on recent status). How could I do this one on my programm with calling this adapter?
my adapter :
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class ListViewTimelineAdapter extends BaseAdapter{
private static ArrayList<URLPostClass> DataProcessorResult;
private LayoutInflater myInflater;
Context mycontext;
public ListViewTimelineAdapter(Context context, ArrayList<URLPostClass> results) {
DataProcessorResult = results;
myInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
//Log.d("count", String.valueOf(DataProcessorResult.size()));
return DataProcessorResult.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return DataProcessorResult.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
final Context mycontext=parent.getContext();
if(convertView == null) {
convertView = myInflater.inflate(R.layout.custom_viewtimeline, null);
holder = new ViewHolder();
holder.txtJenisStatus = (TextView) convertView.findViewById(R.id.jenisstatus);
holder.txtStatus = (TextView) convertView.findViewById(R.id.status);
holder.txtSales = (TextView) convertView.findViewById(R.id.sales);
holder.txtTgglInsert = (TextView) convertView.findViewById(R.id.tgglinsert);
holder.imgPosting= (ImageView) convertView.findViewById(R.id.imgposting);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtJenisStatus.setText(DataProcessorResult.get(position).getJenisStatus());
holder.txtStatus.setText(DataProcessorResult.get(position).getRemark());
holder.txtSales.setText(DataProcessorResult.get(position).getNamaSales());
holder.txtTgglInsert.setText(DataProcessorResult.get(position).getTgglInsert());
holder.txtStatus.setTextSize(TypedValue.COMPLEX_UNIT_PX, mycontext.getResources().getDimensionPixelSize( R.dimen.lbltitlelistviewitem));
holder.txtJenisStatus.setTextSize(TypedValue.COMPLEX_UNIT_PX, mycontext.getResources().getDimensionPixelSize( R.dimen.lbllistviewitem));
holder.txtSales.setTextSize(TypedValue.COMPLEX_UNIT_PX, mycontext.getResources().getDimensionPixelSize( R.dimen.lbllistviewitem));
holder.txtTgglInsert.setTextSize(TypedValue.COMPLEX_UNIT_PX, mycontext.getResources().getDimensionPixelSize( R.dimen.lbllistviewitem));
try {
String image_url = DataProcessorResult.get(position).getPath();
if (image_url.length()>0) {
ImageLoader imgLoader = new ImageLoader(mycontext);
imgLoader.DisplayImage(image_url, 0, holder.imgPosting);
holder.imgPosting.getLayoutParams().width= mycontext.getResources().getDimensionPixelSize( R.dimen.photolistviewitem);
holder.imgPosting.getLayoutParams().height= mycontext.getResources().getDimensionPixelSize( R.dimen.photolistviewitem);
}else {
holder.imgPosting.setVisibility(View.GONE);
}
} catch (Exception e) {
// TODO Auto-generated catch block
//Toast.makeText(mycontext, e.toString(), Toast.LENGTH_SHORT).show();
}
//if (position % 2 == 1) {convertView.setBackgroundColor(Color.WHITE);} else {convertView.setBackgroundColor(Color.rgb(208,212,208)); }
return convertView;
}
static class ViewHolder {
TextView txtJenisStatus;
TextView txtStatus;
TextView txtSales;
TextView txtTgglInsert;
ImageView imgPosting;
}
}
Since your Adapter is based on an ArrayList of objects, you can change your implementation to subclass ArrayAdapter (Docs: http://developer.android.com/reference/android/widget/ArrayAdapter.html)
public class ListViewTimelineAdapter extends ArrayAdapter<URLPostClass> {
after that, sorting would be trivial:
ArrayList<URLPostClass> myListData = ...
ArrayAdapter<URLPostClass> adapter = new MyArrayAdapter<URLPostClass>(context, R.layout.my_layout, myListData);
adapter.sort(new Comparator<URLPostClass>() {
#Override public int compare(URLPostClass lhs, URLPostClass rhs) {
return rhs.getTgglInsert().compareTo(lhs.getTgglInsert()); // flipped for reverse order
}
});
myListView.setAdapter(adapter);
Considering that you've got a Date field your Comaparator class would be like this
public class CustomDateComparator implements Comparator<DataProcessorResult> {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("dd MMM yyyy");
#Override
public int compare(DataProcessorResult lhs, DataProcessorResult rhs) {
// TODO Auto-generated method stub
Date lhsDate = null;
Date rhsDate = null;
try {
lhsDate = simpleDateFormat.parse(lhs.getTgglInsert());
rhsDate = simpleDateFormat.parse(rhs.getTgglInsert());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(lhsDate == rhsDate) {
return lhs.getNamaSales().compareToIgnoreCase(rhs.getNamaSales());
}else {
return lhsDate.compareTo(rhsDate);
}
}
}
And then you can do this
Collections.sort(results, new CustomDateComparator());
just before you pass it to your custom adapter class.
Hope this helps you.

Listview display duplicate data on refresh

I have made a listview with image and text as elements. If the data is text it displays text and if it is image it displays image.
When i click button from MainActivity to the listview, the listview is displayed as needed, i.e images for image and text for text data.
The problem occurs when the listview activity is opened and any new data is inserted in db and the listview is refreshed. The data in the view is completely messed up. it shows image in the some of the text data.
But when i go back to the main activity and again come back to listview everything is perfect.
Can anyone please help me whats going wrong here.
I am using SimpleCursorAdaptor, CursorLoader.
MainActivity.java
public class MainActivity extends ActionBarActivity implements LoaderCallbacks<Cursor>{
private TextView from, data;
private SimpleCursorAdapter dataAdapter;
private String TO_USER;
ConnectionService connService;
boolean mBounded;
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
String[] projection = {MessageHelper.COLUMN_ID,
MessageHelper.COLUMN_FROM,
MessageHelper.COLUMN_DATA};
String args[] ={ "cid","data"};
CursorLoader cursorLoader = new CursorLoader(this,
MyContentProvider.CONTENT_URI, projection,
MessageHelper.COLUMN_CONVERSATION_ID + " = ?" + " AND " +
MessageHelper.COLUMN_EXIN + " = ?" ,args,
MessageHelper.COLUMN_RECIEVED_TIMESTAMP);
return cursorLoader;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter();
getLoaderManager().initLoader(0, null, this);
}
private void setListAdapter() {
String[] columns = new String[] {
MessageHelper.COLUMN_FROM,
MessageHelper.COLUMN_DATA
};
int[] to = new int[] {
R.id.data
};
Cursor cursor = loadMessage();
cursor.moveToFirst();
dataAdapter = new CustomCursorAdapter(
this,
R.layout.linear_listitem,
cursor,
columns,
to,
0);
listview.setAdapter(dataAdapter);
.
}
public void onLoaderReset(Loader<Cursor> loader) {
dataAdapter.swapCursor(null);
}
protected void onResume() {
super.onResume();
getLoaderManager().restartLoader(0, null, this);
}
protected void onRestart(){
super.onRestart();
}
CursorAdapter.java
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ClipDrawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
//import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import com.expert.sqllite.MessageChat;
import com.expert.sqllite.MessageHelper;
public class CustomCursorAdapter extends SimpleCursorAdapter {
private LayoutInflater mInflater;
private Map<Integer, ArrayList<MessageChat>> chatMapConId = new HashMap<Integer,
ArrayList<MessageChat>>();
public CustomCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
super(context, layout, c, from, to,flags);
mInflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
MessageChat msgchat = new MessageChat();
msgchat.setData(cursor.getString(cursor.getColumnIndex(MessageHelper.COLUMN_DATA)));
msgchat.setFrom(cursor.getString(cursor.getColumnIndex(MessageHelper.COLUMN_FROM)));
ViewHolder holder;
if(!msgchat.getData().contains("-image-")){
holder = (ViewHolder) view.getTag();
}
else{
holder = (ViewHolder) view.getTag();
}
TextView dataMsg =(TextView)view.findViewById(R.id.data);
RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams
(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
ImageView imgMsg =null;
if(msgchat.getFrom().equalsIgnoreCase("me"))
{
if(!msgchat.getData().contains("-image-")){
dataMsg.setBackgroundResource
(R.drawable.speech_bubble_green);
dataMsg.setText(msgchat.getData());
}
else
{
String[] imageSplit=msgchat.getData().split("-image-");
Uri imgUri=Uri.parse(imageSplit[1]);
try {
imgMsg (ImageView)view.findViewById
(R.id.chat_image);
imgMsg.setImageBitmap(getThumbnail
(imgUri,context));
dataMsg.setVisibility(View.INVISIBLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
lp1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
}
else
{
if(!msgchat.getData().contains("-image-")){
dataMsg.setBackgroundResource
(R.drawable.speech_bubble_orange);
dataMsg.setText(msgchat.getData());
}
else{
String[] imageSplit=msgchat.getData().split("-image-");
Uri imgUri=Uri.parse(imageSplit[1]);
try {
imgMsg =(ImageView)view.findViewById
(R.id.chat_image);
imgMsg.setImageBitmap(getThumbnail
(imgUri,context));
imgMsg.setBackgroundResource
(R.drawable.speech_bubble_orange);
dataMsg.setVisibility(View.INVISIBLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
lp1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
}
if(!msgchat.getData().contains("-image-")){
dataMsg.setLayoutParams(lp1);
dataMsg.setTextColor(R.color.textColor);
}
else{
imgMsg.setLayoutParams(lp1);
}
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
File imageFile;
View rowView = mInflater.inflate(R.layout.linear_listitem, parent, false);
View rowViewImage = mInflater.inflate(R.layout.linear_listitem_image, parent, false);
ViewHolder holder = null;
ViewHolderImage holderImage = null;
String data = cursor.getString(cursor.getColumnIndex(MessageHelper.COLUMN_DATA));
String path = null;
if(data.contains("-image-")){
path = data.split("-image-")[1];
}
holder = new ViewHolder();
holder.data = (TextView)rowView.findViewById(R.id.data);
holder.imageHolder = (ImageView)rowViewImage.findViewById(R.id.chat_image);
rowView.setTag(holder);
return rowView;
}
class ViewHolder
{
TextView data,from;
ImageView imageHolder ;
}
class ViewHolderImage
{
ImageView imageHolder ;
}
public static Bitmap getThumbnail(Uri uri,Context context) throw FileNotFoundException,IOException{
InputStream input = context.getContentResolver().openInputStream(uri);
BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
onlyBoundsOptions.inJustDecodeBounds = true;
onlyBoundsOptions.inDither=true;//optional
onlyBoundsOptions.inPreferredConfig=Bitmap.Config.ARGB_8888;//optional
BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
input.close();
if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1))
return null;
int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ?
onlyBoundsOptions.outHeight : onlyBoundsOptions.outWidth;
// double ratio = (originalSize > THUMBNAIL_SIZE) ? (originalSize / THUMBNAIL_SIZE): 1.0;
double ratio = 1.0;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
//bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio);
bitmapOptions.inSampleSize = 2;
bitmapOptions.inMutable = true;
bitmapOptions.inDither=true;//optional
bitmapOptions.inPreferredConfig=Bitmap.Config.RGB_565;//optional
bitmapOptions.outHeight=150;
bitmapOptions.outWidth=150;
input = context.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
input.close();
//bitmap.setWidth(400);
//bitmap.setHeight(400);
return bitmap;
}
private static int getPowerOfTwoForSampleRatio(double ratio){
int k = Integer.highestOneBit((int)Math.floor(ratio));
if(k==0) return 1;
else return k;
}
}
Update
If i have data only text or only image. Then the list view is perfect. The problem i think is when both the view i.e text and image comes into picture.
#Override
public int getItemViewType(int position) {
Cursor cursor = (Cursor) getItem(position);
return getItemViewType(cursor);
}
#Override
public int getViewTypeCount() {
return 2;
}
These method has solved the problem of improper display

How to load images using android baseadapter?

My project works without error, but upon loading, images are not loaded in the Listview.
Here is a sample image
sample at the first working image
But after dragging ListView, all images loads.
sample draggened image load
Please Help. Sorry bad english.
Categoryadapter.java
package com.medyasef.dernek.tjod;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by olkunmustafa on 26.09.2013.
*/
public class CategoryAdapter extends BaseAdapter {
private String LOG_NAME = "HATA";
private List<Categoryicerikler> list_view;
private HashMap<Integer,Bitmap> bitmaplist;
private Context mContext;
private Categories categories = new Categories();
public CategoryAdapter(List<Categoryicerikler> list_view, Context mContext) {
this.list_view = list_view;
this.mContext = mContext;
bitmaplist = new HashMap<Integer, Bitmap>();
for (int i = 0; i < list_view.size() ; i++) {
Categoryicerikler bitmap_icerikler = list_view.get(i);
setBitmapFromURL(bitmap_icerikler.getCategory_post_image(),i);
}
}
/*
Burada resimleri çekmek için thread oluşturuyoruz.
Resim linkini ve ImageView'i veriyoruz ve ekrana basmasını sağlıyoruz.
*/
public void setBitmapFromURL(final String src,final int value) {
new Thread(
new Runnable()
{
#Override
public void run() {
HttpURLConnection connection= null;
try {
URL url = new URL(src);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
InputStream input = connection.getInputStream();
final Bitmap myBitmap = BitmapFactory.decodeStream(input);
try {
bitmaplist.put(value,myBitmap);
}
catch (Exception e){
Log.d(LOG_NAME,e.getMessage());
Log.d(LOG_NAME,"Resim ekleme işlemi başarısız.");
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
connection.disconnect();
}
}
}).start();
}
#Override
public int getCount() {
return list_view.size();
}
#Override
public Object getItem(int position) {
return list_view.get(position);
}
#Override
public long getItemId(int position) {
return list_view.indexOf(getItem(position));
}
#Override
public View getView(int position, View convertview, ViewGroup viewGroup) {
Categoryicerikler categoryicerikler = list_view.get(position);
ViewHolder holder = null;
if(convertview==null){
Log.d(LOG_NAME,"sonuc");
convertview = LayoutInflater.from(mContext).inflate(R.layout.categories,viewGroup,false);
holder = new ViewHolder();
holder.txtTitle = (TextView) convertview.findViewById(R.id.category_posttitle);
holder.txtDate = (TextView) convertview.findViewById(R.id.category_postdate);
holder.imageView = (ImageView) convertview.findViewById(R.id.category_image);
convertview.setTag(holder);
Categories.categoryAdapter.notifyDataSetChanged();
}
else {
holder = (ViewHolder) convertview.getTag();
}
holder.txtTitle.setText(categoryicerikler.getCategory_posttitle());
holder.txtDate.setText(categoryicerikler.getCategory_postdate());
try {
holder.imageView.setImageBitmap(bitmaplist.get(position));
}
catch (Exception e){
}
return convertview;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDate;
}
}
Categoryicerikler.java
package com.medyasef.dernek.tjod;
import android.graphics.Bitmap;
import android.widget.ImageView;
/**
* Created by olkunmustafa on 26.09.2013.
*/
public class Categoryicerikler {
private String category_posttitle;
private String category_postdate;
private String category_post_content;
private String category_post_image;
public Categoryicerikler( String category_posttitle, String category_postdate, String category_post_content,String post_image) {
this.category_posttitle = category_posttitle;
this.category_postdate = category_postdate;
this.category_post_content = category_post_content;
this.category_post_image = post_image;
}
public String getCategory_posttitle() {
return category_posttitle;
}
public void setCategory_posttitle(String category_posttitle) {
this.category_posttitle = category_posttitle;
}
public String getCategory_postdate() {
return category_postdate;
}
public void setCategory_postdate(String category_postdate) {
this.category_postdate = category_postdate;
}
public String getCategory_post_content() {
return category_post_content;
}
public void setCategory_post_content(String category_post_content) {
this.category_post_content = category_post_content;
}
public String getCategory_post_image() {
return category_post_image;
}
public void setCategory_post_image(String category_post_image) {
this.category_post_image = category_post_image;
}
}
Categories.java
package com.medyasef.dernek.tjod;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.Html;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
/**
* Created by olkunmustafa on 25.09.2013.
*/
public class Categories extends Activity {
private List<Categoryicerikler> content_list;
public static CategoryAdapter categoryAdapter;
private ListView main_category;
private static HashMap<Integer,Bitmap> bitmaplist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_categories);
main_category = (ListView) findViewById(R.id.main_category);
new GetCategory().execute();
}
private class GetCategory extends AsyncTask<Void,Void,String> {
#Override
protected void onPreExecute() {
Toast.makeText(Categories.this, "İslem Baslıyor Bekleyiniz", Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(Void... voids) {
/*
Burada internete bağlanıp json veriyi string cinsinden çekiyoruz.
*/
InternetConnection internetcon = new InternetConnection();
String json_result = internetcon.get_json_data();
return json_result;
}
#Override
protected void onPostExecute(String data) {
/*
Gelen string veriyi json_to_list_view metoduna veriyorum
Bu metot gelen json verisinin içeriklerini doldurarak bana birt liste dönderir.
*/
try {
content_list = GetJson.json_to_list_view(data);
} catch (JSONException e) {
Log.d("Json_Error","Json çekilirken hata oluştu");
}
categoryAdapter = new CategoryAdapter(content_list,Categories.this);
main_category.setAdapter(categoryAdapter);
}
}
}
If you simply want to load images in a list view, I would recommend you to use Picasso
Its simple, fast and does nearly everything automatically for you. You also don't have to care about canceling request on activity destroy. So I guess this would be the best start for you, if you simply want to load images into a ImageView in a ListView.
for instance in your adapter you could use:
Picasso.with(context)
.load(url)
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.into(imageView);
Where imageview is the ImageView of your listview cell
Use universal image loader library and then following way
---------------------------------------------------------
1 - options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.physicalgift_normal)
.cacheInMemory()
.cacheOnDisc()
.displayer(new RoundedBitmapDisplayer(10))
.build();
imageLoader=ImageLoader.getInstance();
ImageLoaderConfiguration imgconfig=ImageLoaderConfiguration.createDefault(context);
imageLoader.init(imgconfig);
----------------------------------------------------------
2 - String url=list.get(position).getThumbUrl();
if(url != null && url !="")
imageLoader.displayImage(Utils.getEncodedUrl(url), holder.img, options);
------------------------------------------------------------
3 - SubCatAdapter adapter = new SubCatAdapter(SubCategoryActivity.this,
mlist);
list.setAdapter(adapter);
------------------------------------------------------------
full example is here
public class SubCatAdapter extends BaseAdapter {
private ArrayList<SubcategoryData> list;
private LayoutInflater inflator;
public ImageLoader imageLoader;
private DisplayImageOptions options;
public SubCatAdapter(Context context, ArrayList<SubcategoryData> mlist) {
super();
this.list = mlist;
this.inflator = LayoutInflater.from(context);
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.physicalgift_normal)
.cacheInMemory()
.cacheOnDisc()
.displayer(new RoundedBitmapDisplayer(10))
.build();
imageLoader=ImageLoader.getInstance();
ImageLoaderConfiguration imgconfig=ImageLoaderConfiguration.createDefault(context);
imageLoader.init(imgconfig);
}
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View view = convertView;
ViewHolder holder = null;
if (convertView == null) {
view = inflator.inflate(R.layout.row_subcat, null);
holder = new ViewHolder();
holder.txt_Name = (TextView) view.findViewById(R.id.txt_name);
holder.img=(ImageView)view.findViewById(R.id.img_row);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.txt_Name.setText(list.get(position).getName());
String url=list.get(position).getThumbUrl();
if(url != null && url !="")
imageLoader.displayImage(Utils.getEncodedUrl(url), holder.img, options);
return view;
}
static class ViewHolder {
TextView txt_Name;
ImageView img;
}
}

Android ListActivity row click

I have an activity that displays information about a player. This part works fine. (I used an adapter). But where should I put the code that detects when a row is clicked?
PlayersActivity.java
package com.democratandchronicle.billstrainingcamp;
import android.os.Bundle;
public class PlayersActivity extends ListActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_players);
PlayersAdapter adapter = new PlayersAdapter(this);
getListView().setAdapter(adapter);
PlayersFetchTask loadPlayersTask = new PlayersFetchTask(adapter);
loadPlayersTask.execute();
}
}
PlayersAdapter.java
package com.democratandchronicle.billstrainingcamp;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class PlayersAdapter extends BaseAdapter {
private Context context;
private LayoutInflater layoutInflater;
private JSONArray entries = new JSONArray();
private DrawableManager dm;
public PlayersAdapter(Context context) {
super();
this.context = context;
this.layoutInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.dm = new DrawableManager();
}
#Override
public int getCount() {
return this.entries.length();
}
#Override
public Object getItem(int position) {
try {
return this.entries.getJSONObject(position);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
RelativeLayout playerRowView;
if (convertView == null)
{
playerRowView = (RelativeLayout) this.layoutInflater.inflate(R.layout.player_row, parent, false);
}
else
{
playerRowView = (RelativeLayout) convertView;
}
TextView playerNameText = (TextView) playerRowView.findViewById(R.id.playerName);
TextView playerPositionText = (TextView) playerRowView.findViewById(R.id.playerPosition);
ImageView playerImageView = (ImageView) playerRowView.findViewById(R.id.playerImage);
try
{
JSONObject dataRow = this.entries.getJSONObject(position);
playerNameText.setText(dataRow.getString("firstName") + " "+ dataRow.getString("lastName"));
playerPositionText.setText(dataRow.getString("position"));
if (!dataRow.getString("photo").equals(""))
{
this.dm.fetchDrawableOnThread(dataRow.getString("photo"), playerImageView);
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return playerRowView;
}
public void upDateEntries(JSONArray entries)
{
this.entries = entries;
this.notifyDataSetChanged();
}
}
Where should I put the code that detects when a row is clicked?
To detect a click anywhere on the row, use an OnItemClickListener in your Activity.
To detect clicks in different regions on each row, use OnClickListeners inside your Adapter's getView().
Also you can create a slightly faster Adapter if you use the ViewHolder method. The Google Talk TurboCharge Your UI discussions this and other good practices in detail.
Addition
How would I do this in my activity?
ListActivities have an OnListItemClick built-in, the callback has a slightly different name: onListItemClick(). Use it like so:
#Override
protected void onListItemClick (ListView l, View v, int position, long id) {
Toast.makeText(this, "Clicked row " + position, Toast.LENGTH_SHORT).show();
}

Categories

Resources