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) {
}
}
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");
public class Setting extends Activity implements OnClickListener {
ListView listView1;
ImageView backbutton;
String Url = "http://182.71.212.110:8083/api/values/userdetails";
String Id;
String Designation;
String EmployeeName;
JSONArray _jarray;
DataModel datamodel = new DataModel();
ArrayList<DataModel> list = new ArrayList<DataModel>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.setting);
listView1 = (ListView) findViewById(R.id.listView1);
backbutton = (ImageView) findViewById(R.id.backbutton);
backbutton.setOnClickListener(this);
new GetUserdetail().execute();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.backbutton) {
finish();
}
}
class GetUserdetail extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
String json = HttpHitter.ExecuteData(Url);
_jarray = new JSONArray(json);
System.out.println("_jarray" + _jarray);
for (int i = 0; i <= _jarray.length(); i++) {
JSONObject _obj = _jarray.getJSONObject(i);
if (Id != null) {
datamodel.setId(_obj.getString("Id"));
}
if (Designation != null) {
datamodel.setDesignation(_obj.getString("Designation"));
}
if (EmployeeName != null) {
datamodel.setEmployeeName(_obj
.getString("EmployeeName"));
}
list.add(datamodel);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
CustomList adapter = new CustomList(Setting.this, list);
listView1.setAdapter(adapter);
}
}
}
public class DataModel implements Parcelable {
private String Id = "";
private String Designation = "";
private String EmployeeName = "";
public String getId() {
return Id;
}
public void setId(String id) {
this.Id = id;
}
public String getDesignation() {
return Designation;
}
public void setDesignation(String designation) {
this.Designation = designation;
}
public String getEmployeeName() {
return EmployeeName;
}
public void setEmployeeName(String employeeName) {
this.EmployeeName = employeeName;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
public DataModel() {
// TODO Auto-generated constructor stub
}
public DataModel(Parcel in) {
Id = in.readString();
EmployeeName = in.readString();
Designation = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeString(Id);
dest.writeString(EmployeeName);
dest.writeString(Designation);
}
}
public class CustomList extends BaseAdapter {
Context context;
private ArrayList<DataModel> arrModel;
public CustomList(Context context, ArrayList<DataModel> arrModel) {
this.context = context;
this.arrModel = arrModel;
}
/* private view holder class */
private class ViewHolder {
TextView txtTitle;
TextView txtDesc;
ImageView locationimage;
ImageView roleimageview;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.settingrowitem, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView
.findViewById(R.id.rowcontact_txtName);
holder.txtTitle = (TextView) convertView
.findViewById(R.id.rowcontact_txtrole);
holder.locationimage = (ImageView) convertView
.findViewById(R.id.imageView1);
holder.roleimageview = (ImageView) convertView
.findViewById(R.id.imageView2);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtDesc.setText(arrModel.get(position).getEmployeeName());
holder.txtTitle.setText(arrModel.get(position).getDesignation());
if (position % 2 == 0) {
convertView.setBackgroundColor(Color.parseColor("#ffffff"));
}
else {
convertView.setBackgroundColor(Color.parseColor("#f5f6f1"));
}
return convertView;
}
#Override
public int getCount() {
return arrModel.size();
}
#Override
public Object getItem(int position) {
return arrModel.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
There are three class which I have use to parse data from from web service and and trying to print in Listview .I am able to do Json parsing and getting data from server insetting.javaclass:
list.add(datamodel);
and bind this in list in onpostexcute method:
CustomList adapter = new CustomList(Setting.this, list);
listView1.setAdapter(adapter);
Using this i am trying to print data in listview item but I am getting blank value in each item while Number Json is 49 and i am getting that 49 but getDesignation and getEmploye I am getting blank value please check and tell me where I am doing mistake I have tried much unable to get Print that value please check suggest me
Where are you inistailizind the Id,Designation and EmployeeName, it will be null itself. so doInBackground wont add any datamodel. remove the check
class GetUserdetail extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
String json = HttpHitter.ExecuteData(Url);
_jarray = new JSONArray(json);
System.out.println("_jarray" + _jarray);
for (int i = 0; i <= _jarray.length(); i++) {
DataModel datamodel = new DataModel();
JSONObject _obj = _jarray.getJSONObject(i);
datamodel.setId(_obj.getString("Id"));
datamodel.setDesignation(_obj.getString("Designation"));
datamodel.setEmployeeName(_obj.getString("EmployeeName"));
list.add(datamodel);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
CustomList adapter = new CustomList(Setting.this, list);
listView1.setAdapter(adapter);
}
}
Initialise the model inside the for loop and try once.
To identify changes in your list item you should call
adapter.notifyDataSetChanged();
call it before setting adapter to list view.
I am trying to populate Grid View from JSON response received from Async Task. Below is the activity file
public class OpenTableActivity extends Activity implements AsyncResponse{
String serUri, method;
OpenTableAdapter op;
WebServiceAsyncTask webTask = new WebServiceAsyncTask(this);
ArrayList<HashMap<String, String>> tableList = new ArrayList<HashMap<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.open_table);
getTables();
webTask.listener = this;
GridView gridview = (GridView) findViewById(R.id.grid);
gridview.setAdapter(new OpenTableAdapter(this,tableList));
LinearLayout layout = (LinearLayout) findViewById(R.id.opentableLinear);
layout.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent ev) {
hideKeyboard(view);
return false;
}
});
Button btn = (Button) findViewById(R.id.table_home_btn);
btn.setOnClickListener(homeBtn);
}
public boolean getTables() {
serUri = "tables.json";
method = "get";
WebServiceAsyncTask webServiceTask = new WebServiceAsyncTask(OpenTableActivity.this);
webServiceTask.execute(serUri, method, this);
return true;
}
#Override
public void WriteJsonArray(JSONArray result) {
// TODO Auto-generated method stub
try {
for (int i = 0; i < result.length(); i++) {
JSONObject c = result.getJSONObject(i);
String tabLabel = c.getString("tablabel");
String tabStatus = c.getString("tabstatus");
HashMap<String, String> map = new HashMap<String, String>();
map.put("table_name", tabLabel);
map.put("table_status", tabStatus);
tableList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}}
The Adapter class to fill grid view is as below
public class OpenTableAdapter extends BaseAdapter {
private Context mContext;
String orderNumber;
OpenTableActivity openInstance;
String tableLabel;
String tableStatus;
LayoutInflater mInflater;
ArrayList<HashMap<String, String>> tablist = null;
public OpenTableAdapter(Context c, ArrayList<HashMap<String, String>> tablelist ) {
// TODO Auto-generated constructor stub
mContext = c;
mInflater = LayoutInflater.from(c);
tablist = tablelist;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
openInstance = new OpenTableActivity();
return openInstance.tableList.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(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.button,
parent, false);
holder = new ViewHolder();
holder.btn = (Button) convertView.findViewById(R.id.button);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//Button btn = (Button) view.findViewById(R.id.button);
HashMap<String, String> map = tablist.get(position);
for (java.util.Map.Entry<String, String> mapEntry : map.entrySet()) {
String key = mapEntry.getKey();
String value = mapEntry.getValue();
holder.btn.setText(key);
return convertView;
}
static class ViewHolder
{
Button btn;
}
}
the interface class defined is as below:
public interface AsyncResponse {
public void WriteJsonArray(JSONArray tableList);
}
The Async task class is as below
public class WebServiceAsyncTask extends AsyncTask<Object,Void,JSONArray> {
AsyncResponse listener;
public WebServiceAsyncTask(){}
public WebServiceAsyncTask(Context appcontext)
{
this.context=appcontext;
listener = (AsyncResponse) this.context;
}
String serviceUrl;
OpenTableActivity openInstance=new OpenTableActivity();
CategoryActivity catAct;
private static JSONArray json = null;
private Context context = null;
private static JSONObject jsonObject = null;
protected JSONArray doInBackground(Object... params) {
// TODO Auto-generated method stub
serviceUrl = (String) params[0];
String method = (String) params[1];
final HTTPHelper httph = new HTTPHelper(serviceUrl,context);
json = httph.fetch();
return json;
}
#Override
protected void onPostExecute(JSONArray result) { // invoked on the ui thread
// TODO Auto-generated method stub
// dismiss progress dialog
// update ui here
super.onPostExecute(result);
if (listener != null){
listener.WriteJsonArray(result);
}
}
On running this I am getting Stackoverflow error as soon as activity class is called. I tried many different options but still same error. Not sure what I am missing as unable to debug too as its giving error even before entering the activity class. Please advise. Thanks.
Posting solution. From the discussion
You need to move the below to WriteJsonArray. Once you get the data you need to pass the same to the adapter class
gridview.setAdapter(new OpenTableAdapter(this,tableList));
Replace your getCount by
#Override
public int getCount() {
return tablist.size();
}
In getview remove your for loop
HashMap<String,String> map = tablist.get(position);
String value = map.get("key");
// make sure the key i right. "key" here is only an example. replace with right key
holder.btn.setText("value");
remove this
WebServiceAsyncTask webTask = new WebServiceAsyncTask(this); // at the beginnning
remove this from asynctask
OpenTableActivity openInstance=new OpenTableActivity();
AsyncTask<Void, Void, Boolean> waitForCompletion = new AsyncTask<Void, Void, Boolean>() {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog.setVisibility(View.VISIBLE);
}
#Override
protected Boolean doInBackground(Void... params) {
}
#Override
protected void onPostExecute(Boolean result) {
}
}
I have an application it have two activities. When press a button in the main activity, it shows customized listview, then I press hard back button and go to the main page of my application.
Then I again press the same button and go to the listview it shows the repeated values in the listview.
Any one have any sloution please???
CookList = new ArrayList<HashMap<String, String>>();
try {
url = new URI(cookUri);
List<DataModels> list1 = new ArrayList<DataModels>();
CookListServer cookServer = new CookListServer();
StringBuilder responseString = cookServer.CookConnect(url, "hi");
System.out.println("responseString---------"+responseString);
for(int i=0; i< itemId.size(); i++){
HashMap<String, String> Cook = new HashMap<String, String>();
Cook.put("ItemId", itemId.get(i));
System.out.println("itemId--------"+itemId.get(i));
Cook.put("ItemName", itemName.get(i));
Cook.put("ItemQty", itemQty.get(i));
CookList.add(Cook);
list1.add(get(i));
}
adapter = new MySimpleArrayAdapter(context, CookList, R.layout.cooklist_item, list1);
setListAdapter(adapter);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private DataModels get(int s) {
return new DataModels(s);
}
#Override
public void onResume() {
super.onResume();
adapter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
// Adapter to list the Albums
public class MySimpleArrayAdapter extends ArrayAdapter<HashMap<String, String>> implements SectionIndexer {
private final Context context;
private final ArrayList<HashMap<String, String>> values;
List<DataModels> modellist;
public MySimpleArrayAdapter(Context context, ArrayList<HashMap<String, String>> values, int layout, List<DataModels> modellist) {
super(context, R.layout.cooklist_item, values);
this.context = context;
this.values = values;
this.modellist = modellist;
}
private final class ViewHolder {
public TextView Nametext;
public TextView Qntytext;
public Button prepareButton;
}
private LayoutInflater mLayoutInflater = null;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
if (mLayoutInflater == null) {
mLayoutInflater = LayoutInflater.from(context);
}
convertView = mLayoutInflater.inflate(R.layout.cooklist_item, null);
viewHolder = new ViewHolder();
viewHolder.Nametext = (TextView) convertView.findViewById(R.id.label);
viewHolder.Qntytext = (TextView) convertView.findViewById(R.id.textView1);
viewHolder.prepareButton = (Button) convertView.findViewById(R.id.prepareButton1);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
((ViewHolder) convertView.getTag()).prepareButton.setTag(modellist.get(position));
}
final HashMap<String, String> cooklist = values.get(position);
final ViewHolder holder = (ViewHolder) convertView.getTag();
final String ItemId = cooklist.get("ItemId");
final String ItemName = cooklist.get("ItemName");
final String ItemQty = cooklist.get("ItemQty");
System.out.println("ItemId---------"+ItemId);
System.out.println("ItemName---------"+ItemName);
System.out.println("ItemQty---------"+ItemQty);
holder.Nametext.setText(ItemName);
holder.Qntytext.setText(ItemQty);
registerForContextMenu(convertView);
holder.prepareButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DataModels element = (DataModels) viewHolder.prepareButton.getTag();
holder.prepareButton.setEnabled(false);
}
});
return convertView;
}
#Override
public int getPositionForSection(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getSectionForPosition(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object[] getSections() {
// TODO Auto-generated method stub
return null;
}
}
Thanks...
I got a solution
#Override
protected void onDestroy() {
itemId.clear();
itemName.clear();
itemQty.clear();
super.onDestroy();
}
Thanks....
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.