Searching of Customlist view not working - android

I am trying to built search functionality on custom listView but it is not working..list is not changing according to EditText words changes..
listplaceholder.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/edtSearch"
android:hint="Search"/>
<ListView
android:id="#id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawSelectorOnTop="false" />
</LinearLayout>
my_custom_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="70dp"
android:layout_height="70dp"
android:src="#drawable/icon" />
<FrameLayout
android:id="#+id/frame"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Button"
/>
<LinearLayout
android:id="#+id/ll1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/a"
android:orientation="vertical" >
<TextView
android:id="#+id/from_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000" />
<TextView
android:id="#+id/from_user_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000" />
</LinearLayout>
</FrameLayout>
</LinearLayout>
Main.java
public class Main extends ListActivity {
/** Called when the activity is first created. */
ImageView img, img1;
private AdapterClass adapter;
private String reviewImageLink;
private static final String TAG = "PRANJAL";
private boolean isImage = false;
String fileName[] = new String[10];
private String imgurl;
ArrayList<HashMap<String, String>> searchResult;
private EditText edtSearch;
private ListView list;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
edtSearch = (EditText) findViewById(R.id.edtSearch);
list = (ListView) findViewById(android.R.id.list);
// list = (LinearLayout) findViewById(R.id.list);
final ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions
.getJSONfromURL("http://23.21.228.8/PlutoApp_Beta/consumer_dash/"
+ "checkIn_confirmation_related_record.php?lat=18.535787&lng=73.891889");
try {
JSONArray earthquakes = json.getJSONArray("Display");
for (int i = 0; i < earthquakes.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = earthquakes.getJSONObject(i);
map.put("Name", e.getString("name"));
map.put("Vicinity", e.getString("vicinity"));
map.put("logo", e.getString("logo"));
imgurl = e.getString("logo");
// Toast.makeText(getApplicationContext(), imgurl,
// Toast.LENGTH_SHORT).show();
imgurl = e.getString("logo");
// Toast.makeText(getApplicationContext(), imgurl,
// Toast.LENGTH_SHORT).show();
DownloadFromUrl(imgurl, i + ".jpg");
reviewImageLink = imgurl;// getString(R.string.ImageURI);
URL reviewImageURL;
fileName[i] = reviewImageLink.substring(reviewImageLink
.lastIndexOf("/") + 1);
// map.put("profile_image_url", fileName[i]);
map.put("logo", i + ".jpg");
list.setTextFilterEnabled(true);
mylist.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
/*final ListView lv = getListView();
lv.setTextFilterEnabled(true);*/
searchResult = new ArrayList<HashMap<String, String>>(mylist);
// adapter = new AdapterClass(Main.this, R.layout.main, mylist);
adapter = new AdapterClass(Main.this, R.layout.my_custom_layout, mylist);
// list.setAdapter(adapter);
setListAdapter(adapter);
edtSearch.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// get the text in the EditText
String searchString = edtSearch.getText().toString();
int textLength = searchString.length();
searchResult.clear();
for (int i = 0; i < mylist.size(); i++) {
String playerName = mylist.get(i).get("Name").toString();
if (textLength <= playerName.length()) {
// compare the String in EditText with Names in the
// ArrayList
if (searchString.equalsIgnoreCase(playerName.substring(
0, textLength)))
Toast.makeText(getApplicationContext(),
"Inside if of : " + playerName, 1000)
.show();
searchResult.add(mylist.get(i));
}
}
adapter.notifyDataSetChanged();
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
/*
* final ListView lv = getListView(); //lv.setTextFilterEnabled(true);
* lv.setOnItemClickListener(new OnItemClickListener() { public void
* onItemClick(AdapterView<?> parent, View view, int position, long id)
* {
*
* #SuppressWarnings("unchecked") HashMap<String, String> o =
* (HashMap<String, String>) lv .getItemAtPosition(position);
*
* } });
*/
}
public void DownloadFromUrl(String DownloadUrl, String fileName) {
try {
File dir = new File("/sdcard/pluto");
if (dir.exists() == false) {
dir.mkdirs();
}
URL url = new URL(DownloadUrl); // you can write here any link
File file = new File(dir, fileName);
long startTime = System.currentTimeMillis();
Log.d("DownloadManager", "download begining");
Log.d("DownloadManager", "download url:" + url);
Log.d("DownloadManager", "downloaded file name:" + fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
Log.d("DownloadManager",
"download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
Log.d("DownloadManager", "Error: " + e);
}
}
}
Please Help me.

You are not setting the adapter again in onTextChange. Add this inside onTextChange at the end:
setListAdapter(searchResult);
and remove
adapter.notifyDataSetChanged();

Related

Listview Pagination in android

I have a listview where I have 50 elements being displayed. I have decided to paginate the view so on each part of the view there are 10 elements and then a next button is clicked to get to the next 10 elements. How can i set 10 data ? I follow this article
http://rakhi577.wordpress.com/2013/05/20/listview-pagination-ex-2/
Here is my code .Can you help me with my code or a link to a guide on how to implement this correctly?
public class MainActivity extends ListActivity {
Context context;
Button btnSearch ;
EditText txtSearch;
private ProgressDialog pDialog;
// URL to get contacts JSON
public int TOTAL_LIST_ITEMS = 50;
public int NUM_ITEMS_PAGE = 10;
private int noOfBtns;
private Button[] btns;
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSearch=(Button)findViewById(R.id.buttonSearch);
txtSearch=(EditText)findViewById(R.id.Searchtext);
}
public String gotourl()
{
final EditText txtSearch=(EditText)findViewById(R.id.Searchtext);
String ts=txtSearch.getText().toString();
String url = "http://latest.bloomapi.com/api/search?limit=50&offset=0&key1=last_name&op1=eq&value1="+ts;
return url ;
}
public void Searchfunction(View v)
{
Btnfooter();
//loadList(0);
CheckBtnBackGroud(0);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
private void Btnfooter()
{
int val = TOTAL_LIST_ITEMS%NUM_ITEMS_PAGE;
val = val==0?0:1;
noOfBtns=TOTAL_LIST_ITEMS/NUM_ITEMS_PAGE+val;
LinearLayout ll = (LinearLayout)findViewById(R.id.btnLay);
btns =new Button[noOfBtns];
for(int i=0;i<noOfBtns;i++)
{
btns[i] = new Button(this);
btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
btns[i].setText(""+(i+1));
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(btns[i], lp);
final int j = i;
btns[j].setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
//loadList(j);
CheckBtnBackGroud(j);
}
});
}
}
private void CheckBtnBackGroud(int index)
{
for(int i=0;i<noOfBtns;i++)
{
if(i==index)
{
btns[index].setBackgroundDrawable(getResources().getDrawable(R.drawable.box_green));
btns[i].setTextColor(getResources().getColor(android.R.color.white));
}
else
{
btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
btns[i].setTextColor(getResources().getColor(android.R.color.black));
}
}
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(gotourl(), ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray("result");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
Integer a = contacts.length();
Log.d("loop", a.toString());
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("npi");
String name = c.getString("first_name");
String email = c.getString("last_name");
//String address = c.getString(TAG_ADDRESS);
String gender = c.getString("type");
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put("npi", id);
contact.put("first_name", name);
contact.put("last_name", email);
//contact.put(TAG_PHONE_MOBILE, mobile);
contact.put("type", gender);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.d("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[] { "first_name", "last_name",
"type" }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}}
I change the code. When i click next button[like 2,3,4,5]. showing first page data. Here is my modified code.Any help Appreciated :
public class MainActivity extends ListActivity {
private TextView title;
Context context;
Button btnSearch ;
EditText txtSearch;
private ListView listview;
private ProgressDialog pDialog;
// URL to get contacts JSON
public int TOTAL_LIST_ITEMS = 50;
public int NUM_ITEMS_PAGE = 10;
private int noOfBtns;
private Button[] btns;
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSearch=(Button)findViewById(R.id.buttonSearch);
txtSearch=(EditText)findViewById(R.id.Searchtext);
title = (TextView)findViewById(R.id.title);
}
public String gotourl()
{
final EditText txtSearch=(EditText)findViewById(R.id.Searchtext);
String ts=txtSearch.getText().toString();
String url = "http://latest.bloomapi.com/api/search?limit=50&offset=0&key1=last_name&op1=eq&value1="+ts;
return url ;
}
public void Searchfunction(View v)
{
Btnfooter();
CheckBtnBackGroud(0);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if(position%2==0)
{
view.setBackgroundColor(Color.parseColor("#F4FA58"));
}else
{
view.setBackgroundColor(Color.parseColor("#DA81F5"));
}
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
private void Btnfooter()
{
int val = TOTAL_LIST_ITEMS%NUM_ITEMS_PAGE;
val = val==0?0:1;
noOfBtns=TOTAL_LIST_ITEMS/NUM_ITEMS_PAGE+val;
LinearLayout ll = (LinearLayout)findViewById(R.id.btnLay);
btns =new Button[noOfBtns];
for(int i=0;i<noOfBtns;i++)
{
btns[i] = new Button(this);
btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
btns[i].setText(""+(i+1));
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(btns[i], lp);
final int j = i;
btns[j].setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
new GetContacts().execute();
CheckBtnBackGroud(j);
}
});
}
}
private void CheckBtnBackGroud(int index)
{
title.setText("Page "+(index+1)+" of "+noOfBtns);
for(int i=0;i<noOfBtns;i++)
{
if(i==index)
{
btns[index].setBackgroundDrawable(getResources().getDrawable(R.drawable.box_green));
btns[i].setTextColor(getResources().getColor(android.R.color.white));
}
else
{
btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
btns[i].setTextColor(getResources().getColor(android.R.color.black));
}
}
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(gotourl(), ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
int number = 0;
int start = number * NUM_ITEMS_PAGE;
// looping through All Contacts
// Getting JSON Array node
contacts = jsonObj.getJSONArray("result");
// looping through All Contacts
//for (int i = 0; i < contacts.length(); i++) {
for(int i=start;i<(start)+NUM_ITEMS_PAGE;i++) {
Integer a = contacts.length();
Log.d("loop", a.toString());
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("npi");
String name = c.getString("first_name");
String email = c.getString("last_name");
String gender = c.getString("type");
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put("npi", id);
contact.put("first_name", name);
contact.put("last_name", email);
//contact.put(TAG_PHONE_MOBILE, mobile);
contact.put("type", gender);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.d("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[] { "first_name", "last_name",
"type" }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}}
Below is my code to show list view with pagination. There is two blue button for change pages.
You can customize according to you need.
Create UserCategory.java
package com.UserCategory;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
public class UserCategory extends Activity implements OnClickListener{
private final int PAGE_SIZE = 5;
private int StartingIndex = 0;
ArrayList<String> userClass=new ArrayList<String>();
int textlength=0;
private String lv_arr[];
private ListView lv1;
EditText searchText;
//Button Previous;
private String Machine[]={"Machine 1","Machine 2","Machine 3","Machine 4","Machine 5","Machine 6","Machine 7","Machine 8","Machine 9","Machine 10","Machine 11","Machine 12","Machine 1","Machine 2","Machine 3","Machine 4","Machine 5","Machine 6","Machine 7","Machine 8","Machine 9","Machine 10","Machine 11","Machine 12"};
ImageView next,Previous;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.main);
lv1=(ListView)findViewById(R.id.ListView01);
searchText=(EditText)findViewById(R.id.et_Serchlist);
next=(ImageView)findViewById(R.id.btn_next);
Previous=(ImageView)findViewById(R.id.btn_previous);
next.setOnClickListener(this);
Previous.setOnClickListener(this);
//parsing();
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , Machine));
changeListViewModel(0);
}
private void changelist(int startingIndex) {
if(startingIndex < 0) {
Previous=(ImageView)findViewById(R.id.btn_previous);
ImageView back=(ImageView)findViewById(R.id.btn_Whiteprevious);
back.setVisibility(1);
Previous.setVisibility(4);
startingIndex = 0;
}else if(startingIndex >= userClass.size())
startingIndex -= PAGE_SIZE;
StartingIndex = startingIndex;
int endingIndex = startingIndex + PAGE_SIZE;
System.out.println("ending index"+endingIndex);
if(StartingIndex!=0){
Previous=(ImageView)findViewById(R.id.btn_previous);
ImageView back=(ImageView)findViewById(R.id.btn_Whiteprevious);
back.setVisibility(4);
Previous.setVisibility(1);
}
if(endingIndex == userClass.size()){
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(1);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(4);
}
if(endingIndex != userClass.size()){
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(4);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(1);
}
if(endingIndex > userClass.size()) endingIndex = userClass.size();
try {
String[] subSet = getDataSubset1(startingIndex, endingIndex);
System.out.println("subSet array"+subSet);
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , subSet));
} catch (Exception e) {
e.printStackTrace();
}
}
private String[] getDataSubset1(int startingIndex, int endingIndex){
String[] changeList = new String[endingIndex - startingIndex];
int index = -1;
for(int x = startingIndex; x < endingIndex; x++)
changeList[++index] = userClass.get(x);
return changeList;
}
private void changeListViewModel(int startingIndex){
if(startingIndex < 0) {
Previous=(ImageView)findViewById(R.id.btn_previous);
ImageView back=(ImageView)findViewById(R.id.btn_Whiteprevious);
back.setVisibility(1);
Previous.setVisibility(4);
startingIndex = 0;
}
else if(startingIndex >= Machine.length){
startingIndex -= PAGE_SIZE;
}
System.out.println("strating"+startingIndex);
System.out.println("startingIndex"+startingIndex);
StartingIndex = startingIndex;
int endingIndex = startingIndex + PAGE_SIZE;
System.out.println("endingIndex"+endingIndex);
if(StartingIndex!=0)
{
Previous=(ImageView)findViewById(R.id.btn_previous);
ImageView back=(ImageView)findViewById(R.id.btn_Whiteprevious);
back.setVisibility(4);
Previous.setVisibility(1);
}
if(endingIndex == userClass.size()){
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(1);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(4);
}
if(endingIndex != userClass.size()){
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(4);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(1);
}
System.out.println("ending index"+endingIndex);
if(endingIndex > Machine.length) {
endingIndex = Machine.length;
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(1);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(4);
}
String[] subSet = getDataSubset(startingIndex, endingIndex);
System.out.println("subSet main array"+subSet.length);
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , subSet));
}
private String[] getDataSubset(int startingIndex, int endingIndex){
String[] toRet = new String[endingIndex - startingIndex];
int index = -1;
System.out.println("index"+index);
for(int x = startingIndex; x < endingIndex; x++)
toRet[++index] = Machine[x];
return toRet;
}
private void parsing() {
// TODO Auto-generated method stub
try {
URL url = new URL("http://10.10.1.100/DogEventsWebService/EventService.svc/categories/1");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("UserCategory");
Machine = new String[nodeList.getLength()];
for (int i = 0; i < nodeList.getLength(); i++)
{
Node node = nodeList.item(i);
Machine[i] = new String();
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("ClassDescription");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
Machine[i]=((Node) nameList.item(0)).getNodeValue();
}
System.out.println("after for loop Machine"+Machine);
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn_next:
textlength=searchText.getText().length();
System.out.println("nextbutton"+textlength);
if(textlength==0){
changeListViewModel(StartingIndex + PAGE_SIZE);
}else{
changelist(StartingIndex + PAGE_SIZE);
}
break;
case R.id.btn_previous:
textlength=searchText.getText().length();
if(textlength==0){
changeListViewModel(StartingIndex - PAGE_SIZE);
}else{
changelist(StartingIndex - PAGE_SIZE);
}
break;
default:
break;
}
}
}
create main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<View android:layout_height="35dp"
android:layout_width="fill_parent"
android:background="#ffffff"/>
<TextView android:id="#+id/tv_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello"
android:layout_alignParentTop="true"
android:layout_marginLeft="0dp"
android:textSize="25dp"/>
<EditText
android:id="#+id/et_Serchlist"
android:layout_height="35dp"
android:paddingLeft="19dp"
android:layout_marginLeft="60dp"
android:layout_toRightOf="#+id/tv_header"
android:maxLength="20"
android:maxLines="1"
android:inputType="text"
android:hint="Search"
android:textColor="#ffffff"
android:background="#drawable/my_border"
android:layout_width="100dip"/>
<ListView
android:id="#+id/ListView01"
android:layout_width="fill_parent"
android:textSize="4px"
android:layout_below="#+id/tv_header"
android:layout_above="#+id/btn_previous"
android:layout_height="wrap_content" />
<View android:layout_height="55dp"
android:layout_below="#+id/ListView0"
android:layout_alignParentBottom="true"
android:layout_width="fill_parent"
android:background="#ffffff"/>
<ImageView
android:src="#drawable/grewprevious"
android:id="#+id/btn_Whiteprevious"
android:layout_width="wrap_content"
android:layout_marginLeft="12dp"
android:layout_marginBottom="6dp"
android:layout_below="#+id/ListView0"
android:visibility="invisible"
android:layout_alignParentBottom="true"
android:layout_height="wrap_content"/>
<ImageView
android:src="#drawable/right"
android:id="#+id/btn_grewforward"
android:layout_width="wrap_content"
android:layout_marginLeft="259dp"
android:layout_marginBottom="6dp"
android:layout_below="#+id/ListView0"
android:visibility="invisible"
android:layout_alignParentBottom="true"
android:layout_height="wrap_content"/>
<ImageView
android:src="#drawable/backward"
android:id="#+id/btn_previous"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="12dp"
android:layout_marginBottom="6dp"
android:layout_below="#+id/ListView0"
android:onClick="backButtonClicked"/>
<ImageView android:src="#drawable/forward"
android:id="#+id/btn_next"
android:layout_width="80dp"
android:layout_marginBottom="6dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_below="#+id/ListView0"
android:layout_marginLeft="249dp"
android:text="Next"
android:onClick="nextButtonClicked"/>
</RelativeLayout>
Create userlist.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="#+id/tv_className"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
</LinearLayout>
Add my_border.xml into Drawable folder:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="2dip" android:color="#ee777777" />
<solid android:color="#ee444444"/>
<padding
android:left="20dip"
android:top="2dip"
android:right="20dip"
android:bottom="2dip" />
<corners android:radius="15dip" />
![enter image description here][1]</shape>
If it give error for iamges then use any other images and run application.
Let me know it work for you.
Thanks

