Textview below each image in a galleryview - android

In my application i am using some 5 galleryview to display the image, done correctly,i can able to populate the image correctly.Now i want to add textview below each image.
I want gallery view like this:
image1 Image2 Image3 image4
-------->Galleryview1
text1 text2 text3 text4
------------------------------------------
image1 image2 image3 image4
--------->Galleryview2
text1 text2 text3 text4
My code:
Adapter code:
public class GalleryviewAdapter extends BaseAdapter
{
static final String URL="http://aaaa/home.xml";
public static GalleryviewAdapter instance=new GalleryviewAdapter();
public static GalleryviewAdapter getInstance()
{
return instance;
}
Context context;
GalleryviewAdapter()
{
System.out.println("Inside cons");
getelement();
// getelementindia();
}
// String[] itemsArray =
// {
// "SUN","MON", "TUS", "WED", "THU", "FRI", "SAT"
// };
// MyAdapter(Context c)
// {
// context = c;
// }
private Activity activity;
private LayoutInflater inflater=null;
public void ImageAdapter(Activity a)
{
activity = a;
inflater = (LayoutInflater)activity.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
}
String imageurl[]= {};//new String[5];
// String imageurlindia[]={};
public void getelement()
{
System.out.println("Inside getelement");
// String[] itemsarray={};
// ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
// ArrayList<String> menuItems = new ArrayList<String>();
TaplistingParser parser = new TaplistingParser();
String xml= parser.getXmlFromUrl(URL);
Document doc=parser.getDomElement(xml);
// System.out.println("sssss="+doc);
NodeList nl=doc.getElementsByTagName("article");
imageurl = new String[nl.getLength()];
System.out.println("len="+nl.getLength());
for(int i=0; i < nl.getLength(); i++ )
{
// System.out.println("Inside for");
// HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// map.put("SectionName", parser.getValue(e, "sectionname"));
// System.out.println("b4 items="+parser.getValue(e, "sectionname"));
// itemsarray[i] = parser.getValue(e, "sectionname");
// System.out.println("items="+itemsarray[i]);
imageurl[i]=parser.getValue(e, "kickerimage");
// menuItems.add(parser.getValue(e, "sectionname"));
// menuItems.add(parser.getValue(e, "sectionname"));
// System.out.println("menu="+menuItems);
}
// String[] itemsarray = menuItems.toArray(new String[menuItems.size()]);
// String[] itemsarray = new String[menuItems.size()];
// itemsarray=menuItems.toArray(itemsarray);
//// for(int j= 0;j < itemsarray.length;j++ )
//// {
//// Log.d("string is",(itemsarray[j]));
//// }
// return itemsarray;
}
public int getCount()
{
// TODO Auto-generated method stub
return imageurl.length;
}
public Object getItem(int position)
{
// TODO Auto-generated method stub
return imageurl[position];
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
// System.out.println("sssssssss="+imageurl[position]);
// View vi=convertView;
// ViewHolder holder;
// if(convertView==null)
// {
// vi = inflater.inflate(R.layout.main, null);
// holder=new ViewHolder();
// holder.text=(TextView)vi.findViewById(R.id.Txt01);
// holder.image=(ImageView)vi.findViewById(R.id.imageview1);
// vi.setTag(holder);
// }
Bitmap bitmap=DownloadImage(imageurl[position]);
View rowView = LayoutInflater
.from(parent.getContext())
.inflate(R.layout.main, null);
//
ImageView imgview=(ImageView)rowView.findViewById(R.id.imageview1);
imgview.setImageBitmap(bitmap);
//
// ImageView imgviewindia=(ImageView)rowView.findViewById(R.id.imageviewindia);
// imgviewindia.setImageBitmap(bitmap);
// TextView listTextView = (TextView)rowView.findViewById(R.id.);
// listTextView.setText(getelement()[position]);
return rowView;
}
private Bitmap DownloadImage(String URL)
{
// System.out.println("image inside="+URL);
Bitmap bitmap = null;
InputStream in = null;
try
{
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// System.out.println("image last");
return bitmap;
}
private InputStream OpenHttpConnection(String urlString)
throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK)
{
in = httpConn.getInputStream();
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
}
}
// }
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" >
<ImageView
android:id="#+id/imageview1"
android:layout_marginLeft="10dp"
android:layout_marginTop="-20dp"
android:layout_width="120dp"
android:layout_height="100dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/Txt01" />
</LinearLayout>
My main activitycode:
public class NewspapperActivity extends Activity
{
/** Called when the activity is first created. */
Context ctx;
static final String URLHeading = "http://aaaaaa.in/cccccc.xml";
String[] headingurl=new String[20];
// ListViewwithimageAdapter adapter;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.galleryview);
// ArrayList<String>item = new ArrayList<String>();
Heading parser = new Heading();
String xmldata = parser.getXmlFromUrl(URLHeading);
Document domelement = parser.getDomElement(xmldata);
NodeList node = domelement.getElementsByTagName("item");
// int i ;
TextView txt1 = (TextView)findViewById(R.id.Text01);
TextView txt2 = (TextView)findViewById(R.id.Text02);
TextView txt3 = (TextView)findViewById(R.id.Text03);
TextView txt4 = (TextView)findViewById(R.id.Text04);
TextView txt5 = (TextView)findViewById(R.id.Text05);
// glly.setAdapter(adapter);
// System.out.println("prakash4");
// for(i=0 ; i < node.getLength();i++)
// {
Element e0 = (Element) node.item(0);
txt1.setText(parser.getValue(e0, "sectionname"));
Element e1 = (Element) node.item(1);
txt2.setText(parser.getValue(e1, "sectionname"));
Element e2 = (Element) node.item(2);
txt3.setText(parser.getValue(e2, "sectionname"));
Element e3 = (Element) node.item(3);
txt4.setText(parser.getValue(e3, "sectionname"));
Element e4 = (Element) node.item(4);
txt5.setText(parser.getValue(e4, "sectionname"));
Gallery glly= (Gallery)findViewById(R.id.Gallery01);
Gallery glly2= (Gallery)findViewById(R.id.Gallery02);
Gallery glly3= (Gallery)findViewById(R.id.Gallery03);
Gallery glly4= (Gallery)findViewById(R.id.Gallery04);
Gallery glly5= (Gallery)findViewById(R.id.Gallery05);
// GridView gv = (GridView)findViewById(R.id.grid);
// ListViewwithimageAdapter adapter = ListViewwithimageAdapter.getInstance();
GalleryviewAdapter adapter=GalleryviewAdapter.getInstance();
glly.setAdapter(adapter);
glly.setSelection(1);
glly2.setAdapter(adapter);
glly2.setSelection(1);
glly3.setAdapter(adapter);
glly3.setSelection(1);
glly4.setAdapter(adapter);
glly4.setSelection(1);
glly5.setAdapter(adapter);
glly5.setSelection(1);
// item.add(parser.getValue(e, "sectionname"));
// }
// gv.setAdapter(new GridviewImageAdapter(this));
}
}
I am new to this ..Please help me.Thanks in advance..

