Frage

Ich habe Code verwendet, um einige Dateien aus unserem Internet herunterzuladen.

public class SplashDownload extends Activity {

    public static final int PROGRESS_DIALOG = 0;
    private ProgressDialog mProgressDialog;
    private WordDataHelper wordDataHelper;
    private ExtraDataHelper extraDataHelper;

    // put your file path here
    private String filePath = "http://test.com/Assets/";
    // put your filename here
    private String fileName;
    // put your download directory name here
    private String downloadDir;

    private int wordCounter = 0, extraCounter = 0, counter = 1;

    private boolean wordDLOn = true;
    private int totalFileNo;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splashdllayout);
        getDownloadList();
    }

    private void goForward() {

        Intent intent = new Intent().setClass(this, LangH.class)
                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    }

    private void doNext() {

        if (wordDLOn) {

            System.out.print("wordDetails update: "
                    + wordDetails[wordCounter - 1][0]
                    + extraDetails[extraCounter][0] + fileName);
            wordDataHelper.updateDLStat(Long
                    .valueOf(wordDetails[wordCounter - 1][0]));
        } else {

            System.out.print("extraDetails update: "
                    + extraDetails[extraCounter - 1][0] + fileName);
            extraDataHelper.updateDLStat(Long
                    .valueOf(extraDetails[extraCounter - 1][0]));
        }

        if (wordCounter < wordDetails.length) {
            System.out.print("wordCounter: " + wordCounter + "/"
                    + wordDetails.length);
            startDownload(wordDetails[wordCounter][1]);
            wordCounter++;
        } else if (extraCounter < extraDetails.length) {
            wordDLOn = false;
            downloadDir = "LanH/extras";
            System.out.print("extraCounter: " + extraCounter + "/"
                    + extraDetails.length);
            startDownload(extraDetails[extraCounter][1]);
            extraCounter++;
        } else {
            goForward();
        }
    }

    private void getDownloadList() {

        // lessons download..........

        String[] wordDetails = {"1.mp4","2.mp4","3.mp4","4.mp4","5.mp4","6.mp4","7.mp4","8.mp4",};
        downloadDir = "LanH/words";


        String[] extraDetails = {"a.mp4","b.mp4","c.mp4","d.mp4","e.mp4","f.mp4","g.mp4","h.mp4",};


        totalFileNo = extraDetails.length + wordDetails.length;

        if (wordDetails.length != 0) {
            startDownload(wordDetails[wordCounter]);
            wordCounter++;
        } else if (extraDetails.length != 0) {
            wordDLOn = false;
            startDownload(extraDetails[extraCounter]);
            extraCounter++;
        } else {
            goForward();
        }

    }

    private void startDownload(String dlFilename) {
        // tv = (TextView) findViewById(R.id.tv1);
        fileName = dlFilename;
        System.out.print("fileName: " + fileName);

        File dir = new File(android.os.Environment
                .getExternalStorageDirectory().getAbsolutePath()
                + "/"
                + downloadDir);
        // creates the directory if it doesn't exists
        if (dir.exists() == false) {
            dir.mkdirs();
        }
        dir = null;

        if (checkNet()) {
            if (checkExternalMedia() == true) {
                String url = filePath + fileName;
                new DownloadFileAsync().execute(url, fileName);
                mProgressDialog.setMessage("Downloading file.." + fileName);
            } else {
                Toast.makeText(getApplicationContext(),
                        "External Media is NOT readable/writable",
                        Toast.LENGTH_SHORT).show();
            }
        } else {

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("No Internet Connectivity. Check the connection and retry the app.")
                    .setCancelable(false)
                    .setPositiveButton("OK",
                            new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int id) {
                            finish();
                        }
                    });
            AlertDialog alert = builder.create();
            alert.show();
        }
    }


    /** Method to check whether external media available and writable. */
    private boolean checkExternalMedia() {
        boolean stat;
        String state = Environment.getExternalStorageState();

        if (Environment.MEDIA_MOUNTED.equals(state)) {
            // Can read and write the media
            stat = true;
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            // Can only read the media
            stat = false;
        } else {
            // Can't read or write
            stat = false;
        }
        return stat;
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case PROGRESS_DIALOG:
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Downloading file.." + fileName);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setCancelable(false);
            mProgressDialog.show();
            return mProgressDialog;
        default:
            return null;
        }
    }

    class DownloadFileAsync extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(PROGRESS_DIALOG);
        }

        @Override
        protected String doInBackground(String... aurl) {
            int count;

            try {
                URL url = new URL(aurl[0]);
                URLConnection conexion = url.openConnection();
                conexion.connect();

                int lenghtOfFile = conexion.getContentLength();
                Log.d("DOWNLOAD_TEST", "Lenght of file: " + lenghtOfFile);

                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(
                        android.os.Environment.getExternalStorageDirectory()
                                + "/" + downloadDir + "/" + aurl[1]);

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();
            } catch (Exception e) {
            }
            return null;

        }

        protected void onProgressUpdate(String... progress) {
            Log.d("DOWNLOAD_TEST", progress[0]);
            mProgressDialog.setProgress(Integer.parseInt(progress[0]));
        }

        @Override
        protected void onPostExecute(String unused) { 

            dismissDialog(PROGRESS_DIALOG);

            // tv.append("\n\nFile Download Complete!");
            // Button btn = (Button) findViewById(R.id.btn1);
            // btn.setVisibility(View.GONE);

            // you can call a second intent here to redirect to another screen
            doNext();
        }
    }

    private boolean checkNet() {
        boolean connected = false;
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
                .getState() == NetworkInfo.State.CONNECTED
                || connectivityManager.getNetworkInfo(
                        ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
            // we are connected to a network
            connected = true;
        } else
            connected = false;
        return connected;

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }
}

Der Prozess läuft gut. Es wird nach dem Absturzbericht berichtet:

java.lang.IllegalArgumentException: no dialog with id 0 was ever shown via Activity#showDialog
at android.app.Activity.missingDialog(Activity.java:2663)
at android.app.Activity.dismissDialog(Activity.java:2648)
at com.langhost.main.SplashDownload$DownloadFileAsync.onPostExecute(SplashDownload.java:264)
at com.langhost.main.SplashDownload$DownloadFileAsync.onPostExecute(SplashDownload.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:417)
at android.os.AsyncTask.access$300(AsyncTask.java:127)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:143)
at android.app.ActivityThread.main(ActivityThread.java:5068)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)

Was ist das Problem in meinem Code? Ist isShowing() Überprüfen Sie vorher dismissDialog Wird das Problem lösen?

War es hilfreich?

Lösung

Wird Ihr Fortschrittsdialog tatsächlich angezeigt?
Anstatt es zu entlassen, könnten Sie versuchen, es zu verwenden removeDialog(PROGRESS_DIALOG); um es aufzuräumen.

Andere Tipps

Wenn du das machst

mProgressDialog.show();

während

protected Dialog onCreateDialog(int id)

Sie haben die ID für den Dialogfeld bereits auf einen zufälligen oder null -Wert festgelegt. Wenn Sie also anrufen, um es zu entlassen, glaubt die Bewerbung, dass Sie verrückt sind.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top