Populating Table Layout using JSON String - android

I have a JSON String returned by my web service as follows:
{"checkrecord"[{"rollno":"abc2","percentage":40,"attended":12,"missed":34}],"Table1":[]}
The above String represents my dataset. I have converted the String to a JSON Object and I now want to put the data in the String into a TableLayout.
I want the table to be like this when displayed on android app:
rollno percentage attended missed
abc2 40 12 34
This is the code I am using as of now :
//json processing code
public void jsonprocessing(String c)
{
try
{
JSONObject jsonobject = new JSONObject(c);
JSONArray array = jsonobject.getJSONArray("checkrecord");
int max = array.length();
for (int j = 0; j < max; j++)
{
JSONObject obj = array.getJSONObject(j);
JSONArray names = obj.names();
for (int k = 0; k < names.length(); k++)
{
name = names.getString(k);
value= obj.getString(name);
createtableLayout();
}
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//create table layout
public void createtableLayout()
{
Log.d("values",value); //I am able to see the values abc2,40,12 and 34 over here in logcat
TableLayout t= (TableLayout)findViewById(R.id.tablelayout);
TableRow r1=new TableRow(this);
r1.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
TextView t1 = new TextView(this);
t1.setText(value);
t1.setTextColor(Color.BLACK);
t1.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
r1.addView(t1);
t.addView(r1, new TableLayout.LayoutParams( LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
}
My TableLayout contains a button and a EditText as the first TableRow. After I click the button I get the JSON String. So I need to insert 2 TableRows dynamically after that as per my requirement.
My xml as of now is as follows:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tablelayout"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:background="#000044">
<TableRow>
<EditText
android:id="#+id/edittext"
android:width="200px" />
<Button
android:id="#+id/button"
android:text="Check Record"/>
</TableRow>
</TableLayout>
So my problem is how to add those 2 extra TableRows so as to populate them with the String values ?
My code isn't working fine. I am not able to get the required output.
Can anyone help me in this?
Thanks

you can use multicolumn listview for your purpose,
Parse the JSON response and get values into different strings and use this blog for your purpose
Multicolumn Listview

You, probably, can define those 2 more rows in your XML and make them initially invisible. Then upon receiving your data put your data in those rows and make them visible.

// Every UI object must have a layout parameter
int widthContent = RelativeLayout.LayoutParams.WRAP_CONTENT;
int heightContent = RelativeLayout.LayoutParams.WRAP_CONTENT;
// Create relative layout
RelativeLayout.LayoutParams rlParamsName = new RelativeLayout.LayoutParams(widthContent,heightContent);
// Create table row layout
int trWidthContent = TableRow.LayoutParams.WRAP_CONTENT;
int trHeightContent = TableRow.LayoutParams.WRAP_CONTENT;
TableRow.LayoutParams trLayout = new TableRow.LayoutParams(trWidthContent, trHeightContent);
// Create a linear layout to add new object as vertical
LinearLayout objLinearLayout = new LinearLayout(context);
objLinearLayout.setOrientation(LinearLayout.VERTICAL);
// Add number of categories to menu
for (int i = 0; i < SpecialCategories.length(); i++) {
try {
// Json for special categories
JSONObject jsonData = SpecialCategories.getJSONObject(i);
// Get name and count of category
String specialCategoryNames = jsonData.getString("label").toString();
String specialCategoryCount = jsonData.getString("coupon_count").toString();
final TableRow tr = new TableRow(this);
tr.setLayoutParams(trLayout);
tr.setId(i);
//tr.setBackgroundColor(0xFFBEBEBE);
// What is the text view for category name
TextView categoryName = new TextView(this);
categoryName.setPadding(8, 8, 8, 8);
categoryName.setTextSize(18);
categoryName.setLayoutParams(trLayout);
categoryName.setText(specialCategoryNames);
categoryName.setId(i);
categoryName.setTypeface(null, Typeface.BOLD);
categoryName.setTextColor(0xFF000000);
// What is count for category
TextView categoryCount = new TextView(this);
categoryCount.setPadding(7, 8, 8, 8);
categoryCount.setLayoutParams(trLayout);
categoryCount.setBackgroundColor(Color.WHITE);
categoryCount.setText("("+specialCategoryCount+")");
// Add disclosure image to row
ImageView objDrawLineImageView = new ImageView(this);
objDrawLineImageView.setPadding(280, 19, 6, 6);
objDrawLineImageView.setImageResource(R.drawable.disclosure);
objDrawLineImageView.setLayoutParams(trLayout);
// Add name of category
tr.addView(categoryName);
// Add count for category
tr.addView(categoryCount);
// Add disclosure back to table row
tr.addView(objDrawLineImageView);
// Add table row into linear layout
objLinearLayout.addView(tr);
//Add Row End Line to Linear layout
ImageView rowEndLine = new ImageView(context);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,2);
params.setMargins(0, 5, 0, 0);
rowEndLine.setLayoutParams(params);
rowEndLine.setBackgroundColor(0xFFBEBEBE);
// Add end line image to linear layout
objLinearLayout.addView(rowEndLine);
// What happen when user click on table row
tr.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(Main.this, ""+tr.getId(),Toast.LENGTH_SHORT).show();
Log.e("TAG", " clicked ID: "+tr.getId());
}
});
} catch (Exception e) {
e.printStackTrace();
}// end try
}// end for SpecialCategories.length()
//Add button number two to the activity.
RelativeLayout objRelativeLayout = (RelativeLayout)findViewById(R.id.row_special);
objRelativeLayout.addView(objLinearLayout);

Related

Android Studio - removing table row programmatically

I have created a table dynamically from an array list
for (int i = 0; i < arrayList.size(); i++) {
TextView name = new TextView(this);
TextView time = new TextView(this);
TableRow row = new TableRow(this);
// Set event name and remaining time
name.setText(arrayList.get(i).name);
time.setText("...");
// Add text views to row
row.addView(time, layoutParams);
row.addView(name, layoutParams);
// Add row to table
tableLayout.addView(row, i);
}
Now if I want to edit or remove certain rows under a condition, I will have to access that row, but how?
outerloop:
for(int i = 0; i < arrayList.size(); i++ ) {
if(// row's time <= 0 ...) {
tableLayout.removeViewAt(i); // this doesn't seem to work properly
// it removes the wrong rows
}
else {
// ...
break outerloop;
}
}
For some reason tableLayout.removeViewAt(i); removes the incorrect row. Alternatively, I'd prefer to edit that row's name, but the principle applies, I just need to find a way to access the table row. Any way?
Create your table like this:
ArrayList<TableRow> rows = new ArrayList<>();
for (int i = 0; i < arrayList.size(); i++) {
TextView name = new TextView(this);
TextView time = new TextView(this);
TableRow row = new TableRow(this);
rows.add(row);
// Set event name and remaining time
name.setText(arrayList.get(i).name);
time.setText("...");
// Add text views to row
row.addView(time, layoutParams);
row.addView(name, layoutParams);
// Add row to table
tableLayout.addView(row, i);
}
When you want to remove a row now you can do that by it's index in the ArrayList:
row = rows.get(i);
table.removeView(row);
rows.remove(i);
When you want to remove multiple rows this could be a solution for you:
ArrayList<TableRow> removeRows = new ArrayList<>();
for(int i = 0; i < rows.size(); i++) {
if(....) {
removeRows.add(rows.get(i));
}
}
// now delete those rows
for(TableRow remove : removeRows) {
tableLayout.removeView(row);
rows.remove(remove);
}
I hope this works for you!

How to add dynamic layout in existing layout ( Android, JSON )

I have an app in which I am showing data from JSON. I am displaying data in a dynamic textview on the right and left side of the relative layout. Now I want to add this layout in an existing layout so that I can apply an OnClickListener on the textview. Right now I am getting data into a string and then setting that string into static textviews in the left and right side of the layout.
How would it be possible to generate textview dynamically on the basis of number of data I am getting from JSON ?
for (Region object : temp.phonelist.regionList)
{
if (object.getCCInfoShortDesc() != null || !(object.getCCInfoShortDesc().equals(null)))
{
Log.i("nullexception", "nullexception");
holder.tvDescription.setText(object.getCCInfoShortDesc());
holder.tvDescription.setVisibility(View.VISIBLE);
}else {
Log.i("nullexception1", "nullexception1");
holder.tvDescription.setVisibility(View.GONE);
}
leftContent += object.getCCInfoLeft() + ":" + "\n";
rightContent += object.getCCInfoRight() + "\n";
}
Log.i("lefftcontent", leftContent);
Log.i("rightcontent", rightContent);
if (leftContent != null) {
holder.tvData2.setText(leftContent);
holder.tvData2.setVisibility(View.VISIBLE);
}
if (rightContent != null) {
holder.tvData1.setText(rightContent);
holder.tvData1.setVisibility(View.VISIBLE);
}
You can do it in this way..
final int Count = < Number of TextViews>; // total number of textviews to add
final TextView[] TextViewsARR = new TextView[N]; // create an empty array;
for (int i = 0; i < Count; i++) {
// create a new textview
final TextView rowTextView = new TextView(this);
// set some properties of rowTextView or something
rowTextView.setText("This is row #" + i);
// add the textview to the linearlayout
myLinearLayout.addView(rowTextView);
// save a reference to the textview for later
TextViewsARR [i] = rowTextView;
}
I have a sample below that generates a checkbox dynamically, If you
observe i am generating the checkbox based on the cursor count.
You can adapt this saple to your needs
Instead of checkbox use a texview
Give any layout like linear, relative etc and generate views
dynamically
private CheckBox chkBoxMealType[] = null;
mCursor = db.rawQuery("SELECT meal_type_id,meal_type_name FROM meal_type_mas", null);
if(mCursor.moveToFirst()){
do{
if(chkBoxMealTypeCnt==0){
chkBoxMealType=new CheckBox[mCursor.getCount()];
}
//create a general view for checkbox
chkBoxMealType[chkBoxMealTypeCnt]= new CheckBox(getActivity());
//Create params for veg-checkbox
//Reason:: we don't need to worry about the data exist in cuisine_type_mas table
chkBoxMealType[chkBoxMealTypeCnt].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
chkBoxMealType[chkBoxMealTypeCnt].setTextColor(getResources().getColor(R.color.searchGoldLight));
chkBoxMealType[chkBoxMealTypeCnt].setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
chkBoxMealType[chkBoxMealTypeCnt].setTag(mCursor.getString(mCursor.getColumnIndexOrThrow(meal_type_mas.COLUMN_MEAL_TYPE_ID)));
chkBoxMealType[chkBoxMealTypeCnt].setText(WordUtils.capitalizeFully(mCursor.getString(mCursor.getColumnIndexOrThrow(meal_type_mas.COLUMN_MEAL_TYPE_NAME))));
mealTypeContainer.addView(chkBoxMealType[chkBoxMealTypeCnt]);
//since cursor count starts from 0 last count must be allowed
chkBoxMealTypeCnt++;
}while(mCursor.moveToNext());
Log.d("", "");
}
I have another sample..... Download this project(Click Here) and run in your editor
Snapshot::
Firstly you need to add a View in your layout ... Like you may try using LinearLayout or HorizontalLayout ... and then attach/add your dynamic textview to that layout.
Pragmatically you may try like this
packageButtons = new ArrayList<TextView>(); // Create your textview arraylist like this
for(int a = 0; a < your_text_view_from_json.size(); a++){
final TextView rowTextView;
rowTextView = new TextView(getApplicationContext());
rowTextView.setText(taxi_type_spin.get(a).taxi_type);
rowTextView.setTextSize(15);
rowTextView.setTextColor(getResources().getColor(R.color.white));
LinearLayout.LayoutParams lparam = new LinearLayout.LayoutParams(0,
LinearLayout.LayoutParams.WRAP_CONTENT, 1);
//rowTextView.setPadding(0, 0, 0, 0);
packageButtons.add(rowTextView);
rowTextView.setLayoutParams(lparam);
rowTextView.setId(a);
final int b = a;
// get value of clicked item over here ..
rowTextView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Button btn = (Button)v;
String get_value = btn.getText().toString();
//Toast.makeText(getApplicationContext(), "Button name is : " + get_value + " AND ID IS : " + rowTextView.getId(), Toast.LENGTH_LONG).show();
if(taxi_type_spin.get(b).taxi_type.equalsIgnoreCase(Utils.Hourly_Package))
{
setTaxiType(rowTextView.getId(),true);
ll_spin.setVisibility(View.VISIBLE);
}
else
{
setTaxiType(rowTextView.getId(),false);
ll_spin.setVisibility(View.GONE);
}
setSelectedButtonColor(b);
}
});
// add the textview to the linearlayout
myLinearLayout.addView(rowTextView);
NOTE rowTextView .. this is your default view attached to your XML file
Hope it helps!
private void setLayout(LinearLayout llayout,
final ArrayList<String> items) {
for (int i = 0; i < items.size(); i++) {
LinearLayout row = null;
LayoutInflater li = getLayoutInflater();
row = (LinearLayout) li.inflate(R.layout.custom_item,
null);
ImageView image = (ImageView) row.findViewById(R.id.image);
llayout.addView(row);
}
}
I would suggest you to use ArrayList, because the class java.util.ArrayList provides resizable-array, which means that items can be added and removed from the list dynamically.
and get value from ArrayList something like this:
for(int i=0; i<arrayList.size(); i++)
{
textName.setText(object.getName());
}
How it is possible to genrate textview dynamically
on the basis of number of data i am getting from json.
You need to create TextView and add it to the parent layout each time you iterate on the forloop. So you will have textView for each of the element of the temp.phonelist.regionList
sample:
for (Region object : temp.phonelist.regionList)
{
TextView tx = new TextView(context); //creating a new instance if textview
//yourstuff goes here
tx.setText(text_you_want);
yourView.addView(tx); //this is to add the textView on each iteration
}
here is your solution do this way,Take one Layout(Linear or Relative) and add control dynamically....
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
for (int i = 0; i < 4; i++)
{
TextView txtDemo = new TextView(getActivity());
txtDemo .setTextSize(16);
txtDemo .setLayoutParams(lp);
txtDemo .setId(i);
lp.setMargins(0, 10, 0, 0);
txtDemo .setPadding(20, 10, 10, 10);
txtDemo .setText("Text View"+ i);
linearlayout.addView(txtDemo );
}
}