Use below xml code instead of your xml code, it will solve your problem and if you have any problem regarding that then tell me.
<?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="fill_parent" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/imageview1"
android:layout_width="120dp"
android:layout_height="100dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="-20dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:src="#drawable/ic_launcher"/>
<TextView
android:id="#+id/Txt01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageview1"
android:layout_centerHorizontal="true"
android:text="Dipak" />
</RelativeLayout>
</RelativeLayout>

Related

Correct item is not selected in Listview

I am using this Tutorial for Creating a custom listview with radio button. In this tutorial when we click the item in the list then color of item change.
This is happening when i am testing this code above 4.0 but below 4.0 it is not workin properly I am not understand why????
Class Blog.java
public class Blog extends Activity {
ListView listView;
ArrayList< String>arrayList; // list of the strings that should appear in ListView
ArrayAdapter arrayAdapter; // a middle man to bind ListView and array list
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom);
listView = (ListView) findViewById(R.id.lstDemo);
// LIST OF STRINGS / DATA THAT SHOULD APPEAR IN LISTVIEW HERE WE HAVE HARD CODED IT WE CAN TAKE THIS INPUT FROM USER AS WELL
arrayList = new ArrayList();
arrayList.add("India");
arrayList.add("USA");
arrayList.add("England");
arrayList.add("Singapur");
arrayList.add("China");
arrayList.add("Canada");
arrayList.add("Srilanka");
arrayList.add("SouthAfrica");
arrayAdapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_single_choice,arrayList);
listView.setAdapter(arrayAdapter);
// LETS HIGHLIGHT SELECTED ITEMS
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView arg0, View view, int position,
long itemId) {
/*
* when we click on item on list view we can get it catch item here.
* so view is the item clicked in list view and position is the position
* of that item in list view which was clicked.
*
* Now that we know which item is click we can easily change the color
* of text but when we click on next item we we have to deselect the old
* selected item means recolor it back to default , and then hight the
* new selected item by coloring it .
*
* So here's the code of doing it.
*
*
* */
CheckedTextView textView = (CheckedTextView) view;
for (int i = 0; i < listView.getCount(); i++) {
textView= (CheckedTextView) listView.getChildAt(i);
if (textView != null) {
textView.setTextColor(Color.WHITE);
}
}
listView.invalidate();
textView = (CheckedTextView) view;
if (textView != null) {
textView.setTextColor(Color.BLUE);
}
}
});
}
}
My xml View
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/lstDemo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:choiceMode="singleChoice">
</ListView>
Define your variables like this
private ProgressDialog pDialog;
private ListView lv;
private ArrayList<GoModelAll> m_ArrayList = null;
GoArrayAdapter gaa;
Define your AsyncTask like this
new GoAsyncTask().execute();
Your AsyncTask class Code like this
class GoAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
/*pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();*/
pd.show();
}
#Override
protected String doInBackground(String... params) {
sal = new StaticApiList();
myUrl = StaticApiList.go_api;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(myUrl);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println("httpResponse");
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
jsonString = stringBuilder.toString();
Log.i("talk_all_json", jsonString);
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("Exception generates caz of httpResponse :"
+ cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out
.println("Second exception generates caz of httpResponse :"
+ ioe);
ioe.printStackTrace();
}
return null;
}
#SuppressWarnings("static-access")
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
vivek = true;
try{
m_ArrayList = new ArrayList<GoModelAll>();
if (jsonString.length() > 0) {
JSONArray jArray = new JSONArray(jsonString);
dh.open();
for(int i=0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
description = jObject.getString("description");
excert = jObject.getString("excert");
thumsrc = jObject.getString("thumsrc");
title = jObject.getString("title");
postid = jObject.getInt("postid");
Log.d("talklog", "Title -> " + title + " , thumsrc -> " + thumsrc
+ " , excert -> " + excert + " , description -> " + description);
Log.d("talklog", "============================= end of " + i + " ===============================");
gma = new GoModelAll();
gma.description = description;
gma.excert = excert;
gma.thumsrc = thumsrc;
gma.title = title;
gma.postid = postid;
Cursor cursor = dh.getSeenStatus(gma.postid);
if(cursor.getCount()>0)
{
cursor.moveToFirst();
if(cursor.getInt(0) == 0)
{
gma.isSeen = false;
}
else
{
gma.isSeen = true;
}
}
else
{
ContentValues cv = new ContentValues();
cv.put(DbHandler.KEY_ID, postid);
cv.put(DbHandler.KEY_VALUE, 0);
dh.addData(DbHandler.TABLE_SEEN, cv);
}
m_ArrayList.add(gma);
}
dh.close();
}
gaa = new GoArrayAdapter(getActivity(), m_ArrayList);
lv = (ListView) getActivity().findViewById(R.id.go_list);
lv.setVisibility(View.VISIBLE);
lv.setAdapter(gaa);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
dh.open();
dh.updateSeenStatus(m_ArrayList.get(arg2).postid, 1);
m_ArrayList.get(arg2).isSeen = true;
dh.close();
GoDetail fragment = new GoDetail();
Bundle bundle = new Bundle();
bundle.putString("title", m_ArrayList.get(arg2).title);
bundle.putString("excert", m_ArrayList.get(arg2).excert);
bundle.putString("description", m_ArrayList.get(arg2).description);
bundle.putString("thumsrc", m_ArrayList.get(arg2).thumsrc);
bundle.putString("header_title", "Go");
//bundle.putInt("postid", m_ArrayList.get(arg2).postid);
fragment.setArguments(bundle);
((BaseContainerFragment)getParentFragment()).replaceFragment(fragment, true);
}
});
}catch(Exception e){
e.printStackTrace();
}
//pDialog.dismiss();
pd.dismiss();
}
}
Your Adapter class
public class GoArrayAdapter extends ArrayAdapter<GoModelAll> {
private final Context context;
ImageLoader imgLoader;
private final ArrayList<GoModelAll> values;
DataHelper dh;
public GoArrayAdapter(Context context,
ArrayList<GoModelAll> values) {
super(context, R.layout.go_row, values);
this.context = context;
this.values = values;
imgLoader = new ImageLoader(context);
dh = new DataHelper(context);
}
#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.go_row, parent, false);
/** Get view over here.. */
GoModelAll asm = values.get(position);
TextView title = (TextView) rowView.findViewById(R.id.go_tv);
ImageView business_logo = (ImageView) rowView.findViewById(R.id.go_image);
ImageView go_red = (ImageView)rowView.findViewById(R.id.go_red);
if(asm.isSeen)
{
go_red.setVisibility(View.INVISIBLE);
}
/**Set view over here..*/
title.setText(asm.title);
// Loader image - will be shown before loading image
int loader = R.drawable.image_not_available;
String image_url = asm.thumsrc;
imgLoader.DisplayImage(image_url, loader, business_logo);
return rowView;
}
}
At last your Model class
public class GoModelAll {
public String description = "";
public String excert = "";
public String thumsrc = "";
public String title = "";
public int postid = 0;
public boolean isSeen = false;
}
Show us your adapter code as well and try not to change an item of list view from setOnItemClickListener instead change your data and notify adapter to refresh the view.
Set this as background to your list item :
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="#color/white" />
<item android:color="#color/black" />
</selector>

