gpt4 book ai didi

Android ProgressDialog上下文问题

转载 作者:太空宇宙 更新时间:2023-11-03 13:04:35 25 4
gpt4 key购买 nike

简要总结:我正在制作一个应用程序来解析二进制文件、存储顶点及其属性,并在 openGL 中显示它们。我正在尝试在解析时实现 ProgressDialog,但我遇到了很多麻烦。我已经尝试在很多地方实现它,但这是我当前的设置:

    public class PointViewer extends Activity{
...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Bundle extras = getIntent().getExtras();
filePath = extras.getString("file_path");

mGLView = new GLSurfaceView(this);
theRenderer = new OpenGLRenderer();
mGLView.setRenderer(theRenderer);
//Parse the file and set the arrays
theRenderer.setLAS(filePath);
setContentView(mGLView);

}
...
}

渲染类...

public class OpenGLRenderer extends Activity implements GLSurfaceView.Renderer {
...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

}

public void setLAS (String fileName){

new ProgressTask(this).execute();


}
...
/*
* The class for the progress dialog
*/
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
private Context context;

//private List<Message> messages;
public ProgressTask(Context ctx) {

context = ctx;
dialog = new ProgressDialog(context);
}



/** progress dialog to show user that the backup is processing. */

protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
this.dialog.show();
}

@Override
protected void onPostExecute(final Boolean success) {


if (dialog.isShowing()) {
dialog.dismiss();
}

if (success) {
Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
}
}

protected Boolean doInBackground(final String... args) {
try{
ptCloud = new PointCloud(args[0]);

...

dialog.setProgress(percentParsed);
return true;
} catch (Exception e){
Log.e("tag", "error", e);
return false;
}
}


}

当我调用 dialog = new ProgressDialog(context); 它在空指针异常时出错,我假设是因为存在上下文问题...有人有任何想法吗?

最佳答案

首先,您不应该自己创建 OpenGLRenderer,因为它是一个 Activity 并且应该由系统管理。当您自己创建 OpenGLRenderer 时,此 Activity 的上下文会被错误地初始化。当您使用无效上下文创建 ProgressDialog 时,您会收到 NullPointerException


但即使您正确启动 OpenGlRenderer,您的应用程序仍会在以下行崩溃:

dialog.setProgress(percentParsed);

你应该使用 publishProgress相反,并在 AsyncTask 的 onProgressUpdate 中更新 ProgressDialog功能。那是因为您无法从非 UI 线程更新 UI。

关于Android ProgressDialog上下文问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6585510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com