我很难弄清楚如何使这项工作。
我正在开发一个应用程序,在该应用程序中,我从在线 txt 下载数据,对其进行解析并将其添加到我的数据库中。这需要 +-30 秒,并且只实施了更新程序的一部分。
当我尝试使用线程或异步任务时,在尝试将参数传递给正在更新数据库的 void 时遇到问题。
我怎样才能以好的方式实施它?
这是我的代码:
主要活动类:
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) {
}
}}
如您所见,我在主要活动中调用了 WhazzupUpdate.DownloadWhazzup 方法,此时一切都被冻结了,但不知道如何将其推导到另一个威胁并保留对数据库的引用等等......
希望任何人都可以帮助我。提前致谢。