Android- Adding items dynamically to scrollview - java

I have been for hours trying to follow various tutorials in order to add items dynamically into a scrollview but nothing seems to be working...
The idea is just to add Strings into a TextView next to a Checkbox, which were done in a separate xml file and I just wanted the list to grow as I keep adding them.
For now, only one String is being added (the last one substitutes the previous one), and in any attempt to try to change that, my app stops working.
Here is the code as it stands:
TableLayout addPlayersTableLayout;
TableRow tableRow1;
ScrollView addPlayersScrollView;
String[] players = new String[]{ "Blah", "Whatever", "Test", "Nipah!"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPlayersTableLayout = (TableLayout)findViewById(R.id.TableLayout1);
tableRow1 =(TableRow)findViewById(R.id.tableRow1);
addPlayersScrollView = (ScrollView)findViewById(R.id.playersScrollView);
insertPlayerInScrollView();
}
Here is the implementation of the function that is supposed to add the items:
(add_player_row.xml is the file where the textview and checkbox that are supposed to be the items were made)
private void insertPlayerInScrollView() {
LayoutInflater inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View newPlayerRow = inflator.inflate(R.layout.add_player_row, null);
TextView newPlayerTextView = (TextView) newPlayerRow.findViewById(R.id.addPlayerTextView);
CheckBox playerCheckBox = (CheckBox)findViewById(R.id.playerCheckBox);
newPlayerTextView.setText(players[1]);
addPlayersTableLayout.addView(newPlayerRow,0);
}
The final line of code is the only way it works at all, even though on most forums and tutorials, people would indicate for me to use the addPlayersScrollView, but if I do so, the app crashes.
So... Any ideas?
Thank you very much!

I'm facing something similar than you. I have a layout like this:
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableLayout
android:id="#+id/tableLayoutList"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
And have my row defined like this (mRowLayout.xml):
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayoutRow"
android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:id="#+id/checkBoxServEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
And then I use the following code to inflate my row:
private void fillTable(View v, Cursor c) {
TableLayout ll = (TableLayout) v.findViewById(R.id.tableLayoutList);
View mTableRow = null;
int i = 0;
while(!c.isAfterLast()){
i++;
mTableRow = (TableRow) View.inflate(getActivity(), R.layout.mRowLayout, null);
CheckBox cb = (CheckBox)mTableRow.findViewById(R.id.checkBoxServEmail);
cb.setText( c.getString(c.getColumnIndex(Empleado.EMAIL)));
mTableRow.setTag(i);
//add TableRows to TableLayout
ll.addView(mTableRow);
c.moveToNext();
}
}
What I'm trying to do here is inflate my rows dynamically. The cursor have the items that I wanna show from data base. I'm not sure if this can solve your problem. Let me know.

Related

Android textView.setText() throws exception

I'm trying to create an app where I can put several times the same kind of layout in a LinearLayout.
The layout just has a TextView and i'm trying to use setText but this line of code doesn't seems to work.
I don't know how many layout I must add to the LinearLayout because it depends of how many drones (I have one layout/drone) the user will have upload to the app, so I made a function that read the text to put in the TextView from a SharedPreference and that also read the number of drones (so the number of layouts) in another SharedPreferences.
The TextView i'im putting the string in is from a layout named dronelayoutmain.
I tried sending just "test" in the setText, but it crashes anyway, so I think that android just can't find my TextView, but I don't really know why.
So here is the function I call in OnCreate that is supposed to add one layout for each drone I have
public void affichagedrone(){
LinearLayout mlineairelayout = (LinearLayout)
findViewById(R.id.lineaireLayout);
LinearLayout.LayoutParams params = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
Context mContext;
mContext = getApplicationContext();
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
SharedPreferences droneprefs = mContext.getSharedPreferences("dronepref", MODE_PRIVATE);
SharedPreferences applimaindata = mContext.getSharedPreferences("applimaindata", MODE_PRIVATE);
int nbdrone = applimaindata.getInt(String.valueOf(emplacementNbDrone),1);
String string;
TextView textViewnomConstructeurDrone;
if (nbdrone !=0) {
for(int i=0;i<nbdrone;i++) {
textViewnomConstructeurDrone = (TextView) findViewById(R.id.textViewNomConstructeur);
string = droneprefs.getString(String.valueOf(i),"Fail");
textViewnomConstructeurDrone.setText(string);
final View rowView = inflater.inflate(R.layout.dronelayoutmain, null);
// Add the new row before the add field button.
mlineairelayout.addView(rowView);
}
}
}
And here is the layout i'm trying to put in the LinearLayout.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="120dp"
>
<TextView
android:id="#+id/textViewNomConstructeur"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:text="#string/adddrone"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
The function is supposed to check in applimaindata the number of layout to add, and then, in the for(), is supposed to set the Text of the TextView from the droneprefs file and then add the Layout to the main LinearLayout
If this TextView belongs in the newly inflated layout, you must find it after the layout is inflated:
for(int i = 0; i < nbdrone; i++) {
final View rowView = inflater.inflate(R.layout.dronelayoutmain, null);
textViewnomConstructeurDrone = rowView.findViewById(R.id.textViewNomConstructeur);
string = droneprefs.getString(String.valueOf(i),"Fail");
textViewnomConstructeurDrone.setText(string);
mlineairelayout.addView(rowView);
}

