簡體   English   中英

導出到CSV時進度對話框上出現NullPointerException-Android

[英]NullPointerException on Progress Dialog while exporting to CSV - Android

無論我如何修改預執行類或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:致命例外:主進程:com.example.android.stockpile,PID:7122 java.lang.NullPointerException:嘗試在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) com.example.android.stockpile.CatalogActivity.onOptionsItemSelected(CatalogActivity.java:com.example.android.stockpile.ExportDatabaseCSVTask.onPreExecute(ExportDatabaseCSVTask.java:40)位於android.os.AsyncTask.executeOnExecutor(AsyncTask.java:648) 199),位於android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:436),位於android.app.Activity.onMenuItemSelected(Activity.java:3435) android.support.v7.app.AppCompatDelegateImpl.onMenuItemSelected()上的android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:196)在android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:109) android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:840)上的AppCompatDelegateImpl.java:888)android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)上的android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:981)上的.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:991)android.support.v7.widget.ActionMenuView android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:151)的android.view.View.performClick(View.java:6256)的.invokeItem(ActionMenuView.java:625)。 View $ PerformClick.run(View.java:24701)在android.os.Handler.handleCallback(Handler.java:789)在android.os.Handler.dispatchMessage(Handler.java: 98)at android.os.Looper.loop(Looper.java:164)at 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)在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項目\\ Stockpile \\ app \\ src \\ main \\ java \\ com \\ example \\ android \\ stockpile \\ CatalogActivity.java:203:錯誤:類ExportDatabaseCSVTask中的構造函數ExportDatabaseCSVTask不能應用於給定類型; 新的ExportDatabaseCSVTask()。execute(“”); ^必需:找到上下文:無參數原因:實際參數和正式參數列表的長度不同

您的上下文將始終為空,因為他尚未初始化。 通過構造函數初始化上下文

private Context context;

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

這是添加構造函數后如何調用的示例:

new ExportDatabaseCSVTask(this)

也要注意在ExportDatabaseCSVTask類內部傳遞上下文,最好通過WeakReference包裝上下文。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM