导出为CSV时,进度对话框上出现NullPointerException - Android

问题描述 投票:0回答:1

无论我如何修改预执行类或ProgressBar的声明,我都会在上下文中获得空指针异常。我已经尝试了其他人为修复错误而实现的几个解决方案,但没有任何效果。

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

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

CatalogActivity:

 @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("");
                }

ExportDatabaseCSVTask:

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:FATAL EXCEPTION:main进程:com.example.android.stockpile,PID:7122 java.lang.NullPointerException:Attempt to在android.app.AlertDialog上的android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:224)上的空对象引用上调用虚拟方法'android.content.res.Resources $ Theme android.content.Context.getTheme()'。 (AlertDialog.java:201)在android.app.AlertDialog。(AlertDialog.java:197)android.app.AlertDialog。(AlertDialog.java:142)在android.app.ProgressDialog。(ProgressDialog.java:94)at位于com.example.android.stockpile.CatalogActivity.onOptionsItemSelected的android.os.AsyncTask.executeOnExecutor(AsyncTask.java:648)中的com.example.android.stockpile.ExportDatabaseCSVTask.onPreExecute(ExportDatabaseCSVTask.java:40)(CatalogActivity.java: 199)在android.app.Activity.onMenuItemSelected(Activity.java:3435)的android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:436)at在android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:109)android.support.v7.app.AppCompatDelegateImpl.onMenuItemSelected的android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:196) AppCompatDelegateImpl.java:888)在android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:840)在android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)在android位于android.support.v7.widget.ActionMenuView的android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:981)上的.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:991)位于android.view的android.view.View.performClick(View.java:6256)的android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:151)上的.invokeItem(ActionMenuView.java:625)。在android.os.Handler.dispatchMessage(Handler.java)的android.os.Handler.handleCallback(Handler.java:789)上查看$ PerformClick.run(View.java:24701) 98)在android.app.Looper.loop(Looper.java:164)的android.app.ActivityThread.main(ActivityThread.java:6541)at com.android的java.lang.reflect.Method.invoke(Native Method) .internal.os.Zygote $ MethodAndArgsCaller.run(Zygote.java:240)at 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不能应用于给定类型; new ExportDatabaseCSVTask()。executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); ^ required:找到上下文:无参数原因:实际和形式参数列表的长度不同F:\ Android projects \ Stockpile \ app \ src \ main \ java \ com \ example \ android \ stockpile \ CatalogActivity.java:203:错误:类ExportDatabaseCSVTask中的构造函数ExportDatabaseCSVTask不能应用于给定类型; new ExportDatabaseCSVTask()。execute(“”); ^ required:找到的上下文:无参数原因:实际和形式参数列表的长度不同

android sqlite export-to-csv progressdialog
1个回答
0
投票

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

private Context context;

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

这个例子如何在添加构造函数后调用:

new ExportDatabaseCSVTask(this)

还要注意在ExportDatabaseCSVTask类中传递上下文,通过WeakReference更好地包装上下文。

© www.soinside.com 2019 - 2024. All rights reserved.