Duplicate Items Added To Gridlayout Using Custom ButtonAdapter Extends BaseAdapter - android

I need some help on this issue. When I added items to grid layout, some duplicate items added to container and when scrolling their positions are changing. Here is the XML and Java code.
Layout:
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableRow android:layout_width="wrap_content" android:paddingTop="20dp" android:layout_height="wrap_content" android:id="#+id/tableRow2" android:layout_centerHorizontal="true" android:background="#color/transparent" android:minHeight="110dp">
<ImageView android:layout_height="wrap_content" android:layout_width="wrap_content" android:src="#drawable/school_logo_default" android:layout_gravity="bottom" android:id="#+id/school_logo"></ImageView>
</TableRow>
<ImageView
android:layout_width="fill_parent"
android:layout_height="90dip"
android:layout_alignParentTop="true"
android:src="#drawable/gradient_top"
android:scaleType="fitXY"
/>
<ImageView
android:layout_width="fill_parent"
android:layout_height="90dip"
android:layout_alignParentBottom="true"
android:src="#drawable/gradient_bottom"
android:scaleType="fitXY"
/>
<LinearLayout
android:id="#+id/top"
android:layout_width="fill_parent"
android:layout_height="wrap_content" android:gravity="left|top">
<TextView android:layout_height="wrap_content" android:textColor="#color/white" android:layout_weight="1" android:textStyle="bold" android:text="#string/userName" android:layout_width="wrap_content" android:layout_gravity="center_vertical" android:layout_marginRight="20dip" android:gravity="left|top" android:background="#color/transparent" android:paddingLeft="5dp" android:textSize="16px" android:paddingTop="5dp" android:id="#+id/username"></TextView>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingBottom="20dip"
android:layout_alignParentBottom="true"
android:id="#+id/bottom">
<ImageView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="#+id/screen_icon" android:src="#drawable/sl_tools"></ImageView>
</LinearLayout>
<TableRow android:layout_width="wrap_content" android:gravity="center" android:layout_height="wrap_content" android:id="#+id/tableRow1" android:layout_centerInParent="true" android:background="#color/transparent">
<ListView android:columnWidth="120dp" android:id="#+id/gridView1" android:numColumns="4" android:verticalSpacing="10dip" android:gravity="center" android:horizontalSpacing="10dip" android:scrollbars="vertical" android:layout_gravity="center" android:stretchMode="columnWidth" android:background="#color/transparent" android:paddingTop="140dip" android:paddingBottom="80dip"></ListView>
</TableRow>
</RelativeLayout>
</FrameLayout>
Class MyInternet:
package com.explore.home;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.AndroidException;
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.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.explore.objects.PInfoItem;
import com.explore.utils.DMS;
import com.explore.utils.Utils;
public class MyInternet extends Activity {
private static final String LOG = "My Internet";
public List<AppInfo> listApps = new ArrayList<AppInfo>();
LayoutInflater inflator;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
inflator = getLayoutInflater();
setContentView(R.layout.myinternet);
TextView tv = (TextView) findViewById(R.id.username);
tv.setText(DMS.userProfile.user_fname + " " + DMS.userProfile.user_lname);
FrameLayout lLayout = (FrameLayout) findViewById(R.id.myinternetlayout);
lLayout.setBackgroundColor(Color.parseColor(DMS.deviceSettings.Background_Color));
try
{
listApps = Utils.getAppsForScreen(getBaseContext(), "myinternet");
}
catch (IOException e)
{
Toast.makeText(getBaseContext(), "Error MyInternet - " +e.getMessage(), Toast.LENGTH_SHORT).show();
}
ImageView iv1 = (ImageView)findViewById(R.id.school_logo);
iv1.setImageBitmap(Utils.getBitmapByURL(DMS.deviceConfig.curriculum_loft_url + DMS.deviceSettings.School_Logo));
GridView gv = (GridView)findViewById(R.id.gridView1);
gv.setAdapter(new ButtonAdapter(this));
}
class MyOnClickListener implements OnClickListener {
private final int position;
public MyOnClickListener(int position) {
this.position = position;
}
public void onClick(View v) {
Log.i(LOG, "handler=" + listApps.get(position).appName);
try {
handler(listApps.get(position));
} catch (AndroidException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void handler(AppInfo appInfo) throws AndroidException, ClassNotFoundException
{
if(appInfo.type==0) // Shell Out APK
{
File realFilePath = new File("/data/data/com.explore.home/files/"+ appInfo.appFileName);
PackageManager pm = getBaseContext().getPackageManager();
PackageInfo packageInfo = pm.getPackageArchiveInfo( realFilePath.getAbsolutePath(),0);
//PackageManager pm = getPackageManager();
//Intent il = pm.getLaunchIntentForPackage(appInfo.packageName);
Intent il = pm.getLaunchIntentForPackage(packageInfo.packageName);
//Intent i = new Intent();
il.setAction(Intent.ACTION_MAIN);
il.addCategory(Intent.CATEGORY_LAUNCHER);
il.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
ComponentName cn = new ComponentName(packageInfo.packageName, il.getComponent().getClassName());
il.setComponent(cn);
startActivity(il);
return;
}
if(appInfo.type==1) // Shell Out Hyper Link
{
Uri uriUrl = Uri.parse(appInfo.url);
Intent intent = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(intent);
}
else {
Toast.makeText(this, "Not Yet Implemented", Toast.LENGTH_LONG).show();
}
}
class ButtonAdapter extends BaseAdapter {
private Context mContext;
// Gets the context so it can be used later
public ButtonAdapter(Context c) {
mContext = c;
}
// Total number of things contained within the adapter
public int getCount() {
return listApps.size();
}
// Require for structure, not really used in my code.
public Object getItem(int position) {
return null;
}
// Require for structure, not really used in my code. Can
// be used to get the id of an item in the adapter for
// manual control.
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
TableLayout ll;
if (convertView == null) {
Log.i(LOG, "position=" + position);
Log.i(LOG, "count=" + listApps.size());
for(int i=0; i<listApps.size(); i++) {
Log.i(LOG, "apps=" + listApps.get(i).appName);
}
// if it's not recycled, initialize some attributes
AppInfo appInfo = listApps.get(position);
Log.i(LOG, "app name =" + appInfo.appName);
ll = (TableLayout)inflator.inflate(R.layout.app, null, true);
ImageView iv1 = (ImageView)ll.findViewById(R.id.app_icon);
TextView iv2 = (TextView)ll.findViewById(R.id.app_title);
iv2.setText(appInfo.appName);
if(appInfo.type==0)
{
iv1.setImageBitmap(Utils.getAPKIcon(getApplicationContext(), appInfo));
}else
{
if(appInfo.icon!=null)
{
iv1.setImageBitmap(appInfo.icon);
}
}
iv1.setOnClickListener(new MyOnClickListener(position));
iv2.setOnClickListener(new MyOnClickListener(position));
}
else {
ll = (TableLayout) convertView;
}
return ll;
}
}
}
Please let me know why some duplicate items added instead of actual items. While scrolling their positions have changed.

remove the condition and ready
if (convertView == null)

Related

RecyclerView OnClicklistener is unresponsive

Firstly I know there are hundreds of these questions but the answers have not solved my problem. I suspect it's something small I'm missing, basically I've added a RecyclerView and need to start a new activity when a card is clicked.
I've been following this tutorial and it's been smooth sailing up until this point.
https://guides.codepath.com/android/using-the-recyclerview
This is the Recycler
<FrameLayout 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"
tools:context=".MainActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/bgImg"
android:scaleType="centerCrop"/>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/RV"
/>
</FrameLayout>
This is the card
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="4dp"
android:layout_margin="5dp"
android:clickable="true"
android:background="?android:attr/selectableItemBackground">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/vendor_image2"
android:layout_width="fill_parent"
android:layout_height="240dp"
android:padding="5dp" />
<RelativeLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/vendor_image2"
>
<TextView
android:id="#+id/vendor_name2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="bold"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:paddingBottom="5dp"/>
<TextView
android:id="#+id/vendor_content2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginTop="7dp"
android:layout_toEndOf="#+id/vendor_name2"
android:textColor="#color/text_col"
android:paddingBottom="5dp" />
<TextView
android:id="#+id/vendor_suburb2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="italic"
android:textColor="#color/text_col"
android:layout_below="#+id/vendor_name2"
android:layout_marginLeft="10dp" />
<RatingBar
android:id="#+id/MyRating2"
style="?android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/vendor_suburb2"
android:layout_marginLeft="10dp"
android:isIndicator="true"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:numStars="5"
android:textColor="#android:color/black"
android:rating="3.5"
android:stepSize="0.1" />
</RelativeLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
And finally the Adapter and Handler
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.iconiccode.android.guestloc8tor.SQL.DatabaseHandler;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
public class VendorRecycleAdapter extends RecyclerView.Adapter<VendorRecycleAdapter.VendorHolder>
{
public List<Vendor> vendorList;
private DatabaseHandler dbHandler = new DatabaseHandler(MyApp.getContext());
private Vendor currentVendor;
int cate;
Activity thiscontext;
public VendorRecycleAdapter(Activity context, int Cate)
{
this.cate=Cate;
this.thiscontext=context;
}
#Override
public VendorHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
LayoutInflater inflater = LayoutInflater.from(thiscontext);
//View view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_2, parent, false);
View view = inflater.inflate(R.layout.vendor_list_cards,parent,false);
return new VendorHolder(view);
}
#Override
public void onBindViewHolder(VendorHolder holder, int position)
{
vendorList = dbHandler.getVendorData(cate);
currentVendor = vendorList.get(position);
// Get the image string from the Vendor object
String vendorImage = currentVendor.getImage();
Log.e("Vendor Adapter Image", vendorImage);
// Get the name string from the Vendor object
String vendorName = currentVendor.getCompanyName();
Log.e("Vendor Adapter Name", vendorName);
// Get the content string from the Vendor object
String vendorContent = currentVendor.getContent();
// Get the location string from the Vendor object
String vendorSuburb = currentVendor.getSuburb();
Log.e("Vendor Adapter Suburb", vendorSuburb);
// Find the TextView with view ID vendor_name
// Display the name of the current vendor in that TextView
holder.Vvendor_name.setText(vendorName);
holder.Vvendor_image.setImageResource(R.drawable.loading);
ImageLoader imageLoader;
DisplayImageOptions options;
imageLoader = ImageLoader.getInstance();
String url = vendorImage;
imageLoader.init(ImageLoaderConfiguration.createDefault(MyApp.getContext()));
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.loading)
.showImageOnFail(R.drawable.b4f29385)
.resetViewBeforeLoading(true).cacheOnDisk(true)
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565).considerExifParams(true)
.displayer(new FadeInBitmapDisplayer(300)).build();
imageLoader.displayImage(url, holder.Vvendor_image);
// Find the TextView with view ID vendor_content
holder.Vvendor_content.setText(vendorContent);
holder.Vvendor_suburb.setText(vendorSuburb);
}
#Override
public int getItemCount()
{
vendorList = dbHandler.getVendorData(cate);
return vendorList.size();
}
public class VendorHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
public ImageView Vvendor_image;
public TextView Vvendor_name,Vvendor_content,Vvendor_suburb;
public RatingBar Vrating;
public VendorHolder(View itemView)
{
//These pull as null
super(itemView);
Vvendor_image = (ImageView)itemView.findViewById(R.id.vendor_image2);
Vvendor_name = (TextView)itemView.findViewById(R.id.vendor_name2);
Vvendor_content =(TextView)itemView.findViewById(R.id.vendor_content2);
Vvendor_suburb = (TextView)itemView.findViewById(R.id.vendor_suburb2);
Vrating = (RatingBar) itemView.findViewById(R.id.MyRating2);
}
#Override
public void onClick(View v)
{
// int position = getAdapterPosition();
// currentVendor = vendorList.get(position);
Intent intent = new Intent(thiscontext,VendorDetailsActivity.class).addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
String Category = Integer.toString(cate);
JSONObject message = currentVendor.getAllData();
try {
intent.putExtra("IMAGE", message.getString("IMAGE"));
intent.putExtra("URL", message.getString("URL"));
intent.putExtra("CONTENT", message.getString("CONTENT"));
intent.putExtra("COMPANY_NAME", message.getString("COMPANY_NAME"));
intent.putExtra("TEL", message.getString("TEL"));
intent.putExtra("BOOKING_URL", message.getString("BOOKING_URL"));
intent.putExtra("LAT", message.getString("LAT"));
intent.putExtra("LON", message.getString("LON"));
intent.putExtra("STREET", message.getString("STREET"));
intent.putExtra("SUBURB", message.getString("SUBURB"));
intent.putExtra("PROVINCE", message.getString("PROVINCE"));
intent.putExtra("CITY", message.getString("CITY"));
intent.putExtra("CAT",Category);
} catch (JSONException json)
{
Log.e("ERROR", json.getMessage());
}
thiscontext.startActivity(intent);
}
}
}
Any help would be greatly appreciated.
Thanks
I think you just forgot to set the onClickListener in your ViewHolder constructor:
public VendorHolder(View itemView)
{
//These pull as null
super(itemView);
Vvendor_image = (ImageView)itemView.findViewById(R.id.vendor_image2);
Vvendor_name = (TextView)itemView.findViewById(R.id.vendor_name2);
Vvendor_content =(TextView)itemView.findViewById(R.id.vendor_content2);
Vvendor_suburb = (TextView)itemView.findViewById(R.id.vendor_suburb2);
Vrating = (RatingBar) itemView.findViewById(R.id.MyRating2);
// If it should be triggered only when clicking on a specific view, replace itemView with the view you want.
itemView.setOnClickListener(this);
}

