我正在创建一个Android应用程序,它使用Yandex翻译API将存储在数据库中的数据(由用户插入)转换为印地语。我正在使用AsynkTask从数据库中获取数据,然后进行api调用将其转换为hindi,然后将翻译后的文本存储到arrayList中,最后使用ListView和适配器显示列表。 当互联网连接速度很慢时,应用程序始终崩溃。此外,api调用数据库中的每条记录都不是一个好方法。任何人都可以告诉我如何改进我的代码或方法来构建我的应用程序。
代码是这样的:
private class TranslationAsyncTask extends AsyncTask<String, Void, ArrayList<String>> {
@Override
protected ArrayList<String> doInBackground(String... urls) {
DiaryDbHelper mDbHelper = new DiaryDbHelper(WelcomePageActivity.this);
//get the database in readable mode
SQLiteDatabase db = mDbHelper.getReadableDatabase();
//use the query method on db object to retrieve data
String[] projection = new String[]{DiaryEntry._ID, DiaryEntry.COLUMN_CONTENT};
Cursor cursor = db.query(DiaryEntry.TABLE_NAME, projection, null, null, null, null, null);
//create an array list of contents
contentList = new ArrayList<String>();
//if preffered language is Hindi
//use yandexTranslate api
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
//String strUserName = SP.getString("username", "NA");
// boolean bAppUpdates = SP.getBoolean("applicationUpdates",false);
String lang_preffered = SP.getString("lang_preffered", "1");
if (lang_preffered.equals("2")) {
while (cursor.moveToNext()) {
String translatedData = QueryUtils.fetchTranslatedData(urls[0] + "&lang=hi" + "&text=" + cursor.getString(1));
// contentList.add(cursor.getString(1));
contentList.add(translatedData);
Log.d("welcome", "displayDatabase: " + contentList.get(0));
}
cursor.close();
return contentList;
} else {
while (cursor.moveToNext()) {
//String translatedData = QueryUtils.fetchTranslatedData(urls[0]+cursor.getString(1));
contentList.add(cursor.getString(1));
// contentList.add(translatedData);
Log.d("welcome", "displayDatabase: " + contentList.get(0));
}
cursor.close();
return contentList;
}
}
@Override
protected void onPostExecute(ArrayList<String> translations) {
//super.onPostExecute(earthquakes);
UpdateUI(translations);
}
public void UpdateUI(ArrayList<String> translatedList) {
// EarthQuakeAdapter itemsAdapter = new EarthQuakeAdapter(EarthquakeActivity.this,earthquakeList);
ArrayAdapter<String> itemsAdapter = new ArrayAdapter<String>(WelcomePageActivity.this, R.layout.list_view, translatedList);
ListView listview = (ListView) findViewById(R.id.list_view);
listview.setAdapter(itemsAdapter);
}
}