获取:如何添加监听器?

时间:2018-09-19 16:38:16

标签: java android networking fetch

我正在尝试使用Fetch: The Best Downloading Library,但目前停留在侦听器部分。

这是下面的代码:

 public class MainActivity extends AppCompatActivity {
    Fetch fetch;
    private TextView Title;
    private TextView time;
    private TextView percentage;
    private TextView speed;
    private EditText userUrl;
    protected Request request;
    String url = "";
    @Override
    protected void onDestroy() {
        super.onDestroy();
        fetch.close();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Title = findViewById(R.id.textView1);
        time = findViewById(R.id.textView3);
        percentage = findViewById(R.id.textView2);
        speed= findViewById(R.id.textView4);
        Button download = findViewById(R.id.button);
        userUrl = findViewById(R.id.editText);
        final FetchListener fetchListener = new FetchListener() {
            @Override
            public void onAdded(@NotNull Download download) {
                Title.setText(getFileName(download.getFile()));
                SetProgressView(download.getStatus(),download.getProgress());
                UpdateView(download,0,0,null);
            }

            @Override
            public void onCancelled(@NotNull Download download) {
                UpdateView(download,0,0,null);
            }

            @Override
            public void onCompleted(@NotNull Download download) {
                UpdateView(download,0,0,null);
                Toast.makeText(MainActivity.this, "Download Successful", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDeleted(@NotNull Download download) {
                UpdateView(download,0,0,null);
            }

            @Override
            public void onDownloadBlockUpdated(@NotNull Download download, DownloadBlock downloadBlock, int i) {

            }

            @Override
            public void onError(@NotNull Download download, Error error, Throwable throwable) {
                UpdateView(download,0,0,download.getError());
            }

            @Override
            public void onPaused(@NotNull Download download) {
                UpdateView(download,0,0,null);
            }

            @Override
            public void onProgress(@NotNull Download download, long MilSec, long Bytes) {
                UpdateView(download,MilSec,Bytes,null);
            }

            @Override
            public void onQueued(@NotNull Download download, boolean b) {
                Title.setText(getFileName(download.getFile()));
                SetProgressView(download.getStatus(),download.getProgress());
                UpdateView(download,0,0,null);
            }

            @Override
            public void onRemoved(@NotNull Download download) {
                UpdateView(download,0,0,null);
            }

            @Override
            public void onResumed(@NotNull Download download) {
                UpdateView(download,0,0,null);
            }

            @Override
            public void onStarted(@NotNull Download download, List<? extends DownloadBlock> list, int i) {
                UpdateView(download,0,0,null);
            }

            @Override
            public void onWaitingNetwork(@NotNull Download download) {
                //canceled on background thread
            }
        };
        fetch.addListener(fetchListener);
        download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (userUrl.getText().toString().equals("")) {
                    url = "https://www.google.co.in/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
                } else {
                    url = userUrl.getText().toString();
                }
                FetchConfiguration fetchConfiguration = new FetchConfiguration.Builder(MainActivity.this)
                        .setDownloadConcurrentLimit(3)
                        .build();
                MainActivity.this.fetch = Fetch.Impl.getInstance(fetchConfiguration);
                final String file = getfilepath(url);
                request = new Request(url, file);
                request.setPriority(Priority.HIGH);
                request.setNetworkType(NetworkType.ALL);
                MainActivity.this.fetch.enqueue(request, new Func<Request>() {
                    @Override
                    public void call(@NotNull Request result) {
                        Toast.makeText(MainActivity.this, "File is in Que", Toast.LENGTH_SHORT).show();
                    }
                }, new Func<Error>() {
                    @Override
                    public void call(@NotNull Error result) {
                        Toast.makeText(MainActivity.this, "Whoops Error Occurred", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }
    @NonNull
    public static String getfilepath(@NotNull final String string) {
        final String fileName = getFileName(string);
        final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/fetch/";
        return (dir+fileName);
    }

    public static String getFileName (@NotNull final String string) {
        final Uri uri = Uri.parse(string);
        return uri.getLastPathSegment();
    }

    private void SetProgressView(@NotNull final Status status, final int progress) {
        switch (status) {
            case QUEUED: {
                percentage.setText("IN QUE");
                break;
            }
            case ADDED: {
                percentage.setText("ADDED");
                break;
            }
            case DOWNLOADING:
            case COMPLETED: {
                if (progress== -1){
                    percentage.setText("DOWNLOADING");
                } else {
                    final String progresString = getResources().getString(R.string.percent_progress,progress);
                    percentage.setText(progresString);
                }
                break;
            }
            default:{
                percentage.setText("Status Unknown");
            }
        }
    }

    private void ShowDownloadError(@NotNull Error error) {
        Toast.makeText(this, error.toString(), Toast.LENGTH_SHORT).show();
    }

    private void UpdateView(@NotNull Download download, long eta, long speedKBPS, @Nullable Error error) {
        SetProgressView(download.getStatus(),download.getProgress());
        time.setText(Utils.getETA(this,eta));
        speed.setText(Utils.getSpeed(this,speedKBPS));
        if (error != null) {
            ShowDownloadError(download.getError());
        }
    }
}

但该应用无法运行,它显示以下错误:

Process: google.test1, PID: 4975
    java.lang.NullPointerException: Attempt to invoke interface method 'com.tonyodev.fetch2.Fetch com.tonyodev.fetch2.Fetch.addListener(com.tonyodev.fetch2.FetchListener)' on a null object reference
        at google.test1.MainActivity$2.onClick(MainActivity.java:135)
        at android.view.View.performClick(View.java:4781)
        at android.view.View$PerformClick.run(View.java:19907)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:160)
        at android.app.ActivityThread.main(ActivityThread.java:5541)
        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:964)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:759)

其次,当我尝试从此链接下载文件时,它总是弹出错误并且由于监听器不在那里而无法知道原因:

链接:http://speedtest.ftp.otenet.gr/files/test100Mb.db

还有来自logcat的错误:

Process: google.test1, PID: 4975
    java.lang.NullPointerException: Attempt to invoke interface method 'com.tonyodev.fetch2.Fetch com.tonyodev.fetch2.Fetch.addListener(com.tonyodev.fetch2.FetchListener)' on a null object reference
        at google.test1.MainActivity$2.onClick(MainActivity.java:135)
        at android.view.View.performClick(View.java:4781)
        at android.view.View$PerformClick.run(View.java:19907)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:160)
        at android.app.ActivityThread.main(ActivityThread.java:5541)
        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:964)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:759)

我正在使用最新版本的提取。

1 个答案:

答案 0 :(得分:2)

您似乎没有正确初始化Fetch对象。您试图使用该对象添加侦听器,但是您在侦听器内部进行了初始化。您必须先 初始化后才能使用变量。

 public class MainActivity extends AppCompatActivity {
 Fetch fetch;
 ...

 @Override
protected void onCreate(Bundle savedInstanceState) {
 //You need to initialize the instance BEFORE you add the listener. 
 FetchConfiguration fetchConfiguration = new FetchConfiguration.Builder(this)
            .setDownloadConcurrentLimit(3)
            .build();

    fetch = Fetch.Impl.getInstance(fetchConfiguration);

所有这些都位于您提供的link内的文档中:。