there are no any display on listView with baseadapter

every one,
I am a beginning learner on android system ,
I create a small app that could get specific data , like foreign exchange rate from bank website ,
this app uses Jsoup , ListView , BaseAdapter etc...
finally , the only problem is the listView has no any display ,
could any one tell me , how to fix it.
Thanks.
Category.java
public class Category
{
String bank_name;
String page_url;
Category(String bank_name,String url)
{
this.bank_name=bank_name;
this.page_url=url;
}
#Override
public String toString()
{
return bank_name;
}
}
MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.content.*;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends Activity
{
ArrayList<Category> items;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
items=new ArrayList<Category>();
items.add(new Category("台灣銀行","http://rate.bot.com.tw/Pages/Static/UIP003.zh-TW.htm"));
ArrayAdapter<Category> adapter = new ArrayAdapter<Category>(this , android.R.layout.simple_list_item_1 ,items);
ListView lv = (ListView)findViewById(R.id.lv);
lv.setAdapter(adapter);
lv.setOnItemClickListener(itemClick);
}
OnItemClickListener itemClick = new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> av , View v , int position , long id)
{
Category category = items.get(position);
Intent intent = new Intent();
intent.setClass(MainActivity.this , RateActivity.class );
intent.putExtra("bank_name", category.bank_name);
intent.putExtra("page_url" , category.page_url);
startActivity(intent);
}
};
RateBean.java
public class RateBean
{
private String currency;
private String cashBuy;
private String cashSold;
private String spotBuy;
private String spotSold;
public RateBean()
{
currency = "";
cashBuy = "";
cashSold = "";
spotBuy = "";
spotSold = "";
}
public RateBean(String [] strArr)
{
this.currency=strArr[0];
this.cashBuy=strArr[1];
this.cashSold=strArr[2];
this.spotBuy=strArr[3];
this.spotSold=strArr[4];
}
public RateBean(String currency , String cashBuy , String cashSold , String spotBuy ,String spotSold)
{
setCurrency(currency);
setCashBuy(cashBuy);
setCashSold(cashSold);
setSpotBuy(spotBuy);
setSpotSold(spotSold);
}
//Currency setter and getter
public void setCurrency(String currency)
{
this.currency = currency ;
}
public String getCurrency()
{
return currency;
}
//Cash buy setter and getter
public void setCashBuy(String cashBuy)
{
this.cashBuy = cashBuy;
}
public String getCashBuy()
{
return cashBuy;
}
//Cash sold setter and getter
public void setCashSold(String cashSold)
{
this.cashSold = cashSold;
}
public String getCashSold()
{
return cashSold;
}
//Spot buy setter and getter
public void setSpotBuy(String spotBuy)
{
this.spotBuy = spotBuy;
}
public String getSpotBuy()
{
return spotBuy;
}
//Spot sold setter and getter
public void setSpotSold(String spotSold)
{
this.spotSold = spotSold;
}
public String getSpotSold()
{
return spotSold;
}
}
RateActivity.java
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
public class RateActivity extends ListActivity
{
Context context ;
ArrayList<RateBean> rateBean_item;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rate_show);
TextView updateTime = (TextView)findViewById(R.id.updateTime_textView);
Intent intent = getIntent();
String category = intent.getStringExtra("bank_name");
String page_url = intent.getStringExtra("page_url");
setTitle(category);
context=this;
ConnectThread thread = new ConnectThread(context , rateBean_item , page_url , updateTime);
thread.start();
}
public class ConnectThread extends Thread
{
Context context;
ArrayList<RateBean> rateBean_item;
String page_url ;
TextView updateTime;
RateAdapter adapter;
RateBean rateBean;
int i =0;
public ConnectThread(Context context , ArrayList<RateBean> rateBean_item , String page_url , TextView updateTime )
{
this.context=context;
this.rateBean_item=rateBean_item;
this.page_url=page_url;
this.updateTime=updateTime;
}
#Override
public void run()
{
try
{
String currency="";
String cashBuy="";
String cashSold="";
String spotBuy="";
String spotSold="";
Document doc = Jsoup.connect(page_url).get();
rateBean_item = new ArrayList<>();
String temp=doc.select("td[style=width:326px;text-align:left;vertical-align:top;color:#0000FF;font-size:11pt;font-weight:bold;]").text();
String time=temp.substring(12);
updateTime.setText("匯率更新時間:\n" + time);
for( Element title:doc.select("td.titleLeft"))
{
currency=title.text();
if( i < doc.select("td.decimal").size())
{
cashBuy=doc.select("td.decimal").eq(i++).text();
cashSold=doc.select("td.decimal").eq(i++).text();
spotBuy=doc.select("td.decimal").eq(i++).text();
spotSold=doc.select("td.decimal").eq(i++).text();
rateBean = new RateBean( a , b , c ,d , e );
rateBean_item.add(rateBean);
}
}
adapter = new RateAdapter(context , rateBean_item);
setListAdapter(adapter);
adapter.notifyDataSetChanged();
}
catch( Exception exception )
{
exception.printStackTrace();
}
}
}
}
RateAdapter.java
import java.util.ArrayList;
import android.util.Log;
import android.widget.BaseAdapter;
import android.view.*;
import android.widget.*;
import android.content.*;
public class RateAdapter extends BaseAdapter
{
private LayoutInflater inflater;
private ArrayList<RateBean> list ;
public RateAdapter()
{
}
public RateAdapter(Context context , ArrayList<RateBean> list )
{
this.inflater = LayoutInflater.from(context);
this.list = list;
}
#Override
public int getCount()
{
return list.size();
}
#Override
public Object getItem(int position)
{
return list.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
public static class ViewHolder
{
TextView currency_name;
TextView cash_buy;
TextView cash_sold;
TextView spot_buy;
TextView spot_sold;
}
#Override
public View getView( int position , View convertView , ViewGroup parent)
{
ViewHolder holder;
if(convertView == null)
{
convertView = inflater.inflate(R.layout.rate_item , null);
holder = new ViewHolder();
holder.currency_name = (TextView)convertView.findViewById(R.id.xml_currency);
holder.cash_buy = (TextView)convertView.findViewById(R.id.xml_cashBuy);
holder.cash_sold = (TextView)convertView.findViewById(R.id.xml_cashSold);
holder.spot_buy = (TextView)convertView.findViewById(R.id.xml_spotBuy);
holder.spot_sold = (TextView)convertView.findViewById(R.id.xml_spotSold);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
RateBean rateItem = list.get(position);
holder.currency_name.setText(rateItem.getCurrency());
holder.cash_buy.setText(rateItem.getCashBuy());
holder.cash_sold.setText(rateItem.getCashSold());
holder.spot_buy.setText(rateItem.getSpotBuy());
holder.spot_sold.setText(rateItem.getSpotSold());
return convertView;
}
}
activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/title_textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="銀行查詢選擇"/>
<ListView
android:id="#+id/lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
activity_rate_show.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/updateTime_textView"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:hint="updateTime"/>
<Button
android:id="#+id/fresh_button"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="onClick"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/button_fresh"/>
</LinearLayout>>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp">
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.5"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/currency"/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/cash_buy"/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/cash_sold"/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/spot_buy"/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/spot_sold"/>
</LinearLayout>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
rate_item.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/xml_currency"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1.25"
android:textAppearance="?android:attr/textAppearanceLarge"
android:hint="text"/>
<TextView
android:id="#+id/xml_cashBuy"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:hint="text"/>
<TextView
android:id="#+id/xml_cashSold"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:hint="text"/>
<TextView
android:id="#+id/xml_spotBuy"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:hint="text"/>
<TextView
android:id="#+id/xml_spotSold"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:hint="text"/>
</LinearLayout>
<ListView
android:id="#+id/lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Your listview needs a height, it cannot be wrap_content. Give it a height like 500dp or match_parent.

ViewPager not loading properly when user swipes in Android

I have an Android View Pager with five screens with images, autoload pager screen with timer.
When user swipes, it is jumping screens based on timer, and is not loading properly.
I have attached code below.
MainActivity.java
package com.sks.androidviewpager;
import java.util.Timer;
import java.util.TimerTask;
import com.androidsurya.androidviewpager.R;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends Activity {
int noofsize = 5;
ViewPager myPager = null;
int count = 0;
Timer timer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set the layout which is containg viewPager Tag for image
setContentView(R.layout.activity_main);
//ViewPager Adapter to set image
ViewPagerAdapter adapter = new ViewPagerAdapter(MainActivity.this,noofsize);
myPager = (ViewPager) findViewById(R.id.reviewpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
// Timer for auto sliding
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(count<=5){
myPager.setCurrentItem(count);
count++;
}else{
count = 0;
myPager.setCurrentItem(count);
}
}
});
}
}, 500, 3000);
}
}
ViewPagerAdapter.java
package com.sks.androidviewpager;
import com.androidsurya.androidviewpager.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class ViewPagerAdapter extends PagerAdapter {
int size;
Activity act;
View layout;
TextView pagenumber1,pagenumber2,pagenumber3,pagenumber4,pagenumber5;
ImageView pageImage;
Button click;
public ViewPagerAdapter(MainActivity mainActivity, int noofsize) {
// TODO Auto-generated constructor stub
size = noofsize;
act = mainActivity;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return size;
}
#Override
public Object instantiateItem(View container, int position) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) act
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layout = inflater.inflate(R.layout.pages, null);
pagenumber1 = (TextView)layout.findViewById(R.id.pagenumber1);
pagenumber2 = (TextView)layout.findViewById(R.id.pagenumber2);
pagenumber3 = (TextView)layout.findViewById(R.id.pagenumber3);
pagenumber4 = (TextView)layout.findViewById(R.id.pagenumber4);
pagenumber5 = (TextView)layout.findViewById(R.id.pagenumber5);
pageImage = (ImageView)layout.findViewById(R.id.imageView1);
int pagenumberTxt=position + 1;
//pagenumber1.setText("Now your in Page No " +pagenumberTxt );
try {
if(pagenumberTxt == 1){
pageImage.setBackgroundResource(R.drawable.android_1);
pagenumber1.setTextColor(Color.RED);
pagenumber2.setTextColor(Color.WHITE);
pagenumber3.setTextColor(Color.WHITE);
pagenumber4.setTextColor(Color.WHITE);
pagenumber5.setTextColor(Color.WHITE);
}
else if(pagenumberTxt == 2){
pageImage.setBackgroundResource(R.drawable.android_2);
pagenumber1.setTextColor(Color.WHITE);
pagenumber2.setTextColor(Color.RED);
pagenumber3.setTextColor(Color.WHITE);
pagenumber4.setTextColor(Color.WHITE);
pagenumber5.setTextColor(Color.WHITE);
}else if(pagenumberTxt == 3){
pageImage.setBackgroundResource(R.drawable.android_3);
pagenumber1.setTextColor(Color.WHITE);
pagenumber2.setTextColor(Color.WHITE);
pagenumber3.setTextColor(Color.RED);
pagenumber4.setTextColor(Color.WHITE);
pagenumber5.setTextColor(Color.WHITE);
}
else if(pagenumberTxt == 4){
pageImage.setBackgroundResource(R.drawable.android_4);
pagenumber1.setTextColor(Color.WHITE);
pagenumber2.setTextColor(Color.WHITE);
pagenumber3.setTextColor(Color.WHITE);
pagenumber4.setTextColor(Color.RED);
pagenumber5.setTextColor(Color.WHITE);
}
else if(pagenumberTxt == 5){
pageImage.setBackgroundResource(R.drawable.android_5);
pagenumber1.setTextColor(Color.WHITE);
pagenumber2.setTextColor(Color.WHITE);
pagenumber3.setTextColor(Color.WHITE);
pagenumber4.setTextColor(Color.WHITE);
pagenumber5.setTextColor(Color.RED);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
((ViewPager) container).addView(layout, 0);
return layout;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
return null;
}
// }
}
activity_main.xml
<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"
tools:context=".MainActivity" >
<RelativeLayout
android:id="#+id/relativeTextview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/header"
android:padding="5dp" >
<android.support.v4.view.ViewPager
android:id="#+id/reviewpager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
</RelativeLayout>
pages.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/android_3"
android:contentDescription="#string/app_name" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="bottom|center" >
<TextView
android:id="#+id/pagenumber1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="#000"
android:onClick="pageOneClick"
android:text=" 1 "
android:textColor="#fff"
android:textSize="14sp"
android:textStyle="bold" />
<TextView
android:id="#+id/pagenumber2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="#000"
android:textColor="#fff"
android:text=" 2 "
android:textSize="14sp"
android:textStyle="bold" />
<TextView
android:id="#+id/pagenumber3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="#000"
android:textColor="#fff"
android:text=" 3 "
android:textSize="14sp"
android:textStyle="bold" />
<TextView
android:id="#+id/pagenumber4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="#000"
android:textColor="#fff"
android:text=" 4 "
android:textSize="14sp"
android:textStyle="bold" />
<TextView
android:id="#+id/pagenumber5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="#000"
android:textColor="#fff"
android:text=" 5 "
android:textSize="14sp"
android:textStyle="bold" />
</LinearLayout>
</FrameLayout>
Use
myPager.setCurrentItem(myPager.getCurrentItem()+1);
instead of myPager.setCurrentItem(count);
And you should judge if current item is the last item of this view pager.

