我试图第一次创建一个AsyncTask,但我没有太多的运气。
我的AsyncTask需要从服务器获取一些信息,然后在主布局中添加新的布局来显示这些信息。
一切似乎或多或少清楚,但是,错误信息"MainActivity不是一个封闭类"是困扰我。
似乎没有人有这个问题,所以我想我错过了一些非常明显的东西,我只是不知道它是什么。
另外,我不确定我是否使用了正确的方法来获取上下文,并且因为我的应用程序不编译所以我无法测试它。
非常感谢你的帮助。
下面是我的代码:public class BackgroundWorker extends AsyncTask<Context, String, ArrayList<Card>> {
Context ApplicationContext;
@Override
protected ArrayList<Card> doInBackground(Context... contexts) {
this.ApplicationContext = contexts[0];//Is it this right way to get the context?
SomeClass someClass = new SomeClass();
return someClass.getCards();
}
/**
* Updates the GUI before the operation started
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
/**
* Updates the GUI after operation has been completed
*/
protected void onPostExecute(ArrayList<Card> cards) {
super.onPostExecute(cards);
int counter = 0;
// Amount of "cards" can be different each time
for (Card card : cards) {
//Create new view
LayoutInflater inflater = (LayoutInflater) ApplicationContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewSwitcher view = (ViewSwitcher)inflater.inflate(R.layout.card_layout, null);
ImageButton imageButton = (ImageButton)view.findViewById(R.id.card_button_edit_nickname);
/**
* A lot of irrelevant operations here
*/
// I'm getting the error message below
LinearLayout insertPoint = (LinearLayout)MainActivity.this.findViewById(R.id.main);
insertPoint.addView(view, counter++, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
}
}
Eclipse可能是正确的,并且您正在尝试从自己的文件(BackgroundWorker
)中的另一个类访问位于自己的文件中的类(MainActivity
)。没有办法做到这一点——一个类怎么能神奇地知道另一个类的实例呢?你能做的:
- 移动AsyncTask,所以它是一个内部类在
MainActivity
- 将您的活动传递给AsyncTask(通过其构造函数),然后使用
activityVariable.findViewById();
访问(我在下例中使用mActivity
)或者,您的ApplicationContext
(使用适当的命名约定,A
需要小写)实际上是MainActivity
的一个实例你很好去,所以做ApplicationContext.findViewById();
使用构造函数示例:
public class BackgroundWorker extends AsyncTask<Context, String, ArrayList<Card>>
{
Context ApplicationContext;
Activity mActivity;
public BackgroundWorker (Activity activity)
{
super();
mActivity = activity;
}
//rest of code...
至于
我不确定我是否使用了正确的方法来获取上下文
上面的例子是内部类,这里是独立类
public class DownloadFileFromURL extends AsyncTask<String, String, String> {
ProgressDialog pd;
String pathFolder = "";
String pathFile = "";
Context ApplicationContext;
Activity mActivity;
public DownloadFileFromURL (Activity activity)
{
super();
mActivity = activity;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(mActivity);
pd.setTitle("Processing...");
pd.setMessage("Please wait.");
pd.setMax(100);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setCancelable(true);
pd.show();
}
@Override
protected String doInBackground(String... f_url) {
int count;
try {
pathFolder = Environment.getExternalStorageDirectory() + "/YourAppDataFolder";
pathFile = pathFolder + "/yourappname.apk";
File futureStudioIconFile = new File(pathFolder);
if(!futureStudioIconFile.exists()){
futureStudioIconFile.mkdirs();
}
URL url = new URL(f_url[0]);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lengthOfFile = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
FileOutputStream output = new FileOutputStream(pathFile);
byte data[] = new byte[1024]; //anybody know what 1024 means ?
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lengthOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return pathFile;
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pd.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String file_url) {
if (pd!=null) {
pd.dismiss();
}
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(new File(file_url)), "application/vnd.android.package-archive" );
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(i);
}
}