Parse XML in Android for ListView

I'm currently working on parsing xml for android listview.
I was able to parse and get a data for my listview.
But, what if I want to get a specific data from that XML. hmmm like performing
something in SQL "select * from [table] where id = 1".
Something like that...How can I do that with my XML?
Thanks
public class XMLParsing_DisplayListviewActivity extends Activity {
String res1 = null;
InputStream is = null;
StringBuilder sb = null;
public String[] mCD;
public String[] mTitle;
public String[] mArtist;
public String[] mCountry;
public String[] mCompany;
public String[] mPrice;
public String[] mYear;
ListView listview;
ProgressDialog mDialog = null; // thread code
private Runnable viewOrders; // thread code
private Thread thread1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listview=(ListView)findViewById(R.id.listview);
mDialog = new ProgressDialog(this); // thread code
mDialog.setMessage("Please wait...");
viewOrders = new Runnable(){
public void run(){
load();
runOnUiThread(returnRes);
}
};
thread1 = new Thread(null, viewOrders, "Background"); // thread
thread1.start(); // thread code
mDialog.show();
}
private Runnable returnRes = new Runnable(){
public void run(){
mDialog.cancel();
for(int i=0;i<mCD.length;i++){
System.out.println("======================");
System.out.println("Title :- "+mTitle[i]);
System.out.println("Artist :- "+mArtist[i]);
System.out.println("Country :- "+mCountry[i]);
System.out.println("Company :- "+mCompany[i]);
System.out.println("Price :- "+mPrice[i]);
System.out.println("Year :- "+mYear[i]);
}
listview.setAdapter(new CustomAdapter(XMLParsing_DisplayListviewActivity.this));
}
};
public void load() {
//mLoading = true;
Document doc = null;
HttpURLConnection urlConnection = null;
URL url = null;
try {
//url = new URL(urlString.toString());
url = new URL("http://www.xmlfiles.com/examples/cd_catalog.xml");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(urlConnection.getInputStream());
} catch (Exception e) {
System.out.println("e"+e.toString());
}
try {
NodeList nodes = doc.getElementsByTagName("CD");
// iterate the employees
mCD=new String[nodes.getLength()];
mTitle=new String[nodes.getLength()];
mArtist=new String[nodes.getLength()];
mCountry=new String[nodes.getLength()];
mCompany=new String[nodes.getLength()];
mPrice=new String[nodes.getLength()];
mYear=new String[nodes.getLength()];
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList cd = element.getElementsByTagName("CD");
Element line = (Element) cd.item(0);
mCD[i]=getCharacterDataFromElement(line);
NodeList title = element.getElementsByTagName("TITLE");
line = (Element) title.item(0);
mTitle[i]=getCharacterDataFromElement(line);
//System.out.println("catcatcatmidmidmidmidName: " + getCharacterDataFromElement(line));
NodeList artist = element.getElementsByTagName("ARTIST");
line = (Element) artist.item(0);
mArtist[i]=getCharacterDataFromElement(line);
//System.out.println("salary: " + getCharacterDataFromElement(line));
NodeList country = element.getElementsByTagName("COUNTRY");
line = (Element) country.item(0);
mCountry[i]=getCharacterDataFromElement(line);
NodeList company = element.getElementsByTagName("COMPANY");
line = (Element) company.item(0);
mCompany[i]=getCharacterDataFromElement(line);
NodeList price = element.getElementsByTagName("PRICE");
line = (Element) price.item(0);
mPrice[i]=getCharacterDataFromElement(line);
NodeList year = element.getElementsByTagName("YEAR");
line = (Element) year.item(0);
mYear[i]=getCharacterDataFromElement(line);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "?";
}
public class CustomAdapter extends BaseAdapter {
private Context mContext;
Application app;
private LayoutInflater inflater=null;
public CustomAdapter(Context c) {
mContext = c;
inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return mTitle.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.list, null);
TextView txt=(TextView)vi.findViewById(R.id.txtview_title);
TextView txt1=(TextView)vi.findViewById(R.id.txtview_artist);
TextView txt2=(TextView)vi.findViewById(R.id.txtview_country);
TextView txt3=(TextView)vi.findViewById(R.id.txtview_company);
TextView txt4=(TextView)vi.findViewById(R.id.txtview_price);
TextView txt5=(TextView)vi.findViewById(R.id.txtview_year);
txt.setText("Title : " + mTitle[position]);
txt1.setText("Artist : " + mArtist[position]);
txt2.setText("Country : " + mCountry[position]);
txt3.setText("Company : " + mCompany[position]);
txt4.setText("Price : " + mPrice[position]);
txt5.setText("Year : " + mYear[position]);
return vi;
};
}
}
You should parse the xml file just once and create an array or list of objects from it. Once you have everything on memory you can use the array to populate your list with an ArrayAdapter. The position in the array can be used as your id. If you rather have an attribute of the object be the id instead of the position then you can just sort the array accordingly.

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.

