我对android很新,现在我需要asynctask的帮助,因为我无法摆脱它!我的应用程序中有一些资源需要2-3秒才能加载,因此我想用“请稍候”创建progressdialog并使用doinbackground在后台加载资源,然后将它们传递回主活动。我已经阅读了很多帖子,但我无法获得解决方案
所以我希望任何人都可以帮助我,并告诉我如何将数据传递回主要活动。 Thanx提前!!
以下是代码:
public class Menu extends Activity {
MyTask objMyTask;
Context context = this;
LinearLayout order;
ImageButton startorder;
LinearLayout menu, categories_list;
TextView texthint;
String[] item_image;
String[] item_title;
String[] item_shortdesc;
String[] item_desc;
String[] item_price;
int[] item_category;
String[] MenuCategories;
String sign = "";
ArrayList<Integer> items_in_order = new ArrayList<Integer>();
TextView buy;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
//force portrait
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//load data from strings.xml
sign = getResources().getString(R.string.CurrencySign);
item_title = getResources().getStringArray(R.array.ItemTitle);
item_image = getResources().getStringArray(R.array.ItemImage);
item_desc = getResources().getStringArray(R.array.ItemDescription);
item_shortdesc = getResources().getStringArray(R.array.ItemShortDescription);
item_price = getResources().getStringArray(R.array.ItemPrice);
item_category = getResources().getIntArray(R.array.ItemCategory);
MenuCategories = getResources().getStringArray(R.array.MenuCategories);
//load resources
TextView menu_title = (TextView) findViewById(R.id.menu_title);
TextView yourorder = (TextView) findViewById(R.id.yourorder);
TextView hinttext = (TextView) findViewById(R.id.hinttext);
TextView categories = (TextView) findViewById(R.id.categories);
menu = (LinearLayout) findViewById(R.id.menuscroll);
startorder = (ImageButton) findViewById(R.id.startorder);
order = (LinearLayout) findViewById(R.id.orderscroll);
texthint = (TextView) findViewById(R.id.hinttext);
categories_list = (LinearLayout) findViewById(R.id.categories_list);
I want load the data from strings.xml in background like item_title, item_image,item_desc, item_shortdesc, item_price, item_category, MenuCategories
I have this code for asynctask:
public class MyTask extends AsyncTask<String, Void, String> {
private ProgressDialog dialog;
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(Menu.this);
dialog.setMessage("Loading...");
dialog.show();
}
@Override
protected String doInBackground(String... passing) {
{
try {
I don´t know what to enter here ??
} catch (Exception e) {
Log.e("Image","Failed to load Data",e);
}
return null;
}
}
@Override
protected void onPostExecute(String result) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
答案 0 :(得分:0)
资源通过资源管理器加载,与资产不同,应用程序几乎无法控制此过程。调用getResources().getString()
不会加载strings.xml
文件,因为它已经在幕后加载(每个应用运行一次)。因此,将这些调用放在AsyncTask中是没有意义的。
您可以在此处了解有关访问资源的详情:http://developer.android.com/guide/topics/resources/index.html
答案 1 :(得分:0)
如果您的应用无法快速加载字符串资源,则可能是您的数组太大而无法保存在资源中。我强烈建议您使用SQLite数据库代替您的方法。这将解决您的速度问题,并且随着您的菜单增加,使用起来会更加可维护。