How do I get a list of checked items from a custom ListView in Android?

I am experimenting with custom ListView's in Android. I have subclassed ArrayAdpater to hold an ArrayList of objects. The objects that get put in the ArrayAdapter come from a SQLite database.
In my ArrayAdapter class, I have overwritten the getView() method and inflate a custom view that puts an ImageView, 3 TextViews, and a Checkbox view on each row of the ListView.
I want to be able to get all the checked rows in my list do something with them, ie. remove them from the list and underlying database or edit the underlying data object represented by that row.
My problem is that I cannot seem to find a way to get my OnItemClickListener to work. The ListView displays fine but nothing happens when I click the row or if I check the checkbox and try to remove the checked items with my removeUnit() method. I've ran out of ideas.
What am I doing wrong here? Thanks for any help!
Here is my Activity
package com.mack.mylogger;
import android.os.Environment;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.*;
import android.database.Cursor;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.CheckBox;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import android.util.SparseBooleanArray;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import java.util.StringTokenizer;
import java.io.*;
import java.util.*;
public class ReportActivity extends Activity {
private Context context = null;
DBAdapter db = new DBAdapter(this); //my database adapter
ListView reportLV;
ArrayList<Integer> checkedPositions = new ArrayList<Integer>();
String TAG = "ReportActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_report);
// set up the list of finished units
reportLV = (ListView) findViewById(R.id.listview);
reportLV.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
ArrayList<RUnit> units = new ArrayList<RUnit>(); //init adapter with empty list
reportLV.setAdapter(new ReportLVAdapter(this, units));
reportLV.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.d(TAG, "Item is clicked at position: " + position);
CheckBox cb = (CheckBox) view.findViewById(R.id.checkbox);
cb.toggle();
if (cb.isChecked()) {
checkedPositions.add(position);
Log.d(TAG, "Item is checked at position: " + position);
} else if (!cb.isChecked()) {
checkedPositions.remove(position);
Log.d(TAG, "Item is unchecked at position: " + position);
}
}
});
// context
context = this.getBaseContext();
}
#Override
public void onResume() {
super.onResume();
updateListView();
}
private void updateListView() {
// get list of units
db.read();
RUnit[] allUnits = db.getAllUnits();
ArrayList<RUnit> finishedUnits = new ArrayList<RUnit>();
System.out.println("Units in database: " + allUnits.length);
RUnit unit;
for (int i=0; i<allUnits.length; i++) {
unit = allUnits[i];
// check status
if (unit.getStatus() == "Finished") {
finishedUnits.add(unit);
}
}
// update adapter with updated list of finished units
reportLV.setAdapter(new ReportLVAdapter(this, finishedUnits));
}
public void addUnit(View view) {
// method to run when "Add" button is clicked
Intent intent = new Intent(this, AddActivity.class);
startActivity(intent);
}
public void removeUnit(View view) {
// method to run when remove button is clicked
// loop thru the items in the ListView and remove checked items from the db
for (int i=0; i<checkedPositions.size(); i++) {
String unitStr = reportLV.getItemAtPosition(i).toString();
Log.d(TAG, "Removing unit: " + unitStr);
// remove unit from the database
db.deleteUnit(unitStr);
}
//update the LV
updateListView();
}
public void submit(View view) {
// do something here
}
}
Here is my ArrayAdapter
package com.mack.mylogger;
import android.app.Activity;
import android.util.*;
import android.graphics.Color;
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 android.widget.CheckBox;
import android.view.View.OnClickListener;
import java.util.*;
public class ReportLVAdapter extends ArrayAdapter<RUnit> {
private final Activity context;
private final ArrayList<RUnit> units;
String TAG = new String("ReportLVAdapter");
static class ViewHolder {
public TextView serial;
public TextView status;
public TextView date;
public ImageView model;
public ImageView flag;
public CheckBox checkbox;
}
public ReportLVAdapter(Activity context, ArrayList<RUnit> units) {
super(context, R.layout.adapterlv_report, units);
this.context = context;
this.units = units;
Log.d(TAG, "Size of adapter array: " + units.size());
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
ViewHolder viewHolder = new ViewHolder();
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.adapterlv_report, null);
viewHolder.serial = (TextView) rowView.findViewById(R.id.serial);
viewHolder.model = (ImageView) rowView.findViewById(R.id.model);
viewHolder.status = (TextView) rowView.findViewById(R.id.status);
viewHolder.date = (TextView) rowView.findViewById(R.id.date);
viewHolder.flag = (ImageView) rowView.findViewById(R.id.flag);
viewHolder.checkbox = (CheckBox) rowView.findViewById(R.id.checkbox);
rowView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) rowView.getTag();
}
// Need to handle empty database situation
// get info from RUnit obj
RUnit unit = units.get(position);
String sn = unit.getSerialNumAsString();
String mdl = unit.getModel();
String stat = unit.getStatus();
// date
String d;
if (stat == "Finished") { d = unit.getFinishDate(); }
else if (stat == "Submitted") { d = unit.getSubmitDate(); }
else if (stat == "Shipped") { d = unit.getShipDate(); }
else { d = "NA"; }
// flags
String[] flags = unit.getFlags();
///// Set view values
// text values
viewHolder.serial.setText(sn);
viewHolder.status.setText(stat);
viewHolder.date.setText(d);
// set model image
if (mdl == "TK") {
viewHolder.model.setImageResource(R.drawable.tk_icon);
} else {
// must be carrier
viewHolder.model.setImageResource(R.drawable.carrier_icon);
}
// set flag image - only look for hold
for (int i=0; i<flags.length; i++) {
if (flags[i] == "hold") {
// set hold image
viewHolder.flag.setImageResource(R.drawable.hold_flag);
} else {
// no image
}
}
return rowView;
}
My activity XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:text="#string/main_title"
android:textAlignment="gravity"
android:textAllCaps="true"
android:textSize="36sp"
android:textStyle="bold" />
<TextView
android:id="#+id/subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:text="#string/report_subtitle"
android:textAlignment="gravity"
android:textAllCaps="true"
android:textSize="24sp"
android:textStyle="bold" />
<Button
android:id="#+id/button_submit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_gravity="center_horizontal"
android:text="#string/button_submit"
android:onClick="submit"
android:textSize="26sp" />
<LinearLayout
android:id="#+id/button_group"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/button_submit"
android:layout_gravity="center_vertical"
android:orientation="horizontal" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_weight="1.0"
android:onClick="addUnit"
android:text="#string/button_add_fg" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_weight="1.0"
android:text="#string/button_modify_fg" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_weight="1.0"
android:onClick="removeUnit"
android:text="#string/button_remove_fg" />
</LinearLayout>
<ListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#id/button_group"
android:layout_below="#id/subtitle"
android:footerDividersEnabled="true"
android:headerDividersEnabled="true" />
</RelativeLayout>
My custom View for the rows XML
<?xml version="1.0" encoding="utf-8"?>
<GridLayout
xmlns:tools="http://schemas.android.com/tools"
android:columnCount="5"
android:rowCount="2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="#+id/model"
android:layout_row="0"
android:layout_column="0"
android:layout_margin="5dip"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/serial"
android:layout_row="0"
android:layout_column="1"
android:layout_columnSpan="2"
android:textSize="35dp"
android:textStyle="bold"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/status"
android:layout_row="1"
android:layout_column="0"
android:layout_columnSpan="2"
android:textSize="20dp"
android:textStyle="italic"
android:layout_marginLeft="10dip"
android:layout_marginRight="5dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/date"
android:layout_row="1"
android:layout_column="2"
android:textSize="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="#+id/flag"
android:layout_row="0"
android:layout_column="3"
android:layout_rowSpan="2"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<CheckBox
android:id="#+id/checkbox"
android:layout_row="0"
android:layout_column="4"
android:layout_rowSpan="2"
android:layout_gravity="right"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</GridLayout>
You can call getCheckedItemPositions() on the list view. This will return a SparseBooleanArray containing ALL items in the list and whether or not they are checked. Once you have that, you can loop through the array and use valueAt(i) to determine if an item is selected or not.
Here's a good article on this topic.
You can try this
SparseBooleanArray checkedPositions = lv.getCheckedItemPositions ();int size = checkedPositions.size ();for (int i=0 ; i<size ; i++) {
// We get the key stored at the index 'i'
int key = checkedPositions.keyAt (i);
// We get the boolean value with the key
Log.i (Tag, "checkedPositions(" + key + ")=" + checkedPositions.get (key));}