i have one error passing of constructor as this in listfragments

I am newer to the fragments. In oncreate method i pass this value to Appetizerlist. but it shows an error. How to clear the error? Please help me.
public class MyListFragment1 extends ListFragment {
ImageView back;
String url = Main.url;
String Qrimage;
Bitmap bmp;
ListView list;
AppetiserFragment adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.applistviewfragment, null);
list = (ListView) view.findViewById(R.id.list);
return view;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
InputStream is = null;
String result = "";
JSONObject jArray = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url + "test.php3");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
// TODO: handle exception
Log.e("Log", "Error in Connection" + e.toString());
// Intent intent = new Intent(ViewQRCode.this, PimCarder.class);
// startActivity(intent);
}
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();
jArray = new JSONObject(result);
JSONArray json = jArray.getJSONArray("appetiser");
adapter = new AppetiserFragment(this, json);
list.setAdapter(adapter);
} catch (Exception e) {
// TODO: handle exception
Log.e("log", "Error in Passing data" + e.toString());
}
}
}
AppetiserFragment.java
public class AppetiserFragment extends BaseAdapter {
String url = Main.url;
public Context Context;
String qrimage;
Bitmap bmp, resizedbitmap;
Bitmap[] bmps;
Activity activity = null;
private LayoutInflater inflater;
private ImageView[] mImages;
String[] itemimage;
TextView[] tv;
String itemname, price, desc, itemno;
String[] itemnames, checkeditems, itemnos;
String[] prices;
String[] descs;
HashMap<String, String> map = new HashMap<String, String>();
public AppetiserFragment(Context context, JSONArray imageArrayJson) {
Context = context;
// inflater =
System.out.println(imageArrayJson);
// (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader=new ImageLoader(activity);
inflater = LayoutInflater.from(context);
this.mImages = new ImageView[imageArrayJson.length()];
this.bmps = new Bitmap[imageArrayJson.length()];
this.itemnames = new String[imageArrayJson.length()];
this.prices = new String[imageArrayJson.length()];
this.descs = new String[imageArrayJson.length()];
this.itemnos = new String[imageArrayJson.length()];
try {
for (int i = 0; i < imageArrayJson.length(); i++) {
JSONObject image = imageArrayJson.getJSONObject(i);
qrimage = image.getString("itemimage");
itemname = image.getString("itemname");
itemno = new Integer(i + 1).toString();
price = image.getString("price");
desc = image.getString("itemdesc");
System.out.println(price);
itemnames[i] = itemname;
prices[i] = price;
descs[i] = desc;
itemnos[i] = itemno;
byte[] qrimageBytes = Base64.decode(qrimage.getBytes());
bmp = BitmapFactory.decodeByteArray(qrimageBytes, 0,
qrimageBytes.length);
int width = 100;
int height = 100;
resizedbitmap = Bitmap.createScaledBitmap(bmp, width, height,
true);
bmps[i] = bmp;
mImages[i] = new ImageView(context);
mImages[i].setImageBitmap(resizedbitmap);
mImages[i].setScaleType(ImageView.ScaleType.FIT_START);
// tv[i].setText(itemname);
}
System.out.println(map);
} catch (Exception e) {
// TODO: handle exception
}
}
public AppetiserFragment() {
// TODO Auto-generated constructor stub
}
public int getCount() {
return mImages.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder viewHolder;
if (view == null) {
view = inflater.inflate(R.layout.appetiserlistview, null);
System.out.println("prakash");
viewHolder = new ViewHolder();
viewHolder.image = (ImageView) view
.findViewById(R.id.appetiserimage);
viewHolder.text = (TextView) view.findViewById(R.id.appetisertext);
viewHolder.desc = (TextView) view.findViewById(R.id.appetiserdesc);
viewHolder.price = (TextView) view
.findViewById(R.id.appetiserprice);
viewHolder.appitemnum = (TextView) view
.findViewById(R.id.appitemno);
// viewHolder.checkbox = (CheckBox) view.findViewById(R.id.bcheck);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.image.setImageBitmap(bmps[position]);
viewHolder.appitemnum.setText(itemnos[position]);
viewHolder.price.setText(prices[position]);
viewHolder.desc.setText(descs[position]);
// viewHolder.checkbox.setTag(itemnames[position]);
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(itemnames[position]);
return view;
}
static class ViewHolder {
protected TextView text, price, desc, appitemnum;
protected ImageView image;
public static CheckBox checkbox = null;
}
}
i Given whole code i want custom listview using listfragments
In the above code in this line, I'm getting an error at adapter = new Appetizerlist(this, json); Please tell me how to solve the problem. Help me.
as onCreate called before onCreateView so list will null there in onCreate ...........
http://developer.android.com/guide/topics/fundamentals/fragments.html
in oncreate
list.setAdapter(adapter);
in onCreateView you initlized that
list = (ListView) view.findViewById(R.id.list);
......
so move this line list.setAdapter(adapter); in onCreateView
You have error in following line.
adapter = new Appetizerlist(this, json);
Change it to
adapter = new Appetizerlist(getActivity().getApplicationContext(), json);

How to display the custom listview using base adapter in listfragments?

I want do custom listview using base adapter in listfragment
I try this code:
public class MyListFragment1 extends ListFragment {
ImageView back;
String url = Main.url;
String Qrimage;
Bitmap bmp;
ListView list;
AppetiserFragment adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View tmp_view = inflater.inflate(R.layout.applistviewfragment, container, false);
ListView list = (ListView) tmp_view.findViewById(R.id.list);
InputStream is = null;
String result = "";
JSONObject jArray = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url + "test.php3");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
// TODO: handle exception
Log.e("Log", "Error in Connection" + e.toString());
// Intent intent = new Intent(ViewQRCode.this, PimCarder.class);
// startActivity(intent);
}
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();
jArray = new JSONObject(result);
JSONArray json = jArray.getJSONArray("appetiser");
adapter = new AppetiserFragment(getActivity(), json);
list.setAdapter(adapter);
} catch (Exception e) {
// TODO: handle exception
Log.e("log", "Error in Passing data" + e.toString());
}
return tmp_view;
}
}
AppetiserFragment.java
public class AppetiserFragment extends BaseAdapter {
public static ArrayList<String> arr = new ArrayList<String>();
public static ArrayList<String> itemprice = new ArrayList<String>();
public static ArrayList<Bitmap> image = new ArrayList<Bitmap>();
String url = Main.url;
public Context Context;
String qrimage;
Bitmap bmp, resizedbitmap;
Bitmap[] bmps;
Activity activity = null;
private LayoutInflater inflater;
private ImageView[] mImages;
String[] itemimage;
TextView[] tv;
String itemname, price, desc, itemno;
String[] itemnames, checkeditems, itemnos;
String[] prices;
String[] descs;
HashMap<String, String> map = new HashMap<String, String>();
public AppetiserFragment(Context context, JSONArray imageArrayJson) {
Context = context;
// inflater =
System.out.println(imageArrayJson);
// (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader=new ImageLoader(activity);
inflater = LayoutInflater.from(context);
this.mImages = new ImageView[imageArrayJson.length()];
this.bmps = new Bitmap[imageArrayJson.length()];
this.itemnames = new String[imageArrayJson.length()];
this.prices = new String[imageArrayJson.length()];
this.descs = new String[imageArrayJson.length()];
this.itemnos = new String[imageArrayJson.length()];
try {
for (int i = 0; i < imageArrayJson.length(); i++) {
JSONObject image = imageArrayJson.getJSONObject(i);
qrimage = image.getString("itemimage");
itemname = image.getString("itemname");
itemno = new Integer(i + 1).toString();
price = image.getString("price");
desc = image.getString("itemdesc");
**System.out.println(price);**
itemnames[i] = itemname;
prices[i] = price;
descs[i] = desc;
itemnos[i] = itemno;
byte[] qrimageBytes = Base64.decode(qrimage.getBytes());
bmp = BitmapFactory.decodeByteArray(qrimageBytes, 0,
qrimageBytes.length);
int width = 100;
int height = 100;
resizedbitmap = Bitmap.createScaledBitmap(bmp, width, height,
true);
bmps[i] = bmp;
mImages[i] = new ImageView(context);
mImages[i].setImageBitmap(resizedbitmap);
mImages[i].setScaleType(ImageView.ScaleType.FIT_START);
// tv[i].setText(itemname);
}
System.out.println(map);
} catch (Exception e) {
// TODO: handle exception
}
}
public AppetiserFragment() {
// TODO Auto-generated constructor stub
}
public int getCount() {
return mImages.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder viewHolder;
if (view == null) {
view = inflater.inflate(R.layout.appetiserlistview, null);
viewHolder = new ViewHolder();
viewHolder.image = (ImageView) view
.findViewById(R.id.appetiserimage);
viewHolder.text = (TextView) view.findViewById(R.id.appetisertext);
viewHolder.desc = (TextView) view.findViewById(R.id.appetiserdesc);
viewHolder.price = (TextView) view
.findViewById(R.id.appetiserprice);
viewHolder.appitemnum = (TextView) view
.findViewById(R.id.appitemno);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.image.setImageBitmap(bmps[position]);
viewHolder.appitemnum.setText(itemnos[position]);
viewHolder.price.setText(prices[position]);
viewHolder.desc.setText(descs[position]);
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(itemnames[position]);
return view;
}
static class ViewHolder {
protected TextView text, price, desc, appitemnum;
protected ImageView image;
public static CheckBox checkbox = null;
}
}
I can able to print price value. If I do separately as custom listview I can able to image, text, desc, price. But in MyFragmentlist1 extends with listfragment means I cannot able to view in custom listview. I thought MyListFragment1 in this class only I have problem.
First Create a separate layout layout_txtview. I am just using a textview. You can create layout according to items you want to show in a single row.
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textColor="#000000"
android:textAppearance="?android:attr/textAppearanceSmall" />
Now Use this layout to inflate in getView() method of your custom adapter.
Now in onCreate() method of MyListFragment1 class just set the adapter to your custom adapter
setAdapter(new MyListFragment1 (<apss your constructor argument>));
and its done.
Try moving the setAdapter in the onActivityCreated callback, in this way
#Override
public void onActivityCreated(Bundle savedInstanceState) {
ListView list = getListView();
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}

Categories

Resources