我无法弄清楚如何完成这项工作。
我正在开发一个应用程序,在其中我从在线 txt 下载数据,解析它并将其添加到我的数据库中。这需要 +-30 秒,并且只实现了更新程序的一部分。
当我尝试使用线程或异步任务时,在尝试将参数传递给正在更新数据库的 void 时遇到问题。
如何以良好的方式实现它?
这是我的代码:
主要 Activity 类别:
public class Androideye_principal extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
//WhazzupUpdate.DownloadWhazzup(AllUsers, TotalConnections);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_androideye_principal);
PilotsSQLiteHelper pdbh = new PilotsSQLiteHelper(this, "PilotsDB", null, 1);
SQLiteDatabase dbPilots = pdbh.getWritableDatabase();
Context context = getApplicationContext();
String TotalConnections = new String();
WhazzupUpdate.DownloadWhazzup(dbPilots, TotalConnections, context);
dbPilots.close();
CharSequence text = "Total Users: " + TotalConnections;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
[Continues with Buttons stuff and so on...]
解析器类:
public class WhazzupUpdate {
public static void DownloadWhazzup (SQLiteDatabase PilotsDB, String TotalConnections, Context context) {
try {
// Create a URL for the desired page
URL url = new URL("This is my url/whazzup.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
for (int i = 0; i<=4; i++) {
in.readLine(); } // Go to the number of connections
TotalConnections = in.readLine();
for (int i = 0; i<=3; i++) {
in.readLine(); } // Go to !CLIENTS
PilotsDB.execSQL("DELETE FROM Pilots");
while (((str = in.readLine()) != null) && !(in.readLine().contains("!AIRPORTS"))) {
// str is one line of text; readLine() strips the newline character(s)
String[] dataRow = str.split(":");
if (str.contains("PILOT")) {
ContentValues NewValue = new ContentValues();
NewValue.put("VID", dataRow[1]);
[More NewValue puts...]
PilotsDB.insert("Pilots", null, NewValue);
} //End IF Pilot
} // End While
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
}}
如您所见,我在主 Activity 中调用 WhazzupUpdate.DownloadWhazzup 方法,此时所有内容都被卡住,但不知道如何将其派生到另一个威胁并保留对数据库的引用等...
希望有人能帮助我。提前致谢。
最佳答案
一个Thread
或AsyncTask
这里就可以了。我更喜欢使用 AsyncTask
对于我大部分的繁重工作。您可以创建 AsyncTask
并在 doInBackground()
中完成您的工作因为它在背景上工作Thread
。然后您可以更新您的UI
元素(如果在其任何其他方法中需要的话)。
onPostExecute()
将在从 doInBackground()
传递结果后运行
onProgressUpdate()
如果您需要更新 UI
将运行期间doInBackground()
调用publishProgress()
进行操作。在这里您可以显示ProgressBar
如果您需要
和
onPreExecute()
将在您在 doInBackground()
之前第一次调用任务时运行运行。
使用 Thread
在后台线程中运行代码或AsyncTask
将允许您UI
在完成繁重工作的同时获得自由。
关于java - Android - 将数据恢复到 SQLite 时的 AsyncTask 或线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19467339/