如何检查线程是否完成执行 Android Studio [英] How to check if thread finished execution Android Studio
问题描述
我正在尝试使用数据库中的数据创建一个包含 2 个微调器的应用程序.当按下按钮时,会创建一个新的意图,显示 2 个微调器.问题是我必须在一个新线程中创建数据库查询,当我运行应用程序时,我得到一个空指针异常(据我所知,这是因为我存储数据库数据的数组是尚未填充).我的问题是,如何延迟微调器的创建,直到从数据库进行查询?下面是我的实现的示例代码:我创建微调器并调用进行数据库查询的类的意图:
I am trying to create an app that contains 2 spinners with data from a data base. When a button is pressed, a new intent is created, showing the 2 spinners. The problem is that I have to create the DB queries in a new thread, and when I run the app, I get a null pointer exception (as far as my understanding goes, it is because the array in which I store the DB data is not yet populated). My question is, how can I delay the creation of the spinners until the queries from the DB are made? Below is a sample code of my implementation: The intent where I create the spinners and make a call to a class that makes the DB queries:
String [][] dbData; //the array where i store data from DB
getDBdata myData = new getDBdata(); // create a new instance of the class that queries the DB
dbData = myData.getData(); // I get the data
Log.e("My log: ", String.valueOf(dbData.length)); //and here it crashes, giving me a null pointer exception
以及我创建新线程以进行数据库查询的类:
And the class where I create a new thread to make a DB query:
public getDBdata()
{
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
DBconn(); //make a DB query
}
});
thread.start();
}
public String[][] getData()
{
return data;
}
推荐答案
最简单的方法是使用 AsyncTask
.AsyncTask
的基本思想是将您的任务的执行分成三个步骤,这些步骤一个接一个.每个步骤都在一个单独的线程中运行.最后一个在 Main(UI) 中运行,您可以在其中创建微调器.示例:
The easiest way is a using of AsyncTask
. The basic idea of AsyncTask
is splitting execution of your task into three steps which go one after another. Each step is running in a separate thread. The last one runs in the Main(UI) where you can create your spinners. Sample:
public class DBQueryTask extends AsyncTask<Void, Void, String[][]> {
@Override
protected String[][] doInBackground(Void... params) {
DBconn();
String[][] a;
//...populating array
return a;//returning populated array
}
@Override
protected void onPostExecute(String[][] strings) {
//strings - array already populated
//this method runs on the Main thread. Therefore you can create your spinner
}
}
这篇关于如何检查线程是否完成执行 Android Studio的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!