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));
Related
I am loading pictures (below ~3MB in size) into Cardview from a database and it was infalte in Listviewstview.
The loading and browsing of these pictures is way too slow.
Is there any method to downscale these pictures to speed up & sometimes dispalyind [Duplicate] images on other card view?
cardview xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/cv"
android:layout_width="match_parent"
android:layout_height="140dp"
android:alpha="1"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
card_view:cardBackgroundColor="#FFFFFF"
card_view:cardCornerRadius="10dp">
<RelativeLayout
android:id="#+id/r1"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/img_product"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_marginLeft="#dimen/activity_vertical_margin"
android:layout_marginTop="20dp" />
<TextView
android:id="#+id/product_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/img_product"
android:layout_toEndOf="#+id/img_product"
android:layout_toRightOf="#+id/img_product"
android:inputType="textMultiLine"
android:text="Parvana Fancy Necklace Set"
android:textSize="18dp"
android:textStyle="bold" />
<TextView
android:id="#+id/txt_total"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/img_product"
android:layout_toEndOf="#+id/img_product"
android:layout_toRightOf="#+id/img_product"
android:text="RS.234"
android:textSize="20dp"
android:textStyle="bold" />
<Button
android:id="#+id/btn_remove"
android:layout_width="32dp"
android:layout_height="wrap_content"
android:background="#drawable/wishlistddelete_selector"
android:drawableLeft="#drawable/delete_icon"
android:layout_alignTop="#+id/txt_total"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
listview xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/home_bground">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/topbar1"
android:layout_width="match_parent"
android:layout_height="55dp"
android:background="#drawable/top">
<ImageView
android:id="#+id/btn_hme"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:src="#drawable/home_icon" />
<TextView
android:id="#+id/txt_pro_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center_horizontal"
android:text="Shopping Cart"
android:textColor="#ffffff"
android:textSize="18dp"
android:textStyle="bold" />
</RelativeLayout>
<ListView
android:id="#+id/list_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/topbar1"
android:animationCache="false"
android:dividerHeight="0dp"
android:listSelector="#00000000"
android:scrollingCache="false"
android:smoothScrollbar="true" />
</RelativeLayout>
</RelativeLayout>
by using sqllite access the data from database
public class Wishlist extends Activity {
Button checkout;
ListView ListCart;
String name, cusid, ffname, llname, phone, fax, password, email;
String[] qu, s;
int[] g;
int k = 0;
String cost;
ProgressDialog pDialog = null;
List<CartProducts> product_list;
Context ctx;
Integer pos = 0, total = 0, q = 0, gtot = 0, total1 = 0, sum = 0;
SQLiteDatabase FavData;
private Context context;
Integer i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modifywishlist);
Intent page1 = getIntent();
cusid = page1.getStringExtra("cus_id");
ffname = page1.getStringExtra("fname");
llname = page1.getStringExtra("lname");
phone = page1.getStringExtra("ph");
fax = page1.getStringExtra("fax");
password = page1.getStringExtra("password");
email = page1.getStringExtra("email");
ListCart = (ListView) findViewById(R.id.list_item);
ListCart.setScrollingCacheEnabled(false);
Intent page2 = getIntent();
i = page2.getIntExtra("kvalue",1);
pDialog = new ProgressDialog(this);
ctx = this;
FavData = Wishlist.this.openOrCreateDatabase("SHOPPING_CARTFAV", MODE_PRIVATE, null);
FavData.execSQL("CREATE TABLE IF NOT EXISTS fav_items(product_id varchar, name varchar, price varchar, quantity integer, model varchar, image varchar, manufacturer varchar )");
ArrayList<CartProducts> myList = new ArrayList<CartProducts>();
Cursor crsr = FavData.rawQuery("SELECT * FROM fav_items", null);
final String[] productID = new String[crsr.getCount()];
final String[] ProductName = new String[crsr.getCount()];
final String[] ProductPrice = new String[crsr.getCount()];
final String[] ProductQuantity = new String[crsr.getCount()];
final String[] ProductModel = new String[crsr.getCount()];
final String[] ProductImage = new String[crsr.getCount()];
final String[] ProductManufacturer = new String[crsr.getCount()];
int j = 0;
while (crsr.moveToNext()) {
String id = crsr.getString(crsr.getColumnIndex("product_id"));
productID[j] = id;//product_id,name,price,quantity,model,image,manufacturer
name = crsr.getString(crsr.getColumnIndex("name"));
ProductName[j] = name;
String price = crsr.getString(crsr.getColumnIndex("price"));
ProductPrice[j] = price;
String s = ProductPrice[j].toString();
s = s.replace(",", "");
String[] parts = s.split("\\."); // escape .
String part1 = parts[0];
String part2 = parts[1];
part1 = part1.replace("₹", "");
total = Integer.parseInt(part1); // Toast.makeText(Table.this, part1, Toast.LENGTH_SHORT).show();
String qnty = crsr.getString(crsr.getColumnIndex("quantity"));
ProductQuantity[j] = qnty;
String s2 = ProductQuantity[j].toString();
total1 = Integer.parseInt(s2);
sum = total * total1;
String model = crsr.getString(crsr.getColumnIndex("model"));
ProductModel[j] = model;
String image = crsr.getString(crsr.getColumnIndex("image"));
ProductImage[j] = image;
String manufacturer = crsr.getString(crsr.getColumnIndex("manufacturer"));
ProductManufacturer[j] = manufacturer;
myList.add(new CartProducts(productID[j], ProductName[j], ProductPrice[j], ProductQuantity[j], ProductModel[j], ProductImage[j], ProductManufacturer[j]));
gtot = gtot + sum;
j++;
}
ListCart.setAdapter(new Wishlist_Listadapter(ctx, R.layout.activity_wishlist_cartrow, myList));
String s1 = ProductPrice.toString();
}
}
adapter class
public class Wishlist_Listadapter extends ArrayAdapter<CartProducts> {
Bitmap bitmap;
ImageView img;
String urll, name,totalps;
SQLiteDatabase FavData;
Integer total = 0, quanty = 1, grandtot = 0, i = 0;
String it;
Button addbtn, minbtn;
EditText editqu;
int total1 = 0, quantity=0, fulltotal = 0, sum;
SQLiteOpenHelper dbhelper;
Wishlist_Listadapter cart = Wishlist_Listadapter.this;
private int resource;
private LayoutInflater inflater;
private Context context;
int count=1 ;
public Wishlist_Listadapter(Context ctx, int resourceId, List<CartProducts> objects) {
super(ctx, resourceId, objects);
resource = resourceId;
inflater = LayoutInflater.from(ctx);
context = ctx;
}
public View getView(int position, View convertView, ViewGroup parent) {
/* create a new view of my layout and inflate it in the row */
convertView = (RelativeLayout) inflater.inflate(resource, null);
final ViewHolder viewholder;
viewholder = new ViewHolder();
final CartProducts banqt = getItem(position);
totalps=(banqt.getPrice());
String s = totalps.toString();
s = s.replace(",", "");
String[] parts = s.split("\\."); // escape .
String part1 = parts[0];
String part2 = parts[1];
part1 = part1.replace("₹", "");// Toast.makeText(getContext(), part1, Toast.LENGTH_LONG).show();
total = Integer.parseInt(part1);
quanty = Integer.parseInt(banqt.getQuantity());
grandtot = total *quanty;
viewholder.total = (TextView) convertView.findViewById(R.id.txt_total);
viewholder.total.setText(String.valueOf(grandtot));
Button delet = (Button) convertView.findViewById(R.id.btn_remove);
delet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*delete function*/
it = banqt.getProduct_id();
FavData = context.openOrCreateDatabase("SHOPPING_CARTFAV", context.MODE_PRIVATE, null);
FavData.execSQL("DELETE FROM fav_items WHERE product_id=" + it + ";");
Intent intent = ((Wishlist) context).getIntent();
((Wishlist) context).finish();
context.startActivity(intent);
}
});
viewholder.txtName = (TextView) convertView.findViewById(R.id.product_name);
viewholder.txtName.setText(banqt.getName());
img = (ImageView) convertView.findViewById(R.id.img_product);
urll = banqt.getImage().toString();
urll = urll.replaceAll(" ", "%20");// Toast.makeText(getContext(),urll,Toast.LENGTH_LONG).show();
new LoadImage().execute(urll);
return convertView;
}
static class ViewHolder {
TextView txtName;
TextView total;
EditText editqu;
TextView txtprice;
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if (image != null) {
img.setImageBitmap(image);
// pDialog.dismiss();
} else {
// pDialog.dismiss();
Toast.makeText(getContext(), "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
}
Try scale your bitmap to lower its actual resolution, I've used the following codes to reduce bitmap's size.
int nh = (int) (bitmap.getHeight() * (512.0 / bitmap.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 512, nh, true);
For you case, add the following codes into your adapter class AsyncTask's doInBackground method
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
int nh = (int) (bitmap.getHeight() * (512.0 / bitmap.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 512, nh, true);
} catch (Exception e) {
e.printStackTrace();
}
return scaled;
Return scaled bitmap instead of original bitmap.
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>
I have two spinners in an AlertDialog, the spinners look good, and the list of items is correct, it shows the first items of each list. But when I click any of the two spinner, the dropdown list is not displayed to select some other item. The spinners do nothing. This does not happen when I was the same two spinners outside the AlertDialog.
This is the code of AlertDialog:
private void mostrar_alertdialog_spinners() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
TextView title = new TextView(this);
title.setText("Selecciona un archivo:");
title.setPadding(10, 10, 10, 10);
title.setGravity(Gravity.CENTER);
title.setTextColor(Color.rgb(0, 153, 204));
title.setTextSize(23);
builder.setCustomTitle(title);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout_spinners = inflater.inflate(R.layout.layout_spinners,null);
sp_titulos_carpetas = (Spinner) layout_spinners.findViewById(R.id.spinner_titulo_carpetas);
sp_titulos_textos = (Spinner) layout_spinners.findViewById(R.id.spinner_textos_carpetas);
builder.setView(layout_spinners);
builder.setCancelable(false);
builder.show();
//configuracion de textos en memoria sd
String path = Environment.getExternalStorageDirectory().toString()+"/Textos/";
File f = new File(path);
String[] fileStr = f.list();
ArrayList<String> lista_lista_CARPETAS = new ArrayList<String>();
for (String lista_texto : fileStr) {
lista_lista_CARPETAS.add(lista_texto);
}
Collections.sort(lista_lista_CARPETAS, new AlphanumComparator());
String[] lista_k = f.list(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
File f = new File(dir, name);
return f.isDirectory();
}
});
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
File[] files = f.listFiles(fileFilter);
ArrayAdapter<String> carpetas = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, lista_k);
carpetas.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
sp_titulos_carpetas.setAdapter(carpetas);
//ARRAY CON TITULOS DE ARCHIVOS TXT
String camino = Environment.getExternalStorageDirectory().toString()+"/Textos/" + "Naxos"+ "/";
File t = new File(camino);
String[] lista_textos = t.list();
ArrayList<String> lista_lista_textos = new ArrayList<String>();
for (String lista_texto : lista_textos) {
if (lista_texto.toLowerCase().endsWith(".txt")) {
lista_lista_textos.add(lista_texto);
}
}
for (int index =0; index < lista_lista_textos.size(); index++){
lista_lista_textos.set(index, WordUtils.capitalizeFully(lista_textos[index].toLowerCase().replace(".txt", "")));
}
Collections.sort(lista_lista_textos, new AlphanumComparator());
ArrayAdapter<String> adaptador_textos = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, lista_lista_textos);
adaptador_textos.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
sp_titulos_textos.setAdapter(adaptador_textos);
sp_titulos_textos.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String nombre_texto = parent.getSelectedItem().toString();
File sdcard = new File( Environment.getExternalStorageDirectory().toString()+"/Textos/" + "Naxos/");
//Get the text file
File file = new File(sdcard, nombre_texto);
//Read text from file
StringBuilder text = new StringBuilder();
int BUFFER_SIZE = 8192;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "Cp1252"),BUFFER_SIZE);
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
//You'll need to add proper error handling here
}
String nuevoTexto = text.toString().replaceAll("\t", " ");
String nuevoTextoA = nuevoTexto.replaceAll("\n", " ");
Holmes1 = nuevoTextoA;
delimitadores = " ";
tokenHolmes1 = new StringTokenizer(Holmes1, " ");
arrayHolmes1 = Holmes1.split(delimitadores);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
And the xml for the spinners:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="100"
style="#style/spinner_rojo">
<Spinner
android:id="#+id/spinner_titulo_carpetas"
android:layout_width="0dp"
style="#style/spinner_rojo"
android:background="#drawable/spinner_background_holo_light"
android:layout_height="wrap_content"
android:layout_weight="50"></Spinner>
<Spinner
android:id="#+id/spinner_textos_carpetas"
android:layout_width="0dp"
style="#style/spinner_rojo"
android:background="#drawable/spinner_background_holo_light"
android:layout_height="wrap_content"
android:layout_weight="50"></Spinner>
</LinearLayout>
And an image:
Anyone know any possible sulucion to show the drop down list?
I just copied your code and edit ArrayList. It totally worked for me.
private void mostrar_alertdialog_spinners() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
TextView title = new TextView(this);
title.setText("Selecciona un archivo:");
title.setPadding(10, 10, 10, 10);
title.setGravity(Gravity.CENTER);
title.setTextColor(Color.rgb(0, 153, 204));
title.setTextSize(23);
builder.setCustomTitle(title);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout_spinners = inflater.inflate(R.layout.spinner_layout,null);
Spinner sp_titulos_carpetas = (Spinner) layout_spinners.findViewById(R.id.spinner_titulo_carpetas);
Spinner sp_titulos_textos = (Spinner) layout_spinners.findViewById(R.id.spinner_textos_carpetas);
builder.setView(layout_spinners);
builder.setCancelable(false);
builder.show();
ArrayList<String> lista_k = new ArrayList<String>();
lista_k.add("Path A");
lista_k.add("Path B");
ArrayAdapter<String> carpetas = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, lista_k);
carpetas.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
sp_titulos_carpetas.setAdapter(carpetas);
ArrayList<String> lista_lista_textos = new ArrayList<String>();
lista_lista_textos.add("Path C");
lista_lista_textos.add("Path D");
ArrayAdapter<String> adaptador_textos = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, lista_lista_textos);
adaptador_textos.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
sp_titulos_textos.setAdapter(adaptador_textos);
sp_titulos_textos.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
Move this to the end of the code, so you are doing it after setting everything up:
builder.show();
Create custom alert dialog for same. Try this
Dialog new_dialog = new Dialog(getParent());
// new_dialog.setTitle("Book your appointment");
new_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
new_dialog.setContentView(R.layout.customize_dialog_list_view);
new_dialog.setCancelable(false);
cuc = new CommanUtilityClass();
SharedPreferences sp = getSharedPreferences("provider",0);
String services = sp.getString("services", "");
TextView service = (TextView) new_dialog
.findViewById(R.id.cdlv_service_provider);
TextView hour = (TextView) new_dialog.findViewById(R.id.cdlv_working_hours);
TextView appointment_time = (TextView) new_dialog.findViewById(R.id.cdlv_appoint_time);
TextView appointment_date = (TextView) new_dialog.findViewById(R.id.cdlv_appoint_date);
//String[] ampm = myTiming[which].split(":");
/*String[] range = myTiming[which].split(":");
int startTimeInt = Integer.parseInt(range[0])
* 60 + Integer.parseInt(range[1]);
String finalvalue = "";
if(startTimeInt >= 720){
if(startTimeInt >= 780){
}else{
}
}else{
finalvalue = String.valueOf(range[0] + ":" + range[1] + " AM");
}
for (int i = 0; i < range.length; i++) {
String startTimeString = range[i].split("-")[0];
String endTimeString = range[i].split("-")[1];
Log.d("Minutes", "startTimeString = " + startTimeString);
Log.d("Minutes", "endTimeString = " + endTimeString);
int startTimeInt = Integer.parseInt(startTimeString.split(":")[0])
* 60 + Integer.parseInt(startTimeString.split(":")[1]);
int endTimeInt = Integer.parseInt(endTimeString.split(":")[0]) * 60
+ Integer.parseInt(endTimeString.split(":")[1]);
}*/
appointment_time.setText(Html.fromHtml("<b>Appointment time :</b>" + myTimingToShow[which].split("/")[0]));
appointment_date.setText(Html.fromHtml("<b>Appointment date :</b>" + selected));
service.setText(Html
.fromHtml("<b>Service provider :</b>"
+ cuc.toTheUpperCase(bsp_name)));
hour.setText(Html
.fromHtml("<b>Working hours :</b>"
+ cuc.toTheUpperCase(bsp_availability)));
try {
lv = (ListView) new_dialog
.findViewById(R.id.cdlv_list);
CustomDialogArrayAdapter cdaa = new CustomDialogArrayAdapter(
getApplicationContext(),
m_ArrayList);
lv.setAdapter(cdaa);
} catch (Exception e) {
e.printStackTrace();
}
new_dialog.show();
Here I have just inflated xml layout to alert dialog. Make sure you fetch each spinner with context to dialog. See above code for same.
Hope it helps. Cheers!
Due to memory leak, happening so, When you are opening the one spinner it is able to get the valid context, but second time when you are trying to retrieve the another spinner it's actually getting null as a context and not populating anything. But When you are using both the spinner in Activity out of Alert-Dialog, its' actually getting a valid context always. Thus for that time you are not getting any error and it populates correctly.
So, to avoid memory leak, use getApplicationContext() to retrieve the context for spinner ArrayAdapter
ArrayAdapter<String> carpetas = new ArrayAdapter<String>
(getApplicationContext(),android.R.layout.simple_spinner_item, lista_k);
ArrayAdapter<String> adaptador_textos = new ArrayAdapter<String>
(getApplicationContext(),android.R.layout.simple_spinner_item, lista_lista_textos);
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 this ArrayList:
ArrayList<Double> debtList = datasource.debtList;
ArrayList<Double> feeList = datasource.feeList;
How would I print out these two Lists side by side (formatting doesn't matter) in a TableLayout in a loop? Here is layout:
TableLayout table = (TableLayout) findViewById(R.id.myTableLayout);
Ok, you have two arraylists debtList and feeList, I assume both the arraylist contains equal number of elements, now iterate through this list, Create Table Row add two textViews to table row, and add tablerow to the tableLayout, so you can do following:
ArrayList<Double> debtList = datasource.debtList;
ArrayList<Double> feeList = datasource.feeList;
TableLayout table = (TableLayout) findViewById(R.id.myTableLayout);
for(int i=0;i<debtList.size();i++)
{
TableRow row=new TableRow(this);
double debt = debtList.get(i);
double fee = feeList.get(i);
TextView tvDebt=new TextView(this);
tvDebt.setText(""+debt);
TextView tvFee=new TextView(this);
tvFee.setText(""+fee);
row.addView(tvDebt);
row.addView(tvFee);
table.addView(row);
}
I have found out the solution if the arrayLists is not of equal size.
Here is the logic which i have implemented:
Here is my activity:
public class TestStringActivity extends Activity {
private ArrayList<String> input1 = new ArrayList<String>();
private ArrayList<String> input2 = new ArrayList<String>();
private TableRow row;
private TableLayout inflate;
private TextView txtcol1, txtcol2;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Populating the arrayList
input1.add("1 ");
input1.add("2 ");
input1.add("3 ");
input2.add(" Red");
input2.add(" Blue");
input2.add(" Green");
input2.add(" White");
inflate = (TableLayout) TestStringActivity.this
.findViewById(R.id.mytable);
for (int i = 0, j = 0; i < input1.size() || j < input2.size();) {
row = new TableRow(TestStringActivity.this);
txtcol1 = new TextView(TestStringActivity.this);
if (input1.size() > i) {
if ((input1.get(i) != null)) {
txtcol1.setText(input1.get(i));
i++;
}
} else {
txtcol1.setText("");
}
row.addView(txtcol1);
txtcol2 = new TextView(TestStringActivity.this);
if ((input2.size() > j)) {
if (input2.get(j) != null) {
txtcol2.setText(input2.get(j));
j++;
}
} else {
txtcol2.setText("");
}
this.row.addView(txtcol2);
inflate.addView(row);
}
}
}
Here is my Table Layout main.xml:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mytable"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TableLayout>
Hope this helps if the arrayLists size are not of equal size.
Assuming the number of entries in the ArrayLists are equal to the number of cells in the TableLayout, you can try something like this:
int index = 0;
TableLayout tableLayout = findViewById(R.id.table_layout);
for(int n = 0, s = tableLayout.getChildCount(); n < s; ++n) {
double debt = debtList.get(index);
double fee = feeList.get(index);
TableRow row = (TableRow) tableLayout.getChildAt(n);
TextView cell = (TextView) row.findViewById(R.id.textview_cell);
name.setText("debt = " + debt + ", fee = " + fee);
index++;
}