How to dynamically add suggestions to autocompletetextview with preserving character status along with images

Currently I am using code to give text suggestion. I would like to add another text and image. How do I do that? Currently, I am using the code below.I shows text but image is not displayed .How do I set the image ?
public class AutoCompleteTextViewActivity extends Activity{
ImageLoader imageLoader;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisc(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config);
AutoCompleteTextView actv = new AutoCompleteTextView(this);
actv.setThreshold(1);
final String[] from = {BaseColumns._ID, "name", "artist", "title"};
int[] to = {R.id.list_image, R.id.textView1, R.id.textView2, R.id.textView3};
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_row, null, from, to);
adapter.setStringConversionColumn(1);
ViewBinder viewBinder = new ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if (columnIndex == 0) {
ImageView iv = (ImageView) view;
Bitmap bitmap = cursor.getExtras().getParcelable("image");
if (bitmap != null) {
iv.setImageBitmap(bitmap);
}
return true;
}
return false;
}
};
adapter.setViewBinder(viewBinder);
FilterQueryProvider provider = new FilterQueryProvider() {
ExecutorService mPool = Executors.newCachedThreadPool();
Uri URI = Uri.parse("adapter://autocomplete");
public Cursor runQuery(CharSequence constraint) {
if (constraint == null) {
return null;
}
try {
return callWebService(constraint, from);
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
// here you make the web request
private Cursor callWebService(CharSequence constraint, String[] columnNames) throws JSONException {
Log.d("TAG", "callWebService for: " + constraint);
MatrixCursor cursor = new MyMatrixCursor(columnNames);
// TODO do real network request
// call web service here and keep the result in "jsonStr"
// String a=constraint;
JSONObject json=JSONfunctions.getJSONfromURL("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist="+ constraint +"&api_key=63692beaaf8ba794a541bca291234cd3&format=json");
JSONObject js1=json.getJSONObject("artist");
JSONObject js=js1.getJSONObject("similar");
JSONArray resultArray = js.getJSONArray("artist");
int length = resultArray.length();
for (int i = 0; i < length; i++) {
String data = resultArray.getJSONObject(i).getString("name");
String dataimage = resultArray.getJSONObject(i).getJSONArray("image").getJSONObject(i).getString("#text");
cursor.newRow().add(i)
.add(data)
.add(data)
.add(data);
String link = dataimage;
// get cached Bundle based on "link" (use HashMap<String, Bundle>)
// or if new link initiate async request for getting the bitmap
// TODO implement HashMap caching
// new async request
Bundle extras = new Bundle();
try {
mPool.submit(new ImageRequest(link, extras));
} catch (MalformedURLException e) {
e.printStackTrace();
}
cursor.respond(extras);
}
cursor.setNotificationUri(getContentResolver(), URI);
return cursor;
}
class ImageRequest implements Runnable {
private URL mUrl;
private Bundle mExtra;
public ImageRequest(String link, Bundle extra) throws MalformedURLException {
mUrl = new URL(link);
mExtra = extra;
}
public void run() {
String TAG="log";
// TODO do real network request
// simulate network delay
// Log.d(TAG, "getting " + mUrl);
// try {
// Thread.sleep(2000 + (long) (4000 * Math.random()));
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
Bitmap b = imageLoader.loadImageSync(mUrl.toString());
// Bitmap b = BitmapFactory.decodeResource(getResources(), mUrl.toString());
mExtra.putParcelable("image", b);
getContentResolver().notifyChange(URI, null);
Log.d(TAG, "run got a bitmap " + b.getWidth() + "x" + b.getHeight());
}
}
};
adapter.setFilterQueryProvider(provider);
actv.setAdapter(adapter);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
setContentView(actv, params);
}
}
///////////////
MyMatrixCursor
//////////
public class MyMatrixCursor extends MatrixCursor {
List<Bundle> mBundles = new ArrayList<Bundle>();
public MyMatrixCursor(String[] columnNames) {
super(columnNames);
}
#Override
public Bundle respond(Bundle extras) {
mBundles.add(extras);
return extras;
}
#Override
public Bundle getExtras() {
return mBundles.get(mPos);
}
}
////////
JSONfunctions
///////
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url){
InputStream is = null;
String result = "";
JSONObject jArray = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.w("log_tag", "Error converting result "+e.toString());
}
try{
jArray = new JSONObject(result);
}catch(JSONException e){
Log.w("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
}
////////
main.xml
///
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pick Artist"
android:textAppearance="?android:attr/textAppearanceLarge" />
<AutoCompleteTextView
android:id="#+id/actv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:completionThreshold="1"> <requestFocus />
</AutoCompleteTextView>
<TextView
android:id="#+id/selection"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
/////
list_row.xml
///
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:color/white"
android:orientation="horizontal"
android:padding="5dip" >
<!-- ListRow Left sied Thumbnail image -->
<LinearLayout android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip">
<ImageView
android:id="#+id/list_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="42dp"
android:maxHeight="42dp"
android:src="#drawable/ic_launcher"
android:scaleType="fitCenter"
android:layout_marginLeft="3dp"/>
</LinearLayout>
<!-- Title Of Song-->
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:text="test"
android:textColor="#040404"
android:typeface="sans"
android:textSize="15dip"
android:textStyle="bold"/>
<!-- Artist Name -->
<!-- Rightend Duration -->
<!-- Rightend Arrow -->
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_centerVertical="true"
android:text="test"
android:textColor="#040404"
android:textSize="5dip"
android:textStyle="bold"
android:typeface="sans" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:text="test"
android:textColor="#040404"
android:textSize="15dip"
android:textStyle="bold"
android:typeface="sans" />
</RelativeLayout>
///
Manifest
///
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.example"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:label="#string/app_name"
android:name=".AutoCompleteTextViewActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
ok try this:
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
AutoCompleteTextView actv = new AutoCompleteTextView(this);
actv.setThreshold(1);
String[] from = {"name"};
int[] to = {android.R.id.text1};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, null, from, to) {
// required for Spanned data
#Override
public void bindView(View view, Context context, Cursor cursor) {
MyCursor c = (MyCursor) cursor;
TextView tv = (TextView) view;
tv.setText(c.getSpanned());
}
// required for Spanned data
#Override
public CharSequence convertToString(Cursor cursor) {
MyCursor c = (MyCursor) cursor;
return c.getSpanned();
}
};
FilterQueryProvider provider = new FilterQueryProvider() {
#Override
public Cursor runQuery(CharSequence constraint) {
if (constraint == null) {
return null;
}
MyCursor c = new MyCursor();
// fake web service responses
List<String> names = callFakeWebService(constraint);
int i = 0;
for (String name: names) {
SpannableStringBuilder ssb = new SpannableStringBuilder(name);
int start = name.indexOf(" ");
ForegroundColorSpan what = new ForegroundColorSpan(0xffff0000);
ssb.setSpan(what, start + 1, ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
c.newRow().add(i++).add(name);
c.addSpanned(ssb);
}
return c;
}
// fake web service request
private List<String> callFakeWebService(CharSequence constraint) {
Log.d(TAG, "callFakeWebService for: " + constraint);
String[] namesArr = {
"Mark Smith",
"Monica Thompson",
"John White",
"Jane Brown"
};
String stringConstraint = constraint.toString().toLowerCase();
List<String> names = new ArrayList<String>();
for (int i = 0; i < namesArr.length; i++) {
String name = namesArr[i];
if (name.toLowerCase().startsWith(stringConstraint)) {
names.add(name);
}
}
return names;
}
};
adapter.setFilterQueryProvider(provider);
actv.setAdapter(adapter);
ll.addView(actv);
TextView tv = new TextView(this);
tv.setTextSize(32);
tv.setTextColor(0xffff0000);
tv.setText("type one of:\n mark,\n monica,\n john\n jane");
ll.addView(tv);
setContentView(ll);
where custom Cursor could look like this (it is minimalistic version supporting only one Spanned in a row):
static class MyCursor extends MatrixCursor {
private static final String[] NAMES = {BaseColumns._ID, "name"};
private ArrayList<Spanned> mSpannedList;
public MyCursor() {
super(NAMES);
mSpannedList = new ArrayList<Spanned>();
}
public void addSpanned(Spanned s) {
mSpannedList.add(s);
}
public Spanned getSpanned() {
return mSpannedList.get(mPos);
}
}
EDIT with no Spanned text:
AutoCompleteTextView actv = new AutoCompleteTextView(this);
actv.setThreshold(1);
final String[] from = {BaseColumns._ID, "name", "artist", "title"};
int[] to = {R.id.list_image, R.id.textView1, R.id.textView2, R.id.textView3};
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_row, null, from, to);
adapter.setStringConversionColumn(1);
ViewBinder viewBinder = new ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if (columnIndex == 0) {
ImageView iv = (ImageView) view;
Bitmap bitmap = cursor.getExtras().getParcelable("image");
if (bitmap != null) {
iv.setImageBitmap(bitmap);
}
return true;
}
return false;
}
};
adapter.setViewBinder(viewBinder);
FilterQueryProvider provider = new FilterQueryProvider() {
ExecutorService mPool = Executors.newCachedThreadPool();
Uri URI = Uri.parse("adapter://autocomplete");
public Cursor runQuery(CharSequence constraint) {
if (constraint == null) {
return null;
}
try {
return callWebService(constraint, from);
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
// here you make the web request
private Cursor callWebService(CharSequence constraint, String[] columnNames) throws JSONException {
Log.d("TAG", "callWebService for: " + constraint);
MatrixCursor cursor = new MyMatrixCursor(columnNames);
// TODO do real network request
// call web service here and keep the result in "jsonStr"
String jsonStr = "{\"ResultArray\":[{\"data\":{ \"sno\":\"sno1\", \"date\":\"2011-08-21 14:27:09\", \"user\":\"1\", \"link\":\"http://scm-l3.technorati.com/11/11/17/56749/google-docs-revision.jpg?t=20111117074048\", \"name\":\"Aa\" }},{\"data\":{ \"sno\":\"sno2\", \"date\":\"2011-08-21 14:28:09\", \"user\":\"2\", \"link\":\"http://kcclaveria.com/wp-content/uploads/2013/02/google-panda-penguin.jpg\", \"name\":\"Bb\" }}]}";
JSONObject json = new JSONObject(jsonStr);
JSONArray resultArray = json.getJSONArray("ResultArray");
int length = resultArray.length();
for (int i = 0; i < length; i++) {
JSONObject data = resultArray.getJSONObject(i).getJSONObject("data");
cursor.newRow().add(i)
.add(data.getString("name"))
.add(data.getString("user"))
.add(data.getString("sno"));
String link = data.getString("link");
// get cached Bundle based on "link" (use HashMap<String, Bundle>)
// or if new link initiate async request for getting the bitmap
// TODO implement HashMap caching
// new async request
Bundle extras = new Bundle();
try {
mPool.submit(new ImageRequest(link, extras));
} catch (MalformedURLException e) {
e.printStackTrace();
}
cursor.respond(extras);
}
cursor.setNotificationUri(getContentResolver(), URI);
return cursor;
}
class ImageRequest implements Runnable {
private URL mUrl;
private Bundle mExtra;
public ImageRequest(String link, Bundle extra) throws MalformedURLException {
mUrl = new URL(link);
mExtra = extra;
}
#Override
public void run() {
// TODO do real network request
// simulate network delay
Log.d(TAG, "getting " + mUrl);
try {
Thread.sleep(2000 + (long) (4000 * Math.random()));
} catch (InterruptedException e) {
e.printStackTrace();
}
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
mExtra.putParcelable("image", b);
getContentResolver().notifyChange(URI, null);
Log.d(TAG, "run got a bitmap " + b.getWidth() + "x" + b.getHeight());
}
}
};
adapter.setFilterQueryProvider(provider);
actv.setAdapter(adapter);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
setContentView(actv, params);
and the custom MatrixCursor:
class MyMatrixCursor extends MatrixCursor {
List<Bundle> mBundles = new ArrayList<Bundle>();
public MyMatrixCursor(String[] columnNames) {
super(columnNames);
}
#Override
public Bundle respond(Bundle extras) {
mBundles.add(extras);
return extras;
}
#Override
public Bundle getExtras() {
return mBundles.get(mPos);
}
}

GridView Loads the duplicate images and Text (using EndlessScrollListener)

I have a custom gridVIew With an ImageView and a TextView in it, and I have set the gridView as a it show 2 coloumns. here is the code of custom_grid_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/widget44"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical" >
<ImageView
android:id="#+id/imgBookCover"
android:layout_width="88dp"
android:layout_height="102dp"
android:adjustViewBounds="true"
android:background="#drawable/rounded_image_borders"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:src="#drawable/book5" >
</ImageView>
<TextView
android:id="#+id/txt_BookTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:gravity="center_horizontal"
android:lines="1"
android:text="TextView"
android:textColor="#color/White"
android:textColorHighlight="#656565" >
</TextView>
and here is the layout of gridview.xml
<GridView
android:id="#+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_below="#+id/Rel_Spinner"
android:layout_centerHorizontal="true"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="columnWidth" >
</GridView>
Its loading the images from server and showing the correct images and text for the first time, as I have implemented the EndlessScrollListner class in my project.
In the first itration im loading 12 images from the server, when i Scroll down the gridView to end it sends the second request to Load 12 more images and text from the server.
Here the actual problem starts its loading the same images and text.
Please have a look on my bulky code and tell where I am commeting the mistake.
public class Home extends Activity {
static final String URL = "http://www.shiaislamiclibrary.com/requesthandler.ashx";
static final String KEY_ITEM = "Book"; // parent node
static final String KEY_BOOKAUTHOR = "book_author";
static final String KEY_BOOKRATING = "BookRating";
static final String KEY_BOOKID = "BookID";
static final String KEY_BOOKDESC = "BookDescription";
static final String KEY_BOOKDATEPUBLISHED = "DatePublished";
static final String KEY_BOOKTITLE = "BookTitle";
static final String KEY_BOOKCODE = "BookCode";
static final String KEY_BOOKIMAGE = "BookImage";
static final String KEY_ITEM_BOOKs_LIMIT = "Result"; // parent node
static final String KEY_ITEM_TOTAL_BOOKS = "TotalBooks";
static ArrayList<String> BookTitle = null;
static ArrayList<Integer> BookRating = null;
static ArrayList<String> BookDescription = null;
static ArrayList<String> BookCoverPhotos = null;
static ArrayList<String> BookAuther = null;
static ArrayList<String> BookIDs = null;
static ArrayList<String> BookCode = null;
static ArrayList<String> BookPublishDate = null;
static ArrayList<String> ImageByte = null;
static ArrayList<Bitmap> bitmapArray = null;
static int initialIndex = 12;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_activity);
gridView = (GridView) findViewById(R.id.gridview);
gridView.setOnScrollListener(new EndlessScrollListener());
if (BookTitle == null) {
BookTitle = new ArrayList<String>();
BookRating = new ArrayList<Integer>();
BookDescription = new ArrayList<String>();
BookIDs = new ArrayList<String>();
BookCode = new ArrayList<String>();
BookCoverPhotos = new ArrayList<String>();
BookAuther = new ArrayList<String>();
BookPublishDate = new ArrayList<String>();
ImageByte = new ArrayList<String>();
bitmapArray = new ArrayList<Bitmap>();
new UIThread().execute(URL, initialIndex + "");
// Log.i("If", BookTitle + "");
} else {
// Log.i("else", BookTitle + "");
ImageAdapter adapter2 = new ImageAdapter(getBaseContext(),
act);
gridView.setAdapter(adapter2);
}
Im using AsynkTaks to download the images from server. here is the code
private class UIThread extends AsyncTask<String, Integer, String> {
ProgressDialog progressDialog;
ImageAdapter adapter = new ImageAdapter(getBaseContext(), act);
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(getParent(),
"Acumlating Books from server...",
"This may Take a few seconds.\nPlease Wait...");
}
#Override
protected String doInBackground(String... params) {
String URL = params[0];
int initialIndex = Integer.valueOf(params[1]);
Log.i("params", params[1] + "");
XMLParser parser = new XMLParser();
String XMLString = parser.getXmlFromUrl_FeaturedBooks(URL,
initialIndex);
Home.initialIndex = Home.initialIndex + 12;
Log.i("Home.initialIndex", Home.initialIndex + "");
Document doc = parser.getDomElement(XMLString);
NodeList nlBooksLimit = doc
.getElementsByTagName(KEY_ITEM_BOOKs_LIMIT);
Element eLimit = (Element) nlBooksLimit.item(0);
String totalBooks = parser.getValue(eLimit, KEY_ITEM_TOTAL_BOOKS);
Log.i("totalBooks", totalBooks + "");
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
Bitmap imageNotFound = BitmapFactory.decodeResource(getResources(),
R.drawable.defaultcoverphoto);
for (int i = 0; i < nl.getLength(); i++) {
Element e = (Element) nl.item(i);
try {
BookRating.add(Integer.valueOf(parser.getValue(e,
KEY_BOOKRATING)));
// Log.i("Rating Try", BookRating.get(i) + "");
} catch (Exception e2) {
BookRating.add(0);
// Log.i("Rating Catch", BookRating + "");
}
BookDescription.add(parser.getValue(e, KEY_BOOKDESC));
BookTitle.add(parser.getValue(e, KEY_BOOKTITLE));
BookCoverPhotos.add("http://shiaislamicbooks.com/books_Snaps/"
+ parser.getValue(e, KEY_BOOKCODE) + "/1_thumb.jpg");
BookAuther.add(parser.getValue(e, KEY_BOOKAUTHOR));
BookPublishDate.add(parser.getValue(e, KEY_BOOKDATEPUBLISHED));
BookIDs.add(parser.getValue(e, KEY_BOOKID));
BookCode.add(parser.getValue(e, KEY_BOOKCODE));
// Log.i("URLs & Desc", BookCoverPhotos.toString());
try {
bookImageURL = new URL(BookCoverPhotos.get(i));
} catch (MalformedURLException e1) {
e1.printStackTrace();
// Log.i("URL", "ERROR at image position" + i + "");
}
try {
bitMapImage = BitmapFactory.decodeStream(bookImageURL
.openConnection().getInputStream());
bitmapArray.add(bitMapImage);
publishProgress(i + 1);
} catch (IOException e2) {
e2.printStackTrace();
bitmapArray.add(imageNotFound);
// Log.i("File Not Found", bookImageURL + "");
}
}
Log.i("Book Title", BookTitle + "");
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressDialog.setMessage(values[0]
+ " Book(s) found \nPlease wait...");
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
gridView.setAdapter(adapter);
}
}
and here is the EndlessScrollListner.java code. which send the request to sever again to download when the scroll reaches to the bottom of the gridView.
private class EndlessScrollListener implements OnScrollListener {
private int visibleThreshold = 0;
private int currentPage = 0;
private int previousTotal = 0;
private boolean loading = true;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
currentPage++;
}
}
if (!loading
&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
// I load the next page of gigs using a background task,
// but you can call any function here.
new UIThread().execute(URL, Home.initialIndex + "");
Log.i("Reached", "End");
Log.i("Home.initialIndex", Home.initialIndex + "");
loading = true;
}
}
here are 2 pictures to make you more clear my question.
Although pretty late, but I just ran into the same problem. Its happening because of the adapter's getView method.
In your ImageAdapter, if the getView function reuses the view already created then this might be the reason for your image repetition. If the code looks like below, then it is supposed to be changed like the second code snippet to download new images coming from load more.
Snippet 1
public View getView(int position, View v, ViewGroup parent) {
ImageView imageview;
if(v == null)
{
imageview = new ImageView(mcontext);
imageview.setLayoutParams(new GridView.LayoutParams(250,250));
imageview.setPadding(0,0,10,10);
imageview.setScaleType(ImageView.ScaleType.CENTER_CROP);
new DownloadImageTask(imageview).execute(arr.get(position).imageUrl);
}
else
imageview = (ImageView) v;
return imageview;
}
Snippet 2
public View getView(int position, View v, ViewGroup parent) {
ImageView imageview;
if(v == null)
{
imageview = new ImageView(mcontext);
imageview.setLayoutParams(new GridView.LayoutParams(250,250));
imageview.setPadding(0,0,10,10);
imageview.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
else
imageview = (ImageView) v;
new DownloadImageTask(imageview).execute(arr.get(position).imageUrl);
return imageview;
}
Or probably create a new view altogether but then you may need to handle virtualization and reusability of the gridView/listView by yourself.

Scrolling is not perform in Listview in android

I have a problem that, I am adding listview in LinearLayout dynamically through code and set the EndlessAdapter into that, Data is shown correctly but we are unable to scroll from top to bottom in the list. I don't know why? please suggest me any solution regarding the same.
Code:
public void setValuesInCategoryChild(String url, final String filter, final String from, final String to) {
if (isOnline()) {
final ProgressDialog dialog = ProgressDialog.show(ResearchList.this, "Research List ", "Please wait... ", true);
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
// System.out.println("The id after Save:"+id.get(0).toString());
// catagory.addAll(keyword_vector1);
linear_Category_Child.setVisibility(View.GONE);
linear_Category_Child_Child.setVisibility(View.VISIBLE);
// tv_Child_Header.setText("Volvo");
tv_CategoryChildHeader.setText(from);
setHeaderImage(tv_CategoryChildHeader.getText().toString());
System.out.println("The size of Cat Display names:" + coll.getDisplayNames().size());
System.out.println("The size of Cat Images:" + coll.getImages().size());
System.out.println("The size of Cat price:" + coll.getPrice().size());
System.out.println("The size of Cat Year:" + coll.getYears().size());
System.out.println("The size of Cat Rating:" + coll.getRating().size());
System.out.println("The size of Cat Mpg:" + coll.getMpg().size());
setHeaderImage(tv_CategoryChildHeader.getText().toString());
if(coll.getDisplayNames().size()!=0) {
lvCategory = new ListView(ResearchList.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
lvCategory.setLayoutParams(params);
// Adapter for MPG Search
demoAdapterCat = new DemoAdapterCat();
lvCategory.setAdapter(demoAdapterCat);
layout_ResearchList_BrandList.addView(lvCategory);
Utility.setListViewHeightBasedOnChildren(lvCategory);
}else {
/*lvCategory.invalidate();
lvCategory.setAdapter(null);*/
AlertDialog.Builder builder = new Builder(ResearchList.this);
builder.setTitle("Attention!");
builder.setMessage("No Data Available for the Particular Search.");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.create().show();
}
/*Utility util = new Utility();
util.setListViewHeightBasedOnChildren(lvCategory);*/
dialog.dismiss();
}
};
final Thread checkUpdate = new Thread() {
public void run() {
try {
String sortEncode = URLEncoder.encode("mpg");
String filterEncode = URLEncoder.encode(filter);
String clientEncode = URLEncoder.encode("10030812");
String fromEncode = URLEncoder.encode(from);
String toEncode = URLEncoder.encode(to);
String catUrl = "/v1/vehicles/get-make-models.json?sort=" + sortEncode + "&filter=" + filterEncode + "&client-id=" + clientEncode + "&from=" + fromEncode;
genSig = new GetSignature(catUrl, "acura");
try {
signature = genSig.getUrlFromString();
} catch (InvalidKeyException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// jsonString =
// getJsonSring("http://api.highgearmedia.com/v1/vehicles/get-models.json?make=acura&client-id=10030812&signature=LWQbdAlJVxlXZ1VO2mfqAA==");
// String signatureEncode =
// URLEncoder.encode(signature);
String urlEncode = URLEncoder.encode(catUrl + "&signature=" + signature);
jsonString = getJsonSring("http://apibeta.highgearmedia.com" + catUrl + "&signature=" + signature);
System.out.println("The json category:===>" + jsonString);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JsonParse json = new JsonParse(jsonString);
json.parseCat();
LIST_SIZE = coll.getDisplayNames().size();
for (int i = 0; i <= BATCH_SIZE; i++) {
// countriesSub.add(COUNTRIES[i]);
countriesSubCat.add(coll.getDisplayNames().get(i));
imagesSubCat.add(coll.getImages().get(i));
YearSubCat1.add(coll.getYears().get(i));
YearSubCat2.add(coll.getYears().get(i + 1));
mpgSubCat1.add(coll.getMpg().get(i));
mpgSubCat2.add(coll.getMpg().get(i + 1));
priceSubCat1.add(coll.getPrice().get(i));
priceSubCat2.add(coll.getPrice().get(i + 1));
ratingSubCat1.add(coll.getRating().get(i));
ratingSubCat2.add(coll.getRating().get(i + 1));
}
setLastOffset(BATCH_SIZE);
handler.sendEmptyMessage(0);
}
};
checkUpdate.start();
} else {
AlertDialog.Builder builder = new Builder(ResearchList.this);
builder.setTitle("Attention!");
builder.setMessage("Network Connection unavailable.");
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.create().show();
}
}
Layout:
<LinearLayout
android:id="#+id/linear_ResearchListCategoryChild_Child"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:visibility="gone" >
<RelativeLayout
android:id="#+id/linear_ResearchListCategoryChild_Child_HeaderBlock"
android:layout_width="fill_parent"
android:layout_height="40dip"
android:background="#drawable/catagory_bar"
android:orientation="horizontal" >
<TextView
android:id="#+id/tv_ResearchListCategoryChild_Child_Header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="Work in Progress"
android:textColor="#ffffff"
android:textStyle="bold" android:layout_marginLeft="60dip"/>
<ImageView
android:id="#+id/img_ResearchListCategory_ChildHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="10dip"
android:src="#drawable/up_arrow" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:src="#drawable/list_arrow_up" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/linear_ResearchListCategoryChild_Child_Header"
android:layout_width="fill_parent"
android:layout_height="40dip"
android:background="#drawable/nav_bg"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="5dip"
android:clickable="true"
android:text="Highest Rated"
android:textColor="#ffffff"
android:textStyle="bold" android:gravity="center"/>
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView5"
android:layout_alignBottom="#+id/textView5"
android:layout_marginLeft="30dp"
android:layout_toRightOf="#+id/textView5"
android:clickable="true"
android:text="A-Z"
android:textColor="#ffffff"
android:textStyle="bold" android:gravity="center"/>
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView6"
android:layout_alignBottom="#+id/textView6"
android:layout_marginLeft="40dp"
android:layout_toRightOf="#+id/textView6"
android:clickable="true"
android:text="Price"
android:textColor="#ffffff"
android:textStyle="bold" android:gravity="center"/>
<TextView
android:id="#+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView7"
android:layout_alignBottom="#+id/textView7"
android:layout_alignParentRight="true"
android:layout_marginRight="14dp"
android:clickable="true"
android:text="MPG"
android:textColor="#ffffff"
android:textStyle="bold" android:gravity="center"/>
</RelativeLayout>
<!--
<RelativeLayout
android:id="#+id/relative_down_arrow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="visible"
>
</RelativeLayout>
-->
<LinearLayout
android:id="#+id/linearArrowLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:visibility="visible">
<ImageView
android:id="#+id/Highly_rated"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="51dp"
android:src="#drawable/selector_arrow"
android:visibility="invisible" />
<ImageView
android:id="#+id/AZ_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="78dp"
android:src="#drawable/selector_arrow"
android:visibility="invisible" />
<ImageView
android:id="#+id/Price_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="59dp"
android:src="#drawable/selector_arrow"
android:visibility="invisible" />
<ImageView
android:id="#+id/MPG"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="55dp"
android:src="#drawable/selector_arrow"
android:visibility="invisible" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="12dip"
android:layout_marginRight="12dip" android:background="#ffffff" android:id="#+id/layout_ResearchList_BrandList">
</LinearLayout>
</LinearLayout>
DemoAdapterCat:
class DemoAdapterCat extends EndlessAdapter {
ImageLoader image = new ImageLoader(ResearchList.this);
private RotateAnimation rotate = null;
ArrayList<String> tempListNamesCat = new ArrayList<String>();
ArrayList<String> tempListImagesCat = new ArrayList<String>();
ArrayList<String> tempListYearCat1 = new ArrayList<String>();
ArrayList<String> tempListYearCat2 = new ArrayList<String>();
ArrayList<String> tempListmpgCat1 = new ArrayList<String>();
ArrayList<String> tempListmpgCat2 = new ArrayList<String>();
ArrayList<String> tempListpriceCat1 = new ArrayList<String>();
ArrayList<String> tempListpriceCat2 = new ArrayList<String>();
ArrayList<String> tempListRatingCat1 = new ArrayList<String>();
ArrayList<String> tempListRatingCat2 = new ArrayList<String>();
DemoAdapterCat() {
super(new CategoryListLazyAdapter(ResearchList.this,
countriesSubCat, imagesSubCat, YearSubCat1, YearSubCat2,
mpgSubCat1, mpgSubCat2, priceSubCat1, priceSubCat2,
ratingSubCat1, ratingSubCat2));
/*Utility util = new Utility();
util.setListViewHeightBasedOnChildren(lvCategory);*/
rotate = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF,
0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
rotate.setDuration(600);
rotate.setRepeatMode(Animation.RESTART);
rotate.setRepeatCount(Animation.INFINITE);
}
/*
* #Override public int getCount() { return
* brandList.getDisplayNames().size(); //return count+=10; }
*/
#Override
protected View getPendingView(ViewGroup parent) {
row = getLayoutInflater().inflate(R.layout.categorylist, null);
child = row.findViewById(R.id.tv_CategoryItem_Name);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_MPG1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_MPG2);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Price1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Price2);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Rating1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Rating2);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Year1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Year2);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.linear_CategoryList_itemlayer1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.linear_CategoryList_itemlayer2);
child.setVisibility(View.GONE);
/*
* child = row.findViewById(R.id.img_CategoryItem);
* child.setVisibility(View.GONE); child =
* row.findViewById(R.id.img_CategoryItem_Arrow);
* child.setVisibility(View.GONE);
*/
/*
* child = row.findViewById(R.id.linear_main_MPG);
* child.setVisibility(View.GONE);
*/
child = row.findViewById(R.id.throbber);
child.setVisibility(View.VISIBLE);
child.startAnimation(rotate);
return (row);
}
#Override
protected boolean cacheInBackground() {
//count += 10;
SystemClock.sleep(100000);
tempListNamesCat.clear();
tempListImagesCat.clear();
tempListmpgCat1.clear();
tempListmpgCat2.clear();
tempListpriceCat1.clear();
tempListpriceCat2.clear();
tempListYearCat1.clear();
tempListYearCat2.clear();
tempListRatingCat1.clear();
tempListRatingCat2.clear();
// countriesSubCat.clear();
// imagesSubCat.clear();
// YearSubCat1.clear();
// YearSubCat2.clear();
// mpgSubCat1.clear();
// mpgSubCat2.clear();
// priceSubCat1.clear();
// priceSubCat2.clear();
// ratingSubCat1.clear();
// ratingSubCat2.clear();
int lastOffset = getLastOffset();
if (lastOffset < LIST_SIZE) {
int limit = lastOffset + BATCH_SIZE;
for (int i = (lastOffset + 1); (i <= limit && i < LIST_SIZE); i++) {
tempListNamesCat.add(coll.getDisplayNames().get(i));
tempListImagesCat.add(coll.getImages().get(i));
tempListmpgCat1.add(coll.getMpg().get(i));
tempListmpgCat2.add(coll.getMpg().get(i + 1));
tempListpriceCat1.add(coll.getPrice().get(i));
tempListpriceCat2.add(coll.getPrice().get(i + 1));
tempListRatingCat1.add(coll.getRating().get(i));
tempListRatingCat2.add(coll.getRating().get(i + 1));
tempListYearCat1.add(coll.getYears().get(i));
tempListYearCat2.add(coll.getYears().get(i + 1));
}
setLastOffset(limit);
if (limit < LIST_SIZE) {
// return true;
return (getWrappedAdapter().getCount() < coll
.getDisplayNames().size());
} else {
return false;
}
} else {
return false;
}
}
#Override
protected void appendCachedData() {
#SuppressWarnings("unchecked")
// Activity activity = this;
// ArrayAdapter<String> arrAdapterNew =
// (ArrayAdapter<String>)getWrappedAdapter();
CategoryListLazyAdapter arrAdapterNewCategory = (CategoryListLazyAdapter) getWrappedAdapter();
// int listLen = tempList.size();
// int listLen = tempListNames.size();
countriesSubCat.addAll(tempListNamesCat);
imagesSubCat.addAll(tempListImagesCat);
mpgSubCat1.addAll(tempListmpgCat1);
mpgSubCat2.addAll(tempListmpgCat2);
priceSubCat1.addAll(tempListpriceCat1);
priceSubCat2.addAll(tempListpriceCat2);
ratingSubCat1.addAll(tempListRatingCat1);
ratingSubCat2.addAll(tempListRatingCat2);
YearSubCat1.addAll(tempListYearCat1);
YearSubCat2.addAll(tempListYearCat2);
arrAdapterNewCategory.notifyDataSetChanged();
/*Utility util = new Utility();
util.setListViewHeightBasedOnChildren(lvCategory);*/
/*
* for(int i=0; i<listLen; i++){ //
* arrAdapterNew.add(tempList.get(i)); }
*/
}
}
Thanks in adavance.
Try adding a ScrollView in the xml file.

