1

I've used elasticView progressbar library in this project. When I use this directly in a single Activity with an AsyncTask it works fine, but when I create the new java class for downloading and accessed from the MainActivity. It shows class not found exception. Here is my complete code with error log.


MainActivity


public class MainActivity extends AppCompatActivity {
    Button b1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        b1=(Button)findViewById(R.id.button);
        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                download d=new download();
                d.startdownload();
            }
        });
    }

download.java


import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import it.michelelacorte.elasticprogressbar.ElasticDownloadView;

public class download extends AppCompatActivity {
    ElasticDownloadView mElasticDownloadView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.elastic);

        mElasticDownloadView = (ElasticDownloadView) findViewById(R.id.elastic_download_view);
        mElasticDownloadView.setVisibility(View.VISIBLE);

        startdownload();
    }

    public void startdownload() {

        final DownloadTask downloadTask = new DownloadTask(download.this);
        mElasticDownloadView.setVisibility(View.GONE);
        downloadTask.execute("http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg");
    }

    private class DownloadTask extends AsyncTask<String, Integer, String> {
        private Context context;

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

        @Override
        protected String doInBackground(String... sUrl) {


            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;
            try {
                URL url = new URL(sUrl[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();
                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    return "Server returned HTTP " + connection.getResponseCode()
                            + " " + connection.getResponseMessage();
                }

                int fileLength = connection.getContentLength();
                input = connection.getInputStream();
                output = new FileOutputStream("/sdcard/some_photo_from_gdansk_poland.jpg");

                byte data[] = new byte[4096];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {

                    if (isCancelled()) {
                        input.close();
                        return null;
                    }
                    total += count;

                    if (fileLength > 0) {
                        int status = ((int) (total * 100 / fileLength));
                        publishProgress(status);
                    }
                    output.write(data, 0, count);
                }
            } catch (Exception e) {
                return e.toString();
            } finally {
                try {
                    if (output != null)
                        output.close();
                    if (input != null)
                        input.close();
                } catch (IOException ignored) {
                }

                if (connection != null)
                    connection.disconnect();
            }
            return null;

        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mElasticDownloadView.startIntro();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            mElasticDownloadView.setProgress(10);
        }

        @Override
        protected void onPostExecute(String result) {
            mElasticDownloadView.success();
            if (result != null)
                Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show();
        }
    }
}

activity_main.xml


 <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="net.logicalsteps.download_notif.MainActivity">

        <include layout="@layout/elastic"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="start download"
            android:id="@+id/button"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="31dp" />
    </RelativeLayout>

elastic.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="wrap_content"
    android:layout_height="100dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true">

    <it.michelelacorte.elasticprogressbar.ElasticDownloadView
        android:id="@+id/elastic_download_view"
        android:layout_width="match_parent"
        android:layout_height="90dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="27dp" />



</RelativeLayout>

error log:


E/AndroidRuntime: FATAL EXCEPTION: main 
Process: net.logicalsteps.download_notif, PID: 23132  
java.lang.NullPointerException: Attempt to invoke virtual method 'void it.michelelacorte.elasticprogressbar.ElasticDownloadView.setVisibility(int)' on a null object referenc
        at net.logicalsteps.download_notif.download.startdownload(download.java:41)
        at net.logicalsteps.download_notif.MainActivity$1.onClick(MainActivity.java:39)
        at android.view.View.performClick(View.java:5162)
        at android.view.View$PerformClick.run(View.java:20873)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)                                      at android.os.Looper.loop(Looper.java:145)                                         at android.app.ActivityThread.main(ActivityThread.java:5835)                                         at java.lang.reflect.Method.invoke(Native Method)                                         at java.lang.reflect.Method.invoke(Method.java:372)                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
Shree Krishna
  • 8,474
  • 6
  • 40
  • 68
Muhammed Riyas A V
  • 71
  • 1
  • 1
  • 11
  • First start the activity download so the views can be initialized then play with the visibility of views. or don't use the another activity download just make AsynTask extended class and change the views in mainActivity. – Shahab Rauf Mar 30 '16 at 10:03

3 Answers3

2

You need to start an Activity from another with an Intent, else, your class will be initialized, but the Activity will not start its Lifecycle (the onCreate method and such will not be called):

    b1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent downloadIntent = new Intent(v.getContext(), download.class);
            startActivity(downloadIntent);
        }
    });

If you don't want to open a new Activity, you could move your AsyncTask to your MainActivity, and while the it downloads, you could show an custom AlertDialog with your ProgressBar. You can find more on this here.

Community
  • 1
  • 1
yennsarah
  • 5,467
  • 2
  • 27
  • 48
1

Simply you have to look at here

 download d=new download();
 d.startdownload();

You called startdownload() method but till that time onCreate of download Activity isn't called so that mElasticDownloadView could not be initialized. So that initialize that inside either startdownload method too, or anywhere you feel comfortable, OR start the Activity download in onClick() method.

Shree Krishna
  • 8,474
  • 6
  • 40
  • 68
0

Cause of error

The reason this is happening is because when the system starts the download activity, it executes download.onCreate which sets mElasticDownloadView = .... But when you create it in onClick you do not call onCreate so mElasticDownloadView is not initialized.

Using Activities

Now in onClick you create an instance of the download Activity:

download d=new download();
d.startdownload();

This is not the usual way to create activities. If you do it this way, the activity will not have all of its UI inflated from the layout XML file and so there is no progress bar either. If you want to show the activity, you should instead use:

Intent intent = new Intent(MainActivity.this, download.class);
startActivity(intent);

Now, if you want to pass a message to the Activity, you could pass it through the intent:

intent.putExtra(EXTRA_MESSAGE, message);

Then in download.onStart you can retrieve this message getIntent().getStringExtra(...).

However, in your download.onCreate you call startdownload anyway, so you shouldn't need to do the message passing.

Learn more about this here: https://developer.android.com/training/basics/firstapp/starting-activity.html

szym
  • 5,606
  • 28
  • 34
  • :Thanks for your valuable information.i understood the mistake. – Muhammed Riyas A V Mar 30 '16 at 10:08
  • can you sujjest me a way to handle this without using intent.i mean,i need this progressbar in the screen untill the download finishes like a floating item.it should not be gone even if we move out to another page. – Muhammed Riyas A V Mar 30 '16 at 10:16
  • You could compose a single Activity from a number of Views (one of them would be the progress bar). If not, you should take a look at Fragments. – szym Mar 30 '16 at 10:32