I have a listview utilizing a custom adapter, now I want it to show the first five entries and load the others when I scroll down, what's the simplest way to do this?
If my code for the list is
public class Second extends Activity {
static final String Li_nk="LinkName:";
static final String Image_name="ImageName:";
//ListView list;
public final static String AUTH = "authentication";
static final String KEY_THUMB_URL = "thumb_image"; //Uri.decode("http://zeesms.info/android_app_images/Koala.jpg");
//JSONObject j2;
String wrd;
//ArrayList<HashMap<String,String>> mylist;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent i2=getIntent();
wrd=i2.getStringExtra("entrd");
Log.v("keyis",wrd);
final Handler handler = new Handler();
Runnable runable = new Runnable() {
#Override
public void run() {
//call the function
LoadData();
//also call the same runnable
handler.postDelayed(this, 40000);
}
};
handler.postDelayed(runable, 10);
}public void LoadData(){
JSONObject j2=JSONfunctions.getJSONfromURL("/webservice_search.php?keyword="+wrd+"&format=json");
ArrayList<HashMap<String,String>> mylist = new ArrayList<HashMap<String,String>>();
try{JSONArray jray=j2.getJSONArray("listings");
for(int i=0;i<jray.length();i++){
Log.v("state","json data being read");
JSONObject j3= jray.getJSONObject(i);
String first=j3.getString("listing");
Log.v("sublist", first);
JSONObject j4=j3.getJSONObject("listing");
String sec=j4.getString("links");
int maxLength = (sec.length() < 30)?sec.length():27;
sec.substring(0, maxLength);
String cutsec=sec.substring(0,maxLength);
Log.v("links are",cutsec);
String img=j4.getString("image_name");
Log.v("image name is ",img);
//Uri dimg=Uri.parse("http://zeesms.info/android_app_images/Koala.jpg");
HashMap<String,String> map=new HashMap<String,String>();
map.put("Id",String.valueOf(i));
map.put(Li_nk,cutsec);
map.put(Image_name,j4.getString("image_name"));
map.put(KEY_THUMB_URL,"http://zeesms.info/android_app_images/"+img);
mylist.add(map);
}
}
catch(JSONException e){
Log.e("loG_tag","Error parsing"+e.toString());
}
LazyAdapter adapter = new LazyAdapter(this,mylist);
adapter.notifyDataSetChanged();
// list.setSelection(positionToMove);
ListView list=(ListView)findViewById(R.id.lv1);
list.setEmptyView(findViewById(R.id.empty));
list.setAdapter(adapter);
// list.setStackFromBottom(true);
list.setItemsCanFocus(false);
// list.smoothScrollToPosition(3,5);
list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Toast.makeText(getApplicationContext(),"Click ListItem Number " + position, Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.riffre.com/"));
startActivity(myIntent);
}
});
list.setOnScrollListener(new OnScrollListener(){
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
}
#Override
public void onScrollStateChanged(AbsListView view,
int scrollState) {
// TODO Auto-generated method stub
}
});
}
and the code for the adapter class extending baseadapter is
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
Collections.reverse(d);
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.custom_row_view1, null);
TextView title = (TextView)vi.findViewById(R.id.linkname); // merchnts name
TextView artist = (TextView)vi.findViewById(R.id.imagename); // address
//TextView duration = (TextView)vi.findViewById(R.id); // distance
ImageView thumb_image=(ImageView)vi.findViewById(R.id.mClogo); // logo
HashMap<String, String> jsn = new HashMap<String, String>();
jsn = data.get(position);
// Setting all values in listview
title.setText(jsn.get(Second.Li_nk));
artist.setText(jsn.get(Second.Image_name));
//duration.setText(song.get(CustomizedListView.KEY_DURATION));
imageLoader.DisplayImage(jsn.get(Second.KEY_THUMB_URL), thumb_image);
return vi;
}
}
and I have a different class for parsing the json data in the list. So what would be the simplest way to implement endless scrolling?
Any help would be greatly appreciated...
If you load your items from network(so time delay is expected), check this library project : https://github.com/chrisbanes/Android-PullToRefresh
This is an awesome pull-to-refresh listview project, but it also provides pull to refresh from bottom. So you can use that feature to load more items. But this feature need explicit pull action from user.
Found the solution by declaring my list as a global variable. Thanks anyway for your help.
Related
In my app I am trying to save data using ArrayList<HashMap<String, String>>
below is my code:
JsonArrayRequest req = new JsonArrayRequest(Constants.DARSHAN_URL+Constants.MAIN_CATEGORY,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
// Parsing json array response
// loop through each json object
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String material_id = person.getString("material_id");
String material_desc = person.getString("material_desc");
HashMap<String, String> maim_category_array = new HashMap<>();
maim_category_array.put("material_id", material_id);
maim_category_array.put("material_desc", material_desc);
categoryName.add(maim_category_array);
}
adapter = new GridviewAdapter(MainCategoryActivity.this, categoryName);
grid.setAdapter(adapter);
And below is my GridViewCoustomAdapter:
public class GridviewAdapter extends BaseAdapter
{
private ArrayList<HashMap<String, String>> listCountry;
private Activity activity;
public GridviewAdapter(Activity activity, ArrayList<HashMap<String, String>> listCountry) {
super();
this.listCountry = listCountry;
this.activity = activity;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listCountry.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listCountry.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder
{
public TextView txtViewTitle;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if(convertView==null)
{
view = new ViewHolder();
convertView = inflator.inflate(R.layout.button_layout, null);
view.txtViewTitle = (TextView) convertView.findViewById(R.id.btn_select);
convertView.setTag(view);
}
else
{
view = (ViewHolder) convertView.getTag();
}
HashMap<String, String> map = new HashMap<String, String>();
map = listCountry.get(position);
view.txtViewTitle.setText(map.get("material_desc"));
return convertView;
}}
Now I want to get the material_Id to send to next activity. i.e. I want to get matrial_Id onItemClick of gridview
for example:
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Toast.makeText(MainCategoryActivity.this, adapter.getItem(position), Toast.LENGTH_SHORT).show();
Intent i = new Intent(MainCategoryActivity.this, ProductNameActivity.class);
i.putExtra("MATERIAL_ID", <material_id>);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
});
How can I do this??
Please help!!
In onItemClick
HashMap<String, String> map = (HashMap<String, String>)arg0.getItemAtPosition(position);
Then
String id = map.get("material_id");
I just want to get the value of clicked list item,
i.e if list contains apple,ball,cat, then clicked on apple then it gives value as apple, ,In the below code I am using inner class base adapter to display the data.
public class RecordsActivity extends Activity implements
OnItemClickListener
{
ListView listProduct;
ListAdapter adapter;
TextView UserName,Date;
ArrayList<String> billDate = new ArrayList<String>();
ArrayList<String> billNo = new ArrayList<String>();
ArrayList<String >partyName=new ArrayList<String>();
ArrayList<String> billAmount = new ArrayList<String>();
ArrayList<String >receipt=new ArrayList<String>();
ArrayList<String >balance=new ArrayList<String>();
ArrayList<String> week = new ArrayList<String>();
ArrayList<String> amount = new ArrayList<String>();
String get_name,get_date,Name;
String GetAmnt;
Dialog dialog;
AlertDialog alertDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_records);
UserName=(TextView) findViewById(R.id.txt_disuser);
Intent usr=getIntent();
get_name=usr.getStringExtra("user");
UserName.setText(get_name);
Date=(TextView) findViewById(R.id.txt_disdate);
Intent dt=getIntent();
get_date=dt.getStringExtra("date");
Date.setText(get_date);
Intent id =getIntent();
Name=id.getStringExtra("name");
listProduct=(ListView) findViewById(R.id.ListViewFilledRecrd);
listProduct.setAdapter(adapter);
/*listProduct.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3)
{
listProduct.setClickable(true);
String data = (String)listProduct.getItemAtPosition(arg2);
Toast.makeText(getApplicationContext(),data,
Toast.LENGTH_SHORT).show();
}
});*/
}
protected void onResume()
{
getAllProduct();
super.onResume();
}
public void getAllProduct(){
SQLiteDatabase db = this.getDB();
Cursor c;
//c=db.rawQuery("SELECT * FROM RECORDS", null);
c=db.rawQuery("SELECT * FROM RECORDS WHERE PARTY_NAME = '" + Name +
"' ", null);
String
BILL_DATE,BILL_NO,PARTY_NAME,BILL_AMOUNT,RECEIPT,BALANCE,WEEK,AMOUNT;
if(c.moveToFirst())
{
do
{
BILL_DATE = c.getString(1);
BILL_NO=c.getString(2);
PARTY_NAME=c.getString(3);
BILL_AMOUNT=c.getString(4);
RECEIPT=c.getString(5);
BALANCE=c.getString(6);
WEEK=c.getString(7);
AMOUNT=c.getString(8);
billDate.add(BILL_DATE);
billNo.add(BILL_NO);
partyName.add(PARTY_NAME);
billAmount.add(BILL_AMOUNT);
receipt.add("RECEIPT");
balance.add(BALANCE);
week.add(WEEK);
amount.add(AMOUNT);
} while (c.moveToNext());
}
DisplyRecords dsptProd=new
DisplyRecords(RecordsActivity.this,billDate,billNo,partyName,
billAmount,receipt,balance,week,amount);
listProduct.setAdapter(dsptProd);
listProduct.setOnItemClickListener(this);
c.close();
db.close();
}
private SQLiteDatabase getDB()
{
String DB_NAME = "odsr.db";
return openOrCreateDatabase(DB_NAME, SQLiteDatabase.OPEN_READWRITE,
null);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
}
}
class DisplyRecords extends BaseAdapter
{
Context c;
ArrayList<String > BILLDATE;
ArrayList<String>BILLNO;
ArrayList<String> PARTYNAME;
ArrayList<String>BILLAMOUNT;
ArrayList<String>RECEIPT;
ArrayList<String> BALANCE;
ArrayList<String>WEEK;
ArrayList<String>AMOUNT;
public DisplyRecords(RecordsActivity recordsactivity,ArrayList<String>
billDate, ArrayList<String> billNo, ArrayList<String>
partyName,ArrayList<String> billAmount, ArrayList<String> receipt,
ArrayList<String> balance, ArrayList<String> week,ArrayList<String> amount)
{
this.c=recordsactivity;
this.BILLDATE=billDate;
this.BILLNO=billNo;
this.PARTYNAME=partyName;
this.BILLAMOUNT=billAmount;
this.RECEIPT=receipt;
this.BALANCE=balance;
this.WEEK=week;
this.AMOUNT=amount;
//TODO Auto-generated constructor stub
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return BILLDATE.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int pos, View row, ViewGroup parent)
{
View child=row;
LayoutInflater layoutinflater;
if(child==null)
{
layoutinflater=(LayoutInflater)
c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutinflater.inflate(R.layout.list_product,null);
}
TextView txt_billdate=(TextView) child.findViewById(R.id.txt_bill_date);
TextView txt_billno=(TextView) child.findViewById(R.id.txt_bill_no);
TextView txt_partyname=(TextView)
child.findViewById(R.id.txt_party_name);
TextView txt_billamt=(TextView)
child.findViewById(R.id.txt_bill_amount);
TextView txt_receipt=(TextView) child.findViewById(R.id.txt_receipt);
TextView txt_balance=(TextView) child.findViewById(R.id.txt_balance);
TextView txt_wk=(TextView) child.findViewById(R.id.txt_week);
TextView txt_amount=(TextView) child.findViewById(R.id.txt_amount);
txt_billdate.setText(BILLDATE.get(pos));
txt_billno.setText(BILLNO.get(pos));
txt_partyname.setText(PARTYNAME.get(pos));
txt_billamt.setText(BILLAMOUNT.get(pos));
txt_receipt.setText(RECEIPT.get(pos));
txt_balance.setText(BALANCE.get(pos));
txt_wk.setText(WEEK.get(pos));
txt_amount.setText(AMOUNT.get(pos));
// TODO Auto-generated method stub
return child;
}
}
A few assumptions here, your actual fields do not need to be ArrayList's since each query returns a single row item from the db, i create a master object with Strings to represent the data...
So here is how i would do it, you need to re structure your data
First i would change your data to a :
public class ParentObject {
public String BILLDATE ;
public String BILLNO ;
public String PARTYNAME ;
public String BILLAMOUNT ;
public String RECEIPT ;
public String BALANCE ;
public String WEEK ;
public String AMOUNT ;
}
UPDATE
then i would change my Activity to:
public class RecordsActivity extends Activity implements OnItemClickListener{
ListView listProduct;
ListAdapter adapter;
TextView UserName,Date;
// your new parent object ArrayList, much cleaner
List<ParentObject> parentObjects;
String get_name,get_date,Name;
String GetAmnt;
Dialog dialog;
AlertDialog alertDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_records);
UserName=(TextView) findViewById(R.id.txt_disuser);
Intent usr=getIntent();
get_name=usr.getStringExtra("user");
UserName.setText(get_name);
Date=(TextView) findViewById(R.id.txt_disdate);
Intent dt=getIntent();
get_date=dt.getStringExtra("date");
Date.setText(get_date);
Intent id =getIntent();
Name=id.getStringExtra("name");
listProduct=(ListView) findViewById(R.id.ListViewFilledRecrd);
listProduct.setAdapter(adapter);
listProduct.setOnItemClickListener(this);
}
protected void onResume(){
getAllProduct();
super.onResume();
}
public void getAllProduct(){
SQLiteDatabase db = this.getDB();
Cursor c;
//c=db.rawQuery("SELECT * FROM RECORDS", null);
c=db.rawQuery("SELECT * FROM RECORDS WHERE PARTY_NAME = '" + Name + "' ", null);
String BILL_DATE,BILL_NO,PARTY_NAME,BILL_AMOUNT,RECEIPT,BALANCE,WEEK,AMOUNT;
if(c.moveToFirst()){
// initialize the parent arrayList
parentObjects = new ArrayList<ParentObject>();
do{
// initialize a single object
ParentObject parentObject = new ParentObject();
// fill in its data
parentObject.BILL_DATE = c.getString(1);
parentObject.BILL_NO=c.getString(2);
parentObject.PARTY_NAME=c.getString(3);
parentObject.BILL_AMOUNT=c.getString(4);
parentObject.RECEIPT=c.getString(5);
parentObject.BALANCE=c.getString(6);
parentObject.WEEK=c.getString(7);
parentObject.AMOUNT=c.getString(8);
// add it to your list
parentObjects.add(parentObject);
} while (c.moveToNext());
}
// pass the List<ParentObject> into your adapter
DisplyRecords dsptProd= new DisplyRecords(RecordsActivity.this, (ArrayList<ParentObject>)parentObjects);
listProduct.setAdapter(dsptProd);
listProduct.setOnItemClickListener(this);
c.close();
db.close();
}
private SQLiteDatabase getDB(){
String DB_NAME = "odsr.db";
return openOrCreateDatabase(DB_NAME, SQLiteDatabase.OPEN_READWRITE,
null);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
// access to all your data through the parentObject
ParentObject data = (ParentObject) listProduct.getItemAtPosition(position);
// access all fields for this parent
Toast.makeText(RecordsActivity.this, "data: "+ data.BILL_DATE, + " ," + data.BILL_NO, " , etc", Toast.LENGTH_LONG).show();
}
}
and then update your Adapter to handle the List
class DisplyRecords extends BaseAdapter {
Context c;
List<ParentObject> parentObjects;
public DisplyRecords(Context context, ArrayList<ParentObject> parentObjects){
this.c=context;
this.parentObjects = parentObjects;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return parentObjects.size();
}
#Override
public Object getItem(int position) {
return parentObjects.get(position); // always return this parent
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int pos, View row, ViewGroup parent){
// You should implement the ViewHolder pattern, this is not doing that...
View child=row;
LayoutInflater layoutinflater;
if(child==null){
layoutinflater=(LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutinflater.inflate(R.layout.list_product,null);
}
TextView txt_billdate=(TextView) child.findViewById(R.id.txt_bill_date);
TextView txt_billno=(TextView) child.findViewById(R.id.txt_bill_no);
TextView txt_partyname=(TextView) child.findViewById(R.id.txt_party_name);
TextView txt_billamt=(TextView) child.findViewById(R.id.txt_bill_amount);
TextView txt_receipt=(TextView) child.findViewById(R.id.txt_receipt);
TextView txt_balance=(TextView) child.findViewById(R.id.txt_balance);
TextView txt_wk=(TextView) child.findViewById(R.id.txt_week);
TextView txt_amount=(TextView) child.findViewById(R.id.txt_amount);
ParentObject parentObject = parentObjects.get(pos);
txt_billdate.setText(parentObject.BILLDATE);
txt_billno.setText(parentObject.BILLNO.);
txt_partyname.setText(parentObject.PARTYNAME);
txt_billamt.setText(parentObject.BILLAMOUNT);
txt_receipt.setText(parentObject.RECEIPT);
txt_balance.setText(parentObject.BALANCE);
txt_wk.setText(parentObject.WEEK);
txt_amount.setText(parentObject.AMOUNT);
// TODO Auto-generated method stub
return child;
}
}
I have a custom adapter for GridView Adapter
I want to get an specific value from the selected Item such as "stamp ID"
I was developing this to display only the stamps long time ago and now I want to be able to click on one stamp to send him to next page
I looked in the internet for a solution but most of the tutorials require me to modify a lot on the Adapter code (Witch means creating a new class)
I need to know if there a simple way to fix this using the adapter that I am using.
this is the part on StampActiviy class where connect
GridView gridView = (GridView) findViewById(R.id.gvStamps);
// Pass the results into ListViewAdapter.java adapterCollected,adapterunCollected
adapterListStamps = new ListViewListStampsAdapter(KioskStampsListActivity.this, arraylistStamps);
// Set the adapter to the ListView
gridView.setAdapter(adapterListStamps);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// I need to get StampId then send the user to next screen
Toast.makeText(KioskStampsListActivity.this, ""+arg2+" - "+stampsUtil.getStampId(), Toast.LENGTH_LONG).show();
}
});
this is the ListViewListStampsAdapter
public class ListViewListStampsAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewListStampsAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView tvStampName, tvStampId;
ImageView stampImage;
String STAMP_IMAGE_URL = SharedPrefUtils.getUrl(context, "images/stamp/");
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.single_stamp_layout, parent, false);
// Get the position
resultp = data.get(position);
tvStampName = (TextView) itemView.findViewById(R.id.tvStampName);
tvStampId = (TextView) itemView.findViewById(R.id.tvStampId);
stampImage = (ImageView) itemView.findViewById(R.id.stampImage);
tvStampName.setText(resultp.get(KioskStampsListActivity.TAG_STAMP_NAME));
tvStampId.setText(resultp.get(KioskStampsListActivity.TAG_STAMPS_ID));
// Passes stampImage images URL into ImageLoader.class
imageLoader.DisplayImage(STAMP_IMAGE_URL+resultp.get(StampsActivity.TAG_STAMP_IMAGE), stampImage);
Animation myFadeInAnimation = AnimationUtils.loadAnimation(context, R.anim.fadein);
stampImage.startAnimation(myFadeInAnimation);
return itemView;
}
}
this is StampUtil class
public class StampsUtil {
private static String StampId, message, stampimage, stampname;
public String getStampId() {
return StampId;
}
public void setStampId(String stampId) {
StampId = stampId;
}
public static String getMessage() {
return message;
}
public static void setMessage(String message) {
StampsUtil.message = message;
}
public static String getStampimage() {
return stampimage;
}
public static void setStampimage(String stampimage) {
StampsUtil.stampimage = stampimage;
}
public static String getStampname() {
return stampname;
}
public static void setStampname(String stampname) {
StampsUtil.stampname = stampname;
}
}
Thanks
Try below code:
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// I need to get StampId then send the user to next screen
Toast.makeText(KioskStampsListActivity.this, ""+arg2+" - "+stampsUtil.getStampId(), Toast.LENGTH_LONG).show();
System.out.println(arraylistStamps.get(i).getStampId());// you can get value
}
});
You can use
grid.getItemAtPosition(position).toString();
I have used like this:-
public static String getUrl(int position){
String itemName = grid.getItemAtPosition(position).toString();
return itemName;// Return your string value
}
OR
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
String itemName = grid.getItemAtPosition(position).toString();
}});
and in Adapter :-
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return web[position]; //--> web is my array of string
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
I have implemented listview in fragment. In that listview i have used custom adapter to display images with their description. Data is coming from web server. There are many list items with image so I'd like to implement on scroll load ListView for the same.
Which approach should i follow to do the same? I have tried to google it and found some sample but it does not fit into my requirement.
Here is the code of my Fragment containing listview. Thanks in advance.
FragmentTab1.class
public class FragmentTab1 extends Fragment implements
AdapterView.OnItemClickListener {
DisplayImageOptions options;
protected ImageLoader imageLoader = ImageLoader.getInstance();
JSONArray AdsArray = null;
String TAG_IMAGE = "image";
String TAG_DISCRIPTION = "description";
ListView lv;
final Context context = getActivity();
static ArrayList<HashMap<String, String>> adList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragmenttab1, container,false);
options = new DisplayImageOptions.Builder().showStubImage(R.drawable.no_image).cacheInMemory().cacheOnDisc()
.bitmapConfig(Bitmap.Config.RGB_565).build();
lv = (ListView) rootView.findViewById(R.id.listView1);
lv.setOnItemClickListener(this);
adList = new ArrayList<HashMap<String, String>>();
new LoadMyAds().execute();
return rootView;
}
class LoadMyAds extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
UserFunctions userFunction = new UserFunctions();
String type = "all";
JSONObject json = userFunction.myAds(userid, type);
try {
if (json.getString("status") != null) {
String res = json.getString("status");
if (Integer.parseInt(res) == 1) {
adList.clear();
AdsArray = json.getJSONArray("myadslistsArray");
for (int i = 0; i < AdsArray.length(); i++) {
JSONObject c = AdsArray.getJSONObject(i);
String description = c.getString(TAG_DISCRIPTION);
String image = c.getString(TAG_IMAGE);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_IMAGE, image);
map.put(TAG_DISCRIPTION, description); adList.add(0, map);
}
} else {
Toast.makeText(getActivity().getApplicationContext(),
"parsing error", Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
// image parameter need to be added
lv.setAdapter(new CustomAdapter(adList));
}
}
class CustomAdapter extends BaseAdapter {
ArrayList<HashMap<String, String>> locallist;
public CustomAdapter(ArrayList<HashMap<String, String>> list) {
// TODO Auto-generated constructor stub
locallist = list;
imageLoader.init(ImageLoaderConfiguration
.createDefault(getActivity()));
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return locallist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
// return null;
return getItem(getCount() - position - 1);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
if (row == null) {
row = getActivity().getLayoutInflater().inflate(
R.layout.ad_list_item, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.desc= (TextView) row.findViewById(R.id.title);
viewHolder.img = (ImageView) row.findViewById(R.id.thumbImage);
row.setTag(viewHolder);
}
final ViewHolder holder = (ViewHolder) row.getTag();
holder.desc.setText(""+locallist.get(position).get(TAG_DISCRIPTION));
imageLoader.displayImage(locallist.get(position).get(TAG_IMAGE),
holder.img, options);
return row;
}
}
class ViewHolder {
protected TextView desc;
protected ImageView img;
}
}
Attach scroll listener to the listView
lv.setOnScrollListener(new EndlessScrollListener());
Here is the class implementation:
class EndlessScrollListener implements OnScrollListener {
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
new LoadMyAds().execute();
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
}
I need to display my arraylist data in listview. My arraylist is of type public static ArrayList<ArrayList<String>> ourstringList1. In my listadapter class I am trying to get the data from arraylist and setting it to tesxtview. But since I need arr.get(i).get(j)...I am unable to proceed further.
Please help me regarding this...
My code:
public class testreview extends Activity {
private ListView listViewScore = null;
private ListViewAdapter listViewAdapter = null;
public static ArrayList<ArrayList<String>> ourstringList1 = Select.stringList1;
private ArrayList<ArrayList<String>> usernameArrLst = ourstringList1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
listViewScore=(ListView)findViewById(R.id.list);
usernameArrLst = new ArrayList<ArrayList<String>>();
listViewAdapter = new ListViewAdapter();
listViewScore.setAdapter(listViewAdapter);
}
class ListViewAdapter extends BaseAdapter{
#Override
public int getCount() {
// TODO Auto-generated method stub
if(usernameArrLst==null){
return 0;
}
return usernameArrLst.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return usernameArrLst.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
// TODO Auto-generated method stub
View rowView=view;
if(rowView==null){
LayoutInflater layoutinflate =LayoutInflater.from(testreview.this);
rowView=layoutinflate.inflate(R.layout.listrow, parent, false);
}
TextView textViewName=(TextView)rowView.findViewById(R.id.tv_case);
textViewName.setText((CharSequence) usernameArrLst.get(position));
return rowView;
}
}
}
Thanks in advance
for this purpose i think you need to write your custom adapter and set to the list
Get The Idea
Hope this will help you.
Sorry, did not see you had imbricated ArrayList. To get the elements you need, use class casting to get to the inner ArrayList and iterate trough them.
ArrayList<ArrayList<String>> stringList;
stringList = ourStringList1;
for (int i = 0; i < stringList.size(); i++) {
ArrayList<String> innerStringList = (ArrayList<String>) stringList.get(i);
for (int j = 0; j < innerStringList.size(); j++) {
String value = (String) innerStringList.get(j);
// put the value in the textView
}
}
When you build your Adapter class, create a class attribute that will hold the array of ArrayList and initialize it in the constructor.
Hope this helps. If you need further explanation let me know.
sweety if u have showed us what you have tried then it should have been better.But as per my understanding ur code should look like this :
public class TestProjeectActivity extends Activity {
private ListView listViewScore = null;
private ListViewAdapter listViewAdapter = null;
private String[] usernameArr = null;
private ArrayList<String> usernameArrLst = null;
//private Helper helper = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listViewScore=(ListView)findViewById(R.id.listViewScore);
//helper = new Helper(TestProjeectActivity.this);
//usernameArr = helper.getUserName();
usernameArr = new String[]{"Alan","Bob"};
usernameArrLst = new ArrayList<String>(Arrays.asList(usernameArr));//Changed line
listViewAdapter = new ListViewAdapter();
listViewScore.setAdapter(listViewAdapter);
}
class ListViewAdapter extends BaseAdapter{
#Override
public int getCount() {
// TODO Auto-generated method stub
if(usernameArrLst==null){
return 0;
}
return usernameArr.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return usernameArrLst.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
// TODO Auto-generated method stub
View rowView=view;
if(rowView==null){
LayoutInflater layoutinflate =LayoutInflater.from(TestProjeectActivity.this);
rowView=layoutinflate.inflate(R.layout.listviewtext, parent, false);
}
TextView textViewName=(TextView)rowView.findViewById(R.id.textViewName);
textViewName.setText(usernameArr.get(position));
return rowView;
}
}
}