Question

I am having trouble adding rows with TextView inside a TableLayout.

I have created a table_row.xml where i define by xml my TableRow and its TextView's.

table_row xml :

<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >


<TextView
    android:id="@+id/textView_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="2"
    android:text="@string/food_label"
    android:textAppearance="?android:attr/textAppearanceSmall" />

<TextView
    android:id="@+id/textView_kcal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="@string/kcal_label"
    android:textAppearance="?android:attr/textAppearanceSmall" />

</TableRow>

Here is what i do :

Inside class where i want to inflate it in. I define

LayoutInflater inflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
private TableLayout tableChronology = (TableLayout) findViewById(R.id.tableLayout1);
View tr = inflater.inflate(R.layout.table_row_chronology, null,false);

// Here is where i get an error;
tableChronology.addView(tr);

Here is LogCat:

FATAL EXCEPTION: main
Process: com.example.appscan5, PID: 31647
java.lang.NullPointerException
at com.example.appscan5.Today$2.onClick(Today.java:66)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Était-ce utile?

La solution

Here is what fixed my problem if any one is interested in this.

I used:

private LayoutInflater inflater;
View tr = inflater.inflate(R.layout.table_row_chronology, null);

Instead of:

LayoutInflater inflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);

Below is code :

private LayoutInflater inflater;
View tr = inflater.inflate(R.layout.table_row_chronology, null);
TableLayout tableChronology = (TableLayout) findViewById(R.id.mainTable);
tableChronology.addView(tr);

Autres conseils

You should write below code to get it working

private TableLayout tableChronology = (TableLayout) findViewById(R.id.tableLayout1);
TableRow tablerow = new TableRow(this);
View tr = inflater.inflate(R.layout.table_row_chronology, tablerow, false);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top