How to add a row dynamically in a tableLayout in Android

I have a function who gets a list of products from a webpage, and I want to add a row in a tableLayout for each element of the list.
public void getProductsOfCategory() throws IOException{
new Thread(){
public void run(){
//background code...
try {
Bundle extras = getIntent().getExtras();
String categoryName = extras.getString("categoryName");
HttpGet httpget = new HttpGet("http://romal.hopto.org/foodadvisor/users/getProductsOfCategory.json?category="+categoryName);
HttpResponse httpresp = httpClient.execute(httpget);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
httpresp.getEntity().writeTo(baos);
final String content = new String(baos.toByteArray());
CategoryActivity.this.runOnUiThread(new Runnable(){
public void run(){
//foreground code (UI)
//update user interface, for example, showing messages
try {
JSONObject jObject = new JSONObject(content);
JSONArray productsList = jObject.getJSONArray("response");
for(int i=0; i<productsList.length();i++){
JSONObject product = productsList.getJSONObject(i);
JSONObject productData = product.getJSONObject("Product");
String productDescription = productData.getString("description");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
In my layout xml file I have defined the table layout like this:
<TableLayout
android:id="#+id/tableOfProducts"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/productDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:paddingBottom="7dp"
android:paddingLeft="14dp"
android:paddingRight="14dp"
android:paddingTop="7dp"
android:textSize="20dp" />
</TableLayout>
I imagine I have to add some extra code in the for loop, adding a new row and a new textview for each element, and setting the content of the text view with the string that has the description of the product.
How can I do this?
Check this out, this is the general way of creating table rows dynamically. Modify it accordingly
XML file
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_table"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</TableLayout>
JAVA PART
TableLayout t1;
TableLayout tl = (TableLayout) findViewById(R.id.main_table);
Create table row header to hold the column headings
TableRow tr_head = new TableRow(this);
tr_head.setId(10);
tr_head.setBackgroundColor(Color.GRAY); // part1
tr_head.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
I'm adding two data sections to the table row
TextView label_hello = new TextView(this);
label_hello.setId(20);
label_hello.setText("HELLO");
label_hello.setTextColor(Color.WHITE); // part2
label_hello.setPadding(5, 5, 5, 5);
tr_head.addView(label_hello);// add the column to the table row here
TextView label_android = new TextView(this); // part3
label_android.setId(21);// define id that must be unique
label_android.setText("ANDROID..!!"); // set the text for the header
label_android.setTextColor(Color.WHITE); // set the color
label_android.setPadding(5, 5, 5, 5); // set the padding (if required)
tr_head.addView(label_android); // add the column to the table row here
After adding the columns to the table row its time to add the table row the the main table layout that we fetched at the start
tl.addView(tr_head, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT, //part4
LayoutParams.MATCH_CONTENT));
EDIT : YOU CAN DO THE FOLLOWING IN YOUR CODE
TextView[] textArray = new TextView[productsList.length()];
TableRow[] tr_head = new TableRow[productsList.length()];
for(int i=0; i<productsList.length();i++){
JSONObject product = productsList.getJSONObject(i);
JSONObject productData = product.getJSONObject("Product");
String productDescription = productData.getString("description");
//Create the tablerows
tr_head[i] = new TableRow(this);
tr_head[i].setId(i+1);
tr_head[i].setBackgroundColor(Color.GRAY);
tr_head[i].setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
// Here create the TextView dynamically
textArray[i] = new TextView(this);
textArray[i].setId(i+111);
textArray[i].setText(productDescription);
textArray[i].setTextColor(Color.WHITE);
textArray[i].setPadding(5, 5, 5, 5);
tr_head[i].addView(textArray[i]);
// Add each table row to table layout
tl.addView(tr_head[i], new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
} // end of for loop
Creating the TextView and TableRow array are not necessary. You can just include part1, part2, part3 (if you need more than 1 field) and part4 inside your for loop.
Look, i think you have to modify your xml to adding rows to your tableview:
First, the inflater:
LayoutInflater inflater = mContext.getLayoutInflater();
or in this way:
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Here you can set up the layoutparameters from your tableview and the rowview.
//Maybe you don't have to modify nothing from the parameters of your tableview so
//you can dismiss it.
TableLayout.LayoutParams tableParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT);
TableRow.LayoutParams rowParams = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);
//Here were we take the tablelayout from your xml
TableLayout tableLayout = (TableLayout)inflater.inflate(R.layout.tableOfProducts, null);
//Like a told you before, maybe you don't need set the parameters of the tablelayout
//so you can comment next line.
tableLayout.setLayoutParams(this.tableParams);
TableRow tableRow = new TableRow(context);
tableRow.setLayoutParams(this.tableParams);
//Here you have to create and modify the new textview.
TextView textView = new TextView(context);
textView.setLayoutParams(this.rowParams);
tableRow.addView(textView);
tableLayout.addView(tableRow);
If you need more help, tell me, if it is helpful, rating me!!! ;) Un saludo Gallega! O como se dice en gallego: una aperta!
for this, you have to create one xml file for row, then you have to modify your layout.xml file like
<ScrollView>
<LinearLayout orientation=vertical id="+id/rowHolder">
</LinearLayout
</scrollview>
Then in for loop, inflate the row layout and add it runtime to rowHolder object.
I'm new myself to Android, and after years with Python/Gtk, I'm lost if I can't think in terms of Model/View/Presenter.
one useful approach I managed to apply, it puts me back into that optics, and even if it's not relative to a Table, I'm quite sure it can be extended to that (I guess this page would be a good start, for me too).
start by declaring the two objects in your fragment (or activity):
List<String> stringList; // think of it as the model.
ArrayAdapter<String> listAdapter; // and this would be the presenter
define the model in the fragment constructor:
stringList = new ArrayList<>();
next, when the onCreateView of my fragment is invoked, I do this (edit correspondingly if you're using Activity, not Fragment):
View rootView = inflater.inflate(R.layout.fragment_taxonomy, container, false);
ListView mainListView = rootView.findViewById(R.id.taxonomy_results);
// Create ArrayAdapter using the string list. think of it as the presenter.
// see how it's being handled a model and a view.
listAdapter = new ArrayAdapter<>(
rootView.getContext(), R.layout.textrow, stringList);
// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter( listAdapter );
textrow.xml is an extra layout which is being reused every time I add an element to the stringList model.
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rowTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
in the rest of the code, I only "talk" to listAdapter, and I only need its two add and clear methods, to add elements, or for clearing the list.
There are many ways to do this. First, for minimizing your code, create an XML file that initializes the TableRow and its attribute (TextView should be also included). Then, in your target XML file that is linked to the activity, you have to create only the TableLayout.
In the main, create LayoutInflater that will link the items to gather. Then, create as much as you can of the number of TableRow. In the end, each TableRow that has a unique variable should be linked using addView() to the TableLayout that you have created in the XML.
For more, see here. https://github.com/AreejTurky/Dynamic-TableRow-Generation

Unable to pass correct table row's data to next activity

I'm fairly new to Android programming and have completed my first app except for one issue on passing data from a table row that is selected (onClick). I've researched out here and tried most of the recommendations but I'm obviously missing something critical. I am a little confused on the getTag/Id and setTag/Id so maybe that's where I'm going wrong.
A little background, the table can have 1 to N number of rows populated dynamically from database, each row being clickable. Once a row is clicked, I need to pass the unique data of that row to the next activity (using Bundle for that which works fine). What doesn't work is that no matter which row I click, I only get the last row's data passed to the next activity and not the data of the clicked row.
Here's some of my pertinent code for the data add to row/table and onclick... What am I doing wrong to only get the last row's data? Really appreciate anyone's help in pointing me in the right direction.
public void addData(ArrayList<Auctions> auctions) {
prevCity = "";
currCity = "";
prevDate = "";
currDate = "";
prevTime = "";
currTime = "";
prevUnit = "";
currUnit = "";
for (Iterator i = auctions.iterator(); i.hasNext();) {
Auctions p = (Auctions) i.next();
if (p.getCity().equals(prevCity) && p.getDate().equals(prevDate) && p.getTime().equals(prevTime) && p.getSunit().equals(prevUnit)) {
//skip to next unique record
} else {
/** Create a City TableRow dynamically **/
row2 = new TableRow(this);
row2.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
/** Creating a TextView to add to the row **/
tvcity = new TextView(this);
currCity = p.getCity();
if (currCity.toString().equals(prevCity)) {
tvcity.setText("");
} else {
//create a blank row to separate from previous city entries
row1 = new TableRow(this);
row1.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
tvdummy = new TextView(this);
tvdummy.setText("");
tvdummy.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
row1.addView(tvdummy);
auctions_table.addView(row1, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
// work on the new city data
tvcity.setText(p.getCity());
}
tvcity.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
tvcity.setTextColor(getResources().getColor(R.color.red));
//add TextView data to row
row2.addView(tvcity);
// Add the TableRow to the TableLayout
auctions_table.addView(row2, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
// Create date, time, and unit name row dynamically
row3 = new TableRow(this);
row3.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
// Create TextViews to add to the Row -- Date and Time
tvdate = new TextView(this);
tvtime = new TextView(this);
tvsunit = new TextView(this);
currDate = p.getDate();
currTime = p.getTime();
currUnit = p.getSunit();
if ((currDate.toString().equals(prevDate)) && (currTime.toString().equals(prevTime))) {
tvdate.setText("");
tvtime.setText("");
} else {
tvdate.setText(p.getDate());
tvtime.setText(p.getTime());
}
if (currUnit.toString().equals(prevUnit)) {
tvsunit.setText("");
} else {
tvsunit.setText("Dynamic UNIT");
tvsunit.setText(p.getSunit());
}
tvdate.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
tvdate.setTextColor(getResources().getColor(R.color.blue));
tvtime.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
tvtime.setTextColor(getResources().getColor(R.color.blue));
tvsunit.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
tvsunit.setTextColor(getResources().getColor(R.color.blue));
//add TextView data to row
row3.addView(tvdate);
row3.addView(tvtime);
row3.addView(tvsunit);
row3.setId(t);
row3.setFocusable(false);
//row3.setClickable(true);
row3.setOnClickListener(new View.OnClickListener() {
//public OnClickListener tablerowOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
// Get the selected row's data
//row3.getId();
Bundle basket2 = new Bundle();
basket2.putString("ustate", state.getText().toString());
basket2.putString("abbrev", abbrev);
basket2.putString("ucity", currCity);
basket2.putString("uname", currUnit);
basket2.putString("auctiondate", currDate);
basket2.putString("auctiontime", currTime);
Intent StAuctions = new Intent(getApplicationContext(), StorageAuctionDetails.class);
StAuctions.putExtras(basket2);
StAuctions.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(StAuctions);
// Closing screen
//finish();
}
});
row3.setBackgroundResource(drawable.list_selector_background);
// Add the TableRow to the TableLayout
auctions_table.addView(row3, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
}
prevCity = currCity;
prevDate = currDate;
prevTime = currTime;
prevUnit = currUnit;
t++;
}
};
You are going to get these variables based on what they are when onClick is activated:
basket2.putString("ustate", state.getText().toString());
basket2.putString("abbrev", abbrev);
basket2.putString("ucity", currCity);
basket2.putString("uname", currUnit);
basket2.putString("auctiondate", currDate);
basket2.putString("auctiontime", currTime);
Those valued will be for whatever the last time you ran through your iteration.
You need to create a new "basket" for each row entry. Not in the click listener, but in the iteration loop, and make that basket the tag for that row, with something like this:
row3.setTag(basket2);
Can't decrypt your code sufficiently enough. But what I would suggest is that in your onClick(), put in Log.v("Row id is: ", Integer.toString(v.getId())) and see in LogCat if every time you click, it returns the same value.
Also, if I'm writing similar features, I might want to perform the extraction of row information in the onClick(), so information gets extracted from row and put into bundle on the fly, rather than passing the values into bundle during the iterator. Something like:
public void onClick(View v) {
String a; //extras for bundle
Bundle basket2 = new Bundle();
//iterate row's children and assign values to string here
for(int i = 0; i < v.getChildSize(); i++){
TextView t = (TextView)v.getChildAt(i);
//assignment
basket2.putString("someKey", a);
}
//send your intent
}

Android Table Layout with 5x5 dimension

I'm still new in android programming, what I'm trying to do is, I want to create 5x5 dimension TableLayout. I know this can be done by using GridView BaseAdapter suing Inflate service. But for this one i try to apply using table layout. Below is the code. I create new instance of TableLayout, and new instance of Table row. On each table row, I created instance of 5 TextView. But once I open in emulator or in my phone, there is no TableRow created, it just empty blank Table Layout. Also there is no exception was thrown.
GridView navIcon = (GridView) findViewById(R.id.content);
navIcon.setAdapter(new ImageAdapter(this));
navIcon.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View v, int position,long id) {
// TODO Auto-generated method stub
if (position==0){
try{
TableLayout calgrid = (TableLayout) findViewById(R.id.gridtable);
Context ctxt = v.getContext();
TextView[] tView = new TextView[25];
calgrid = new TableLayout(ctxt);
int dip = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,(float) 1, getResources().getDisplayMetrics());
int counter=1;
TableRow[] tr = new TableRow[5];
for(int j=0;j<5;j++){
tr[j] = new TableRow(ctxt);
for(int i=0;i<5;i++){
tView[i] = new TextView(ctxt);
tView[i].setText(String.valueOf(counter));
tView[i].setTextSize(15);
counter+=1;
tView[i].setWidth(50 * dip);
tView[i].setPadding(20*dip, 0, 0, 0);
tView[i].setTextColor(Color.rgb( 100, 200, 200));
Toast.makeText(getApplicationContext(), "tView["+i+"] value " + String.valueOf(tView[i].getText()), Toast.LENGTH_SHORT).show();
tr[j].addView(tView[i], 50, 50);
}
calgrid.addView(tr[j]);
}
}catch(Exception e){
Log.e("MainActivity", "Error in activity", e);
Toast.makeText(getApplicationContext(),e.getClass().getName() + " " + e.getMessage(),Toast.LENGTH_LONG).show();
}
}
}
});
First of all, it is a mistake to do calgrid = (TableLayout) findViewById(R.id.gridtable); and then calgrid = new TableLayout(ctxt);, which basically says find this view now assign this variable to something completely different. Remove the second statement and it will load the table from xml which is what you want.
Second, I think it would be a good idea to simplify things for yourself because there is a lot going on here. Instead of doing all this work inside an onClick listener, do it in the onCreate method itself. Also, you seem to be using the Context from the GridView, which seems odd. Perhaps if you posted your xml layout file it could help explain what you are trying to do?
There is also a problem with indices in the array of TextViews, as tView[i] will only assign items up to 5 but the array contains 25 items. Try using tView[(j*5)+i] instead. I don't think this is causing your problems but just make sure you are assigning your items correctly.
Here is an example of how to do something along the lines of what you want
setContentView(R.layout.grid);
TableLayout tl = (TableLayout) findViewById(R.id.gridtable);
for (int j = 0; j < 5; j++) {
TableRow tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
for (int i = 0; i < 5; i++) {
TextView tView = new TextView(this);
tView.setText("TEXT" + String.valueOf((j * 5) + i + 1));
tView.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tr.addView(tView);
}
tl.addView(tr, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
}
and grid.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridtable"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</TableLayout>
Once you get it working in the activity itself you can try to put it inside a listener attached to a GridView. Hope this helps!

Categories

Resources