How to add Strings to a TextView / ScrollView?

I am quiet new to android developing sorry!
I want to add doctor values as Strings (first name, last name, and some others later) as one entry (I was trying to do so with Objects) to my Scroll View via a button. I know that I need a Layout and a Text View to do so but my Virtual Machine crushes.
As far as I understand I have to put my Text View (with the Strings) in the Layout and the Layout in the Scroll View (am I wrong?).
I was trying several things from different websites which all provide similar solutions but nothing worked so far. I am using Android 6.0 with android studio and designed my UI with the Design View and adapted some code in the XML files.
public void addDoctor(View view) {
setContentView(R.layout.activity_main);
// standard java class Doctor
Doctor doc = new Doctor("Foo", "Boo");
// this is the ScrollView I generated with the design
ScrollView sv = (ScrollView) this.findViewById(R.id.ScrollViewDoctor);
TextView tv = new TextView(this);
// trying to fix the parent problem here
if(tv.getParent() != null) {
((ViewGroup)tv.getParent()).removeView(tv); // <- fix
}
//this should be "Foo"
tv.setText(doc.getDocName());
// this is the layout I generated with the design "linlay"
LinearLayout ll = (LinearLayout) this.findViewById(R.id.linlay);
sv.addView(ll);
//only one child object! -> in the error log
ll.addView(tv);
setContentView(view);
}
I expected the Strings of the object to appear in the Scroll View but the error log says that "ScrollView can host only one direct child" which I was trying to fix with the if statement but it does not seem to affect my code.
Can you please help me with this. Do I miss something?
Thank you!
As far as I understand I have to put my Text View (with the Strings) in the Layout and the Layout in the Scroll View (am I wrong?).
You've right.
<ScrollView>
<LinearLayout>
<TextView></TextView>
</LinearLayout>
</ScrollView>
How to Add a doctor in the right way
error log says that "ScrollView can host only one direct child"
You're getting the error because you added already the linear layout inside the <ScrollView>, so you don't have to call, sv.addView(ll); because it's already inside (And you cannot add multiple layout in standard ScrollView)
So you're reference to ScrollView it's useless.
if you're xml is like this:
<ScrollView>
<LinearLayout>
</LinearLayout>
</ScrollView>
You can achieve your result with this:
public class MyActivityDoctors extends Activity {
ScrollView sv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sv = (ScrollView) this.findViewById(R.id.ScrollViewDoctor);
}
public void addDoctor(Doctor doctor)
{
//Linear Layout inside your ScrollView
LinearLayout ll = (LinearLayout) this.findViewById(R.id.linlay);
//Create a new TextView with doctor data
TextView tv = new TextView(this);
tv.setText(doctor.getDocName());
//Adding textView to LinearLayout
ll.addView(tv);
}
}
remove setContentView(view); on the end, you have already set this layout in first line
setContentView in most cases should be called once, inside onCreate method. if you are calling setContentView multiple times you are basically overrriding previous one
also this
if(tv.getParent() != null) {
((ViewGroup)tv.getParent()).removeView(tv); // <- fix
}
is unnecessary, you are creating new TextView line above, it wont have parent for shure
Why don't you use a RecyclerView? And then you don't need a ScrollView. And don't call setContentView(view); multiples times. You have to do only 1 time.
you need to create Multiline TextView
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="20dp"
android:fillViewport="true">
<TextView
android:id="#+id/txtquestion"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#drawable/abs__dialog_full_holo_light"
android:lines="20"
android:scrollHorizontally="false"
android:scrollbars="vertical"
android:textSize="15sp" />
</ScrollView>

How can I make a dynamically generated tablelayout scrollable?

