【问题标题】:NullPointerException on Progress Dialog while exporting to CSV - Android导出到 CSV 时进度对话框出现 NullPointerException - Android
【发布时间】:2019-03-03 04:24:27
【问题描述】:

无论我如何修改预执行类或 ProgressBar 的声明,我都会在上下文中遇到空指针异常。我尝试了几种其他人实施的解决方案来修复错误,但没有任何效果。

我的应用程序应在 CatalogActivity 中单击按钮后导出 CSV。

已经花了几天时间...非常感谢您的帮助。

目录活动:

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {

                //export data to CSV using method in InventoryProvider via separate java class ExportDatabaseCSVTask
            case  R.id.export_to_csv:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

                    new ExportDatabaseCSVTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

                } else {

                    new ExportDatabaseCSVTask().execute("");
                }

导出数据库CSV任务:

public class ExportDatabaseCSVTask extends AsyncTask<String, String, Boolean> {


    private Context context;
    private ProgressDialog dialog;
    InventoryProvider iProvider;



    @Override
    protected void onPreExecute() {
        super.onPreExecute();


        dialog = new ProgressDialog(context);  ---ERROR HERE

        this.dialog.setMessage("Saving. Please Wait...");
       this.dialog.show();
    }



    @TargetApi(Build.VERSION_CODES.O)
    protected Boolean doInBackground(final String... args) {

        File exportDir = new File(Environment.getExternalStorageDirectory(), "/codesss/");
        if (!exportDir.exists()) { exportDir.mkdirs(); }

        File file = new File(exportDir, "inventory.csv");
        try {
            file.createNewFile();
            CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
            Cursor curCSV = iProvider.raw(CONTENT_URI);
            csvWrite.writeNext(curCSV.getColumnNames());
            while(curCSV.moveToNext()) {
                String arrStr[]=null;
                String[] mySecondStringArray = new String[curCSV.getColumnNames().length];
                for(int i=0;i<curCSV.getColumnNames().length;i++)
                {
                    mySecondStringArray[i] =curCSV.getString(i);
                }
                csvWrite.writeNext(mySecondStringArray);
            }
            csvWrite.close();
            curCSV.close();
            return true;

        } catch (IOException e) {
            return false;
        }
    }

    protected void onPostExecute(final Boolean success) {
        if (this.dialog.isShowing()) { this.dialog.dismiss(); }
        if (success) {
            Toast.makeText(CatalogActivity.getApplicationContext, "this is my Toast message!!! =)",  Toast.LENGTH_LONG).show();
            ShareFile();
        } else {
            Toast.makeText(CatalogActivity.getApplicationContext, "Export failed", Toast.LENGTH_SHORT).show();
        }
    }

    private void ShareFile() {
        File exportDir = new File(Environment.getExternalStorageDirectory(), "/codesss/");
        String fileName = "myfile.csv";
        File sharingGifFile = new File(exportDir, fileName);
        Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
        shareIntent.setType("application/csv");
        Uri uri = Uri.fromFile(sharingGifFile);
        shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
        CatalogActivity.getApplicationContext.startActivity(Intent.createChooser(shareIntent, "Share CSV"));
    }

Logcat:

2019-03-02 21:05:16.109 7122-7122/com.example.android.name E/AndroidRuntime: 致命异常: main 进程:com.example.android.stockpile,PID:7122 java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“android.content.res.Resources$Theme android.content.Context.getTheme()” 在 android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:224) 在 android.app.AlertDialog.(AlertDialog.java:201) 在 android.app.AlertDialog.(AlertDialog.java:197) 在 android.app.AlertDialog.(AlertDialog.java:142) 在 android.app.ProgressDialog.(ProgressDialog.java:94) 在 com.example.android.stockpile.ExportDatabaseCSVTask.onPreExecute(ExportDatabaseCSVTask.java:40) 在 android.os.AsyncTask.executeOnExecutor(AsyncTask.java:648) 在 com.example.android.stockpile.CatalogActivity.onOptionsItemSelected(CatalogActivity.java:199) 在 android.app.Activity.onMenuItemSelected(Activity.java:3435) 在 android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:436) 在 android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:196) 在 android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:109) 在 android.support.v7.app.AppCompatDelegateImpl.onMenuItemSelected(AppCompatDelegateImpl.java:888) 在 android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:840) 在 android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158) 在 android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:991) 在 android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:981) 在 android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:625) 在 android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:151) 在 android.view.View.performClick(View.java:6256) 在 android.view.View$PerformClick.run(View.java:24701) 在 android.os.Handler.handleCallback(Handler.java:789) 在 android.os.Handler.dispatchMessage(Handler.java:98) 在 android.os.Looper.loop(Looper.java:164) 在 android.app.ActivityThread.main(ActivityThread.java:6541) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 2019-03-02 21:05:16.114 1694-4875/system_process W/ActivityManager:强制完成活动 com.example.android.name/.CatalogActivity

如果我尝试将以下内容添加到 ExportDatabaseCSVTask:

public ExportDatabaseCSVTask(Context context) {
        this.context = context;
    }

我在 CatalogActivity 中收到以下错误:

 case  R.id.export_to_csv:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

                    new ExportDatabaseCSVTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - ERROR

                } else {

                    new ExportDatabaseCSVTask().execute(""); --ERROR
                }

错误: 类 ExportDatabaseCSVTask 中的构造函数 ExportDatabaseCSVTask 不能应用于给定类型; 新的 ExportDatabaseCSVTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); ^ 必需:上下文 发现:没有参数 原因:实际参数列表和形式参数列表的长度不同 F:\Android projects\Stockpile\app\src\main\java\com\example\android\stockpile\CatalogActivity.java:203:错误:ExportDatabaseCSVTask 类中的构造函数 ExportDatabaseCSVTask 不能应用于给定类型; 新的 ExportDatabaseCSVTask().execute(""); ^ 必需:上下文 发现:没有参数 原因:实际参数列表和形式参数列表的长度不同

【问题讨论】:

    标签: android sqlite export-to-csv progressdialog


    【解决方案1】:

    您的上下文将始终为空,因为他没有初始化。通过构造函数初始化上下文

    private Context context;
    
    public ExportDatabaseCSVTask(Context context) {
        this.context = context;
    }
    

    这是一个添加构造函数后如何调用的示例:

    new ExportDatabaseCSVTask(this)
    

    还要小心在 ExportDatabaseCSVTask 类中传递上下文,最好通过 WeakReference 包装上下文。

    【讨论】:

    • 您好 Dmitro,感谢您的回复!我以前和现在也试过这个,我收到的错误是:“需要:找到上下文:没有参数原因:实际和正式的参数列表长度不同”
    • 基本上,我需要修改 CatalogActivity 的 onOptionsItemSelected 中的引用。但是,我不知道如何引用 ExportDatabaseCSVTask....
    • 我编辑了我的答案,看看你如何调用你的 AsyncTask。没什么特别的,只是传递你的上下文。
    • 谢谢Dmitro,现在终于没有错误了!我会投票给答案:) 现在我有一个新问题,可能我需要创建一个新问题?当我点击我的导出按钮时,没有任何反应 - 没有弹出消息或保存文件的操作:没有向 HAL 提供足够的数据,预期位置 3650731 ,只写了 3650400
    • 是的,最好创建一个新问题。
    猜你喜欢
    • 2016-09-21
    • 1970-01-01
    • 2013-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多