ListView setOnItemClickListener isn't working

Like the title says, my setOnItemClickListener isn't working. I looked through everything I've seen so far on SO and couldn't find my error.
This is the code:
This is the problematic class. It isn't the main class, but is called from an intent:
package...;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
public class GroupActivity extends Activity {
String group_id = "";
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group);
context = this;
Intent intent = getIntent();
group_id = intent.getStringExtra("group_id");
Log.i("bla", "Launched GroupActivity for group_id " + group_id);
final SubAdapter adapter = new SubAdapter(this, group_id);
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setClickable(true);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> av, View v, int idx, long lidx) {
Log.i("print here", "blaa " + idx);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
This is the SubAdapter class:
package...;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.format.DateUtils;
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;
public class SubAdapter extends BaseAdapter {
private static final int thumb_width = 128;
private static final int thumb_hight = 128;
private static Bitmap default_thumb = null;
private static LayoutInflater inflater = null;
private final String group_id_;
private final Activity activity;
private final SubAdapter t = this;
// used to keep selected position in ListView
private int selectedPos = -1; // init value for not-selected
public SubAdapter(Activity a, final String group_id) {
Drawable d = a.getResources().getDrawable(R.drawable.ic_contact_picture);
default_thumb = ((BitmapDrawable) d).getBitmap();
activity = a;
group_id_ = group_id;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int idx, View convertView, ViewGroup parent) {
Log.i("bla2", "getting view with index " + idx);
View vi = convertView;
if (convertView == null) {
vi = inflater.inflate(R.layout.sub_list_item, null);
vi.setClickable(true);
}
TextView tv1 = (TextView)vi.findViewById(R.id.textView1);
TextView tv2 = (TextView)vi.findViewById(R.id.textView2);
ImageView img = (ImageView)vi.findViewById(R.id.imageView1);
tv1.setText("first name" + " " + "last name");
tv2.setText("some date");
// put thumbnail
Bitmap thumb = default_thumb;
img.setImageBitmap(thumb);
Log.i("bla3", "index is " + idx + "selected index is " + selectedPos);
if(selectedPos == idx){
Log.i("bla4", "inside if");
}
return vi;
}
public void setSelectedPosition(int pos){
selectedPos = pos;
// inform the view of this change
notifyDataSetChanged();
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
This is the activity_group xml:
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".GroupActivity" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusableInTouchMode="false"
android:focusable="false" >
</ListView>
</RelativeLayout>
This is the sub_list_item xml:
<?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:clickable="true"
android:focusable="false"
android:focusableInTouchMode="false">
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_margin="6dp"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_margin="6dp"
android:layout_toLeftOf="#+id/toggleButton1"
android:layout_toRightOf="#+id/imageView1"
android:text="some text"
android:textAppearance="?android:attr/textAppearance" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_toLeftOf="#+id/toggleButton1"
android:text="more text"
android:textAppearance="?android:attr/textAppearance" />
<ToggleButton
android:id="#+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_margin="6dp"
android:text="present" />
</RelativeLayout>
Apart from the click listener, everything else seems to work. The SubAdapter opens properly and the list is populated.
Basically what I'm looking for is to get the message "Log.i("print here", "blaa " + idx);" to print - it is the log from the ListView's setOnItemClickListener (look above)
Please let me know if there is any other relevant code missing
Thanks!!!
In your GroupActivity class please add the following code before findViewById method:
now you get the view same and change your code
ListView lv = (ListView) findViewById(R.id.listView1);
to
final View v = inflater.inflate(R.layout.rescuer_no_dialog, null);
ListView lv = (ListView)v.findViewById(R.id.listView1);
You should probably remove the call to
vi.setClickable(true); in your SubAdapter class, because your convertView will consume the click before you onItemClick listener.
Change this
ListView lv = (ListView) findViewById(R.id.listView1);
to
lv = getListView()
Extend ListActivity and declare lv outside methods.

Categories

Resources