主线程太多,无法从另一个线程

时间:2017-12-10 19:41:51

标签: java android multithreading button

我想在显示布局之前从数据库创建按钮。我需要这些按钮有一些onClick方法,但是我在一个(主)线程上做了太多的错误。

使用了另一个线程但是另一个线程显示错误 - 无法修改来自不同线程的View

使用了AsyncTask ,但将所有工作添加到onPreExecute()onPostExecute()并未解决任何问题并在doInBackground()内执行此操作(不会有意义吗?)>>我想渲染按钮,但backfround进程不能影响主线程

    //get data from database
    DatabaseHelperTables myDb;
    myDb = new DatabaseHelperTables(this);
    tablelist = myDb.getTablesQuery();

    if (tablelist != null) {
        //each button two values [ID,Button_text] in list, therefore i+2
        for (int i = 0; i < tablelist.size(); i = i + 2) {
            final int index = i;

            LinearLayout ll = (LinearLayout) findViewById(R.id.tlacitka);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            //create button, put inside layer
            final Button button = new Button(this);
            button.setPadding(10, 10, 10, 10);
            button.setText(tablelist.get(i+1));
            ll.addView(button, lp);

            button.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    //pass this to another activity - perform action depending on button ID
                    newActivity.someValue = tablelist.get(index);
                    Intent intent = new Intent(getApplicationContext(), newActivity.class);
                    startActivity(intent);
                }
            });
        }
    }

所有这些都在OnCreate(Bundle savedInstanceState)

那么在没有在主线程上做太多工作的情况下,最有效的方法是什么?我当时只有两个按钮,但App将从Internet下载新数据并添加越来越多,具体取决于用户。 我想使用AsyncTask,但将上面的代码移到onPreExecute()onPostExecute()会产生相同的结果。

编辑: 从数据库中获取数据

 public List<String> getTablesQuery() {
    List<String> query = new ArrayList<>();
    // Select All Query
    String selectQuery = "SELECT * FROM " + TABLE_NAME;
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    // looping through all rows and adding to list
    while (cursor.moveToNext()) {
        query.add(cursor.getString(1));
        query.add(cursor.getString(2));
        // Adding contact to list
    }
    cursor.close();
    // return list
    return query;
}

现在在后台运行AsyncTask:

@Override
    protected Void doInBackground(Void... params) {
        DatabaseHelperTables myDb;
        myDb = new DatabaseHelperTables(getApplicationContext());
        //list tablelist defined on the very top of activity
        tablelist = myDb.getTablesQuery();  
        return null;
    }

使用onclick方法在protected void onPostExecute(Void result)

中设置所有按钮
  

错误:I / Choreographer:跳过44帧!申请可能是   在主线上做了太多工作。

1 个答案:

答案 0 :(得分:0)

数据库查询后台线程并在UI线程上返回结果。此外,您可能同时创建了太多视图(具体取决于您拥有的数据量)。在这种情况下,我建议使用RecyclerView,它只能创建适合屏幕的视图。

相关问题