2011-08-23 95 views
1

我一直在寻找这附近,但我似乎无法找到正确的来源/答案。动态添加textview到布局

我想从我的SQLite数据库中提取数据,并根据我在数据库中的元素数量在布局(使用TextViews)中显示它。

如何将TextViews添加到“即时”布局? hardcoding textviews是非常简单的,但我不知道如何动态。 感谢您的帮助!

这里是我的类:

package android.GUI; 


public class Shifts extends Activity implements OnClickListener { 

String dbTime; 

DBAdapter DB = new DBAdapter(this); 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.shifts); 

    LinearLayout layout = (LinearLayout) findViewById(R.id.shifts); 
    TextView text = new TextView(this); 

    DB.open(); 
    Cursor c = DB.getAllShifts(); 
    if (c.moveToFirst()) { 
     do { 

     } while (c.moveToNext()); 
     layout.addView(text); 
     text.setText(showDB(c)); 

    } 

    DB.close(); 

} 

public String showDB(Cursor c) { 
    dbTime = c.getString(1) + "\n" + c.getString(2); 

    return dbTime; 
} 

回答

3

您已经使用

DBAdapter DB = new DBAdapter(this); 

线Activity之前启动。所以这个关键字是导致空指针exception.Please db.open();

动态添加之前写的方法onCreate()这一行:

TextView tv = new TextView(this); 
tv.setText("TaskID"); 
TextView tv1 = new TextView(this); 
task = new EditText(this); 
task.setMaxWidth(100); 
task.setMinHeight(100); 
tv1.setText("Task"); 
id = new EditText(this); 
id.setMaxHeight(10); 
TextView tv2 = new TextView(this); 
name = new EditText(this); 

name.setMaxHeight(1); 
tv2.setText("Name"); 


LinearLayout l = new LinearLayout(this); 
l.setOrientation(LinearLayout.VERTICAL); 
l.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
setContentView(l); 

l.addView(tv); 
l.addView(id); 
l.addView(tv1); 
l.addView(task); 
l.addView(tv2); 
+1

谢谢你,我已经将这一行移至onCreate方法,但仍然崩溃。有什么建议么? – Yosi199

+0

用更新的代码更新你的问题 – Rasel

1

您可以使用ListView和SimpleCursorAdapter,它会自动为你的数据库记录创造的景色。 http://thinkandroid.wordpress.com/2010/01/09/simplecursoradapters-and-listviews/

或者,如果你还是想自己来管理它,你可以使用下列内容:

// In onCreate method. 
// E.g. your topmost view is LinearLayour with id 'layout'. 
LinearLayout layout = findViewById(R.id.layout); 
TextView text = new TextView(this); 
text.setText("Hello, I'm dynamically added text view"); 
layout.addView(text). 
+0

您好,感谢您的帮助。我试过这样做,但我的活动崩溃。你能看看我的代码,并指出我错在哪里,为什么我错了? – Yosi199