nullPointerException in multi column list

I already tried references from similar question on SO, but hasn't got the appropriate solution.
I'm trying to fetch the data from a webpage and display it in format consisting of rows having 4 columns.
Data present on webpage:
SBIN ;1916.00;1886.85;1.54#LT ;1315.50;1310.30;0.40#TCS ;1180.00;1178.00;0.17#AXISBANK ;1031.30;1005.95;2.52#MARUTI ;1000.35;992.35;0.81#PNB ;931.90;916.35;1.70#GAIL ;400.00;398.45;0.39#
I want to diaplay it in the form
SBIN.........1916.00.....1886.85.....1.54
LT...........1315.50.....1310.30.....0.40 and so on.
Note that I don't want dots, I want each value to be a separate column within a row.
My Data consists of 7 rows.
When I run the below code, I get this output
i.e.
values[0] values[1] values[2] values[3]
values[1] values[2] values[3] values[4]
values[2] values[3] values[4] values[5]
(It prints all 4 cols of 1st row, then col 2-4 of 1st row and col1 of 2nd row, then cols 3-4 of 1st row and col 1-2 of 2nd row and so on...)
ReadWebpageAsyncTask.java
public class ReadWebpageAsyncTask extends Activity {
private EditText ed;
private ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ed = (EditText) findViewById(R.id.ed);
lv = (ListView) findViewById(R.id.list);
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://abc.com/default.aspx?id=G" });
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
int sub = result.lastIndexOf('#', result.length() - 1);
String s1 = result.substring(0, sub + 2);
String temp[];
String subarr[] = new String[100];
;
Log.v("data = ", s1);
// String s = s1.replace(";", " - ");
final String arr[] = s1.split("#");
for (int i = 0; i < arr.length; i++) {
Log.v("arr" + i, arr[i] + " " + arr.length);
}
for (int i = 0; i < arr.length - 1; i++)
{
temp = arr[i].split(";");
subarr[(4 * i)] = temp[0];
subarr[(4 * i) + 1] = temp[1];
subarr[(4 * i) + 2] = temp[2];
subarr[(4 * i) + 3] = temp[3];
}
lv.setAdapter(new MyAdapter(ReadWebpageAsyncTask.this, subarr));
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText android:id="#+id/ed"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Search">
</EditText>
<ListView android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
MyAdapter.java
public class MyAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
private String item1, item2, item3, item0;
int x = 0, i = 1, y = 1;
public MyAdapter(Context context, String[] values) {
super(context, R.layout.row, values);
this.context = context;
this.values = values;
}
#Override
public String getItem(int position) {
return values[position];
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.row, parent, false);
TextView tv1 = (TextView) rowView.findViewById(R.id.col1);
TextView tv2 = (TextView) rowView.findViewById(R.id.col2);
TextView tv3 = (TextView) rowView.findViewById(R.id.col3);
TextView tv4 = (TextView) rowView.findViewById(R.id.col4);
if (y < 8) {
item0 = getItem(position);
Log.v("pos = ", "" + position);
item1 = getItem(position + 1);
item2 = getItem(position + 2);
item3 = getItem(position + 3);
tv1.setText(item0);
tv2.setText(item1);
tv3.setText(item2);
tv4.setText(item3);
} else {
Log.v("y= ", "" + y);
}
return rowView;
}
}
row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView android:id="#+id/col1"
android:layout_width="150dip"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/col2"
android:layout_width="70dip"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/col3"
android:layout_width="70dip"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/col4"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
ANY HELP APPRICIATED
Try using ListView
Instead of TableLayout add ListView to your xml and place the content on table in new xml
Create an adapter by extending ArrayAdapter and set this adapter on your listView.
Don't add the views in your Java code, as they are added based on your XML file. It looks to me like your Java code is duplicating what you did in XML which is very precarious...
I don't see why you can't just remove the Java code and use setContentView to use the XML layout you defined.
Set the width to 0, and add weight as 1 for all the testviews, it will evenly assign space for every item in the row.
textView1.setWidth(0);
textView1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));

Categories

Resources