I have 3 fragments inside an Activity and in two of the fragments I have a hardcoded TableLayout inside a ConstraintLayout, the headers and rows of the tables are dynamically generated with information from a MySQL server. Given its dynamic nature, the table is able to overflow the page and I want it to be scrollable.
There are already multiple questions on StackOverflow where people have wanted a scrollable table, but in the questions, the tables and their data are hardcoded (don't know if that is relevant or not). I have tried the solutions proposed in those questions but they don't work on my table. The solutions are generally to either wrap the TableLayout in a ScrollView or to use android:isScrollContainer="1" neither of which have worked for me.
TableLayout inside ScrollView. The ScrollView is there for testing, normally it is just the TableLayout.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ViewProductLocFragment">
<!-- Rest of the fragment -->
<ScrollView
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="16dp"
android:layout_weight="1"
android:scrollbars="none"
app:layout_constraintBottom_toTopOf="#+id/menuBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/view">
<TableLayout
android:id="#+id/tableLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="5dp"
android:layout_marginBottom="5dp"
android:stretchColumns="*"
app:layout_constraintBottom_toTopOf="#+id/menuBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/view">
</TableLayout>
</ScrollView>
</android.support.constraint.ConstraintLayout>
Here is the code that fills the table.
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_view_product_main, container, false);
initializeTableLayout(view);
fillTable(((ViewProductActivity)getActivity()).pallets);
return view;
}
private void fillTable(PalletsResult pallets)
{
Integer count = 0;
for(Pallet pallet : pallets.getPallets()) {
String barcode = pallet.getBarcode();
String location = pallet.getCode();
Integer quantity = pallet.getQuantity();
TableRow tableRow = new TableRow(getContext());
if (count % 2 != 0) {
tableRow.setBackgroundColor(getResources().getColor(R.color.lightGrey));
}
tableRow.setId(View.generateViewId());
tableRow.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
TextView labelBarcode = new TextView(getContext());
labelBarcode.setId(View.generateViewId());
labelBarcode.setGravity(Gravity.CENTER);
labelBarcode.setTextColor(getResources().getColor(R.color.standardTextColor));
labelBarcode.setTextSize(18);
labelBarcode.setText(barcode);
tableRow.addView(labelBarcode);
TextView labelLocation = new TextView(getContext());
labelLocation.setId(View.generateViewId());
labelLocation.setGravity(Gravity.CENTER);
labelLocation.setTextColor(getResources().getColor(R.color.standardTextColor));
labelLocation.setTextSize(18);
labelLocation.setText(location);
tableRow.addView(labelLocation);
TextView labelQuantity = new TextView(getContext());
labelQuantity.setId(View.generateViewId());
labelQuantity.setGravity(Gravity.CENTER);
labelQuantity.setTextColor(getResources().getColor(R.color.standardTextColor));
labelQuantity.setTextSize(18);
labelQuantity.setText(quantity.toString());
tableRow.addView(labelQuantity);
tableLayout.addView(tableRow, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
count++;
}
}
private void initializeTableLayout(View view)
{
tableLayout = view.findViewById(R.id.tableLayout);
TableRow tr_head = new TableRow(getContext());
tr_head.setId(View.generateViewId());
tr_head.setBackgroundColor(getResources().getColor(R.color.lightGrey));
tr_head.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT
));
TextView label_barcode = new TextView(getContext());
label_barcode.setId(View.generateViewId());
label_barcode.setText("BARCODE");
label_barcode.setTextSize(20);
label_barcode.setTextColor(Color.BLACK);
label_barcode.setGravity(Gravity.CENTER);
tr_head.addView(label_barcode);// add the column to the table row here
TextView label_location = new TextView(getContext());
label_location.setId(View.generateViewId());// define id that must be
unique
label_location.setText("LOCATION"); // set the text for the header
label_location.setTextSize(20);
label_location.setTextColor(Color.BLACK); // set the color
label_location.setGravity(Gravity.CENTER);
tr_head.addView(label_location); // add the column to the table row here
TextView label_quantity = new TextView(getContext());
label_quantity.setId(View.generateViewId());// define id that must be
unique
label_quantity.setText("QTY"); // set the text for the header
label_quantity.setTextSize(20);
label_quantity.setTextColor(Color.BLACK); // set the color
label_quantity.setGravity(Gravity.CENTER);
tr_head.addView(label_quantity); // add the column to the table row here
tableLayout.setScrollContainer(true);
tableLayout.addView(tr_head, new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
}
This creates a table that runs off the end of the page and that can't be scrolled.
There is a fair bit of other code that I didn't post in regards to the Activity containing the fragments and what not. Let me know if you want any of that.
Thanks for any help.
Update: I implemented a similar table elsewhere in my app and it worked just fine with the code posted in my examples. This means that the problem I am having is realted to the table being in a fragment and not an activity. I will post some of my fragment code later.
I have tried implementing your code over an Activity. I am posting my Activity and XML code for your reference, can you see what you are missing in your complete code so that this can be helpful.
MainActivity.java
public class MainActivity extends Activity {
TableLayout tableLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeTableLayout();
}
#Override
protected void onResume() {
super.onResume();
fillTable();
}
private void fillTable() {
Integer count = 0;
for (int i = 0; i < 100; i++) {
String barcode = "#0000000000";
String location = "Location";
Integer quantity = 1;
TableRow tableRow = new TableRow(MainActivity.this);
if (count % 2 != 0) {
tableRow.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));
}
tableRow.setId(View.generateViewId());
tableRow.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
TextView labelBarcode = new TextView(MainActivity.this);
labelBarcode.setId(View.generateViewId());
labelBarcode.setGravity(Gravity.CENTER);
labelBarcode.setTextColor(getResources().getColor(R.color.colorAccent));
labelBarcode.setTextSize(18);
labelBarcode.setText(barcode);
tableRow.addView(labelBarcode);
TextView labelLocation = new TextView(MainActivity.this);
labelLocation.setId(View.generateViewId());
labelLocation.setGravity(Gravity.CENTER);
labelLocation.setTextColor(getResources().getColor(R.color.colorAccent));
labelLocation.setTextSize(18);
labelLocation.setText(location);
tableRow.addView(labelLocation);
TextView labelQuantity = new TextView(MainActivity.this);
labelQuantity.setId(View.generateViewId());
labelQuantity.setGravity(Gravity.CENTER);
labelQuantity.setTextColor(getResources().getColor(R.color.colorAccent));
labelQuantity.setTextSize(18);
labelQuantity.setText(quantity.toString());
tableRow.addView(labelQuantity);
tableLayout.addView(tableRow, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
count++;
}
}
private void initializeTableLayout() {
tableLayout = this.findViewById(R.id.tableLayout);
TableRow tr_head = new TableRow(MainActivity.this);
tr_head.setId(View.generateViewId());
tr_head.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));
tr_head.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
TextView label_barcode = new TextView(MainActivity.this);
label_barcode.setId(View.generateViewId());
label_barcode.setText("BARCODE");
label_barcode.setTextSize(20);
label_barcode.setTextColor(Color.BLACK);
label_barcode.setGravity(Gravity.CENTER);
tr_head.addView(label_barcode);// add the column to the table row here
TextView label_location = new TextView(MainActivity.this);
label_location.setId(View.generateViewId());// define id that must be unique
label_location.setText("LOCATION"); // set the text for the header
label_location.setTextSize(20);
label_location.setTextColor(Color.BLACK); // set the color
label_location.setGravity(Gravity.CENTER);
tr_head.addView(label_location); // add the column to the table row here
TextView label_quantity = new TextView(MainActivity.this);
label_quantity.setId(View.generateViewId());// define id that must be unique
label_quantity.setText("QTY"); // set the text for the header
label_quantity.setTextSize(20);
label_quantity.setTextColor(Color.BLACK); // set the color
label_quantity.setGravity(Gravity.CENTER);
tr_head.addView(label_quantity); // add the column to the table row here
tableLayout.setScrollContainer(true);
tableLayout.addView(tr_head, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="16dp"
android:layout_weight="1"
android:scrollbars="none">
<TableLayout
android:id="#+id/tableLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="5dp"
android:layout_marginBottom="5dp"
android:stretchColumns="*"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"></TableLayout>
</ScrollView>
</android.support.constraint.ConstraintLayout>
I have manually added 100 dummy rows to test its scroll behaviour and would like to inform you that it is exactly working as it should. There could be a problem in your Activity or Fragment parent code which is preventing the table from scrolling.
You can use TableView library to make your Table scrollable with dynamic data. The link is given below:-
https://github.com/evrencoskun/TableView

Inflate TextViews to LinearLayout

I want to inflate TextViews to LinearLayout.
I have a layout activity_play_game and java class PlayGameActivity.
Currently, for hardcoded number of TextViews it looks like this:
Now I tried to add number of TextViews according to the value of variable numberForbiddenWords. I added a piece of code that looks like this:
LinearLayout playGame = (LinearLayout) findViewById(R.id.activity_play_game);
TextView temp;
TextView[] textViews = new TextView[numberForbiddenWords];
for(int i = 0; i < numberForbiddenWords; i++) {
temp = new TextView(this);
playGame.addView(temp);
textViews[i] = temp;
}
And I have a method that adds textViews to the activity_play_game. Unfortunately now it looks like this:
As you can see it added TextViews at the bottom. So I removed all TextViews from activity_play_game and added LinearLayout to inflate TextViews:
How can I inflate TextViews to this LinearLayout above the buttons?
I found that kind of solution:
activity_to_add_words:
<?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="vertical">
<TextView
android:id="#+id/textout"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
In the java class:
final View addView;
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
addView = layoutInflater.inflate(R.layout.activity_to_add_words,
null);
final TextView textOut = (TextView) addView.findViewById(R.id.textout);
but this is for a View, not TextView. Do you know how to do it?
Get reference of your LinearLayout container_blue and add TextView's to it.
Try this:
LinearLayout playGame = (LinearLayout) findViewById(R.id.container_blue);
TextView temp;
TextView[] textViews = new TextView[numberForbiddenWords];
for(int i = 0; i < numberForbiddenWords; i++) {
temp = new TextView(this);
temp.setText("TextView " + String.valueOf(i));
temp.setId(i);
temp.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
playGame.addView(temp);
textViews[i] = temp;
}
make one layout file using textview like this :
layout_textview.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="#+id/txt_spin"
android:textSize="18sp"
android:background="#fff"
android:padding="5dp"
android:textColor="#000"
android:layout_height="wrap_content"/>
then apply following code in your java file:
LinearLayout playGame = (LinearLayout) findViewById(R.id.container_blue);
LayoutInflater li =(LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = li.inflate(R.layout.layout_textview, null);
TextView txt= (TextView) view.findViewById(R.id.txt_spin);
playGame.addView(view);
Hope it works for you...happy coding..:)
As far as I see your initial problem was about adding the items dynamically before the three buttons. If you want to add them before the three buttons simply call playGame.addView(temp,0); This will always add the item to the first position in the layout.
If you need a specific order of the added views you need to play with the for loop to add them in the right order.

NullPointerException getting a TextView

I am creating an extremely simple Android application to serve as a proof of concept and a reference for an application I will create in the future.
My goal is to create a ListView, each item containing a TextView and a Button that, when pressed, makes a Toast pop up displaying the content of the TextView.
Here is my code and xml:
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">
<ListView
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="#+id/mainListView1"/>
</LinearLayout>
entry.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:gravity="center_vertical"
android:orientation="horizontal"
android:id="#+id/entryLayout"
>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/entryTextView1"
android:padding="10dp"
android:textSize="25sp"/>
<ImageButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="#android:drawable/ic_menu_close_clear_cancel"
android:id="#+id/entryImageButton"
/>
</LinearLayout>
MainActivity.Class
public class MainActivity extends Activity{
/* Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set main.xml as user interface layout
setContentView(R.layout.main);
String[] companies = new String[] { "Test1", "Test2", "Test3",
"Test4", "Test4", "Test6", "Test7", "Test8", "Test9", "Test10"};
ArrayList<LinearLayout> views = new ArrayList<LinearLayout>();
for(int x=0; x!= companies.length-1; x++){
LinearLayout layout = (LinearLayout) findViewById(R.id.entryLayout);
TextView text = (TextView) layout.getChildAt(0);
text.setText(companies[x]);
ImageButton button = (ImageButton) layout.getChildAt(1);
button.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
LinearLayout layout = (LinearLayout) v.getParent();
TextView view = (TextView) layout.getChildAt(0);
Toast.makeText(MainActivity.this,view.getText(), Toast.LENGTH_SHORT).show();
}
});
views.add(layout);
}
ListView listView = (ListView) findViewById(R.id.mainListView1);
for(LinearLayout layout: views){
listView.addView(layout);
}
}
I get an Kin the line
TextView text = (TextView) layout.getChildAt(0);
And for the life of me I can't figure out why. This is likely due to my lack of knowledge to how certain functions in the API work.
Your immediate issue is that findViewById looks in the layout you've inflated with setContentView() and since the Views you are trying to inflate aren't in that layout, they return null.
So this line returns null
LinearLayout layout = (LinearLayout) findViewById(R.id.entryLayout);
which causes a NPE at this line as you've noticed
TextView text = (TextView) layout.getChildAt(0);
because layout is null.
The bigger issue is the way you are going about using your ListView. Since you want to use a custom layout for the rows, you should be using a custom Adapter and inflate the appropriate layout there . You can then utilize Adapter's getView() method to set the data in each row as needed.
This tutorial can help you get started on that.
You also may want to watch Google I/O World of ListView
ListView Docs

Categories

Resources