F.joel
F.joel

Reputation: 143

call input receiving Method inside on button click and use its values

I tried to find some solution but i did not find the working one i have two classes one is sysnctask class that download video file and it works fine // codes

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

private Context context;

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

@Override
protected void onPreExecute() {
    super.onPreExecute();
}
protected String doInBackground(String... f_url) {
    int count;
    try {
        URL url = new URL(f_url[0]);
        URLConnection conection = url.openConnection();
        conection.connect();

        int lenghtOfFile = conection.getContentLength();

        // download the file
        InputStream input = new BufferedInputStream(url.openStream(), 8192);
        Dominika_details  dominika_details= new Dominika_details();
        // Output stream
        OutputStream output = new FileOutputStream("/sdcard/"+YOUTUBE_ID);

        byte data[] = new byte[1024];

        long total = 0;

        while ((count = input.read(data)) != -1) {
            total += count;

            publishProgress(""+(int)((total*100)/lenghtOfFile));

            // writing data to file
            output.write(data, 0, count);
        }

        // flushing output
        output.flush();

        // closing streams
        output.close();
        input.close();

    } catch (Exception e) {
        Log.e("Error: ", e.getMessage());
    }

    return null;
}

protected void onProgressUpdate(String... progress) {
    // setting progress percentage
    }
@Override
protected void onPostExecute(String file_url) {
    // dismiss the dialog after the file was downloaded
     }
      }

The second one is activity "GetYoutubeUrl " that convert the youtube video id to the downloaded format

//codes

    public class GetYoutubeUrl extends AppCompatActivity {
private static final String YOUTUBE_ID = "3LiubyYpEUk";
private final YouTubeExtractor mExtractor = YouTubeExtractor.create();
private Callback<YouTubeExtractionResult> mExtractionCallback = new Callback<YouTubeExtractionResult>() {
    @Override
    public void onResponse(Call<YouTubeExtractionResult> call, Response<YouTubeExtractionResult> response) {
        bindVideoResult(response.body());
    }
    @Override
    public void onFailure(Call<YouTubeExtractionResult> call, Throwable t) {
        onError(t);
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_get_youtube_url);
    mExtractor.extract(YOUTUBE_ID).enqueue(mExtractionCallback);


    Button  download= (Button)findViewById(R.id.download);
    download.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {



        }
    });
}
private void onError(Throwable t) {
    t.printStackTrace();
    Toast.makeText(GetYoutubeUrl.this, "It failed to extract. So sad", Toast.LENGTH_SHORT).show();
}

private void bindVideoResult(YouTubeExtractionResult result) {
///  Here you can get download url link
    String video= String.valueOf(result.getSd360VideoUri());
    new DownloadFileAsync(this).execute(video);
}

}

In bindVideoResult method of GetYoutubeUrl activity i can call the asynctask class in and download the video very fine using "String video" value as input. what i want to accomplish is two things:

  1. In GetYoutubeUrl activity there is download button on clicklistener , so how can i call the asynctask class inside it and use the value "video " from bindVideoResult method so that i can download this video file only when the button is clicked.

2.How can I Assign every video id as the downloaded file name?,i mean in GetYoutubeUrl activity is where id "YOUTUBE_ID" introduced
so how can i take the name to the asyntask " OutputStream output = new FileOutputStream("/sdcard/"+YOUTUBE_ID);"

// logcat

W/dalvikvm: threadid=1: thread exiting with uncaught exception  (group=0x41ebd9c0)
    E/AndroidRuntime: FATAL EXCEPTION: main
              android.view.WindowManager$BadTokenException: Unable to add      window -- token null is not for an application
                   at   android.view.ViewRootImpl.setView(ViewRootImpl.java:650)
                  at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
                  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
                  at android.app.Dialog.show(Dialog.java:281)
                  at com.fredycom.myyoutube.DownloadFileAsync.onPreExecute(DownloadFileAsync.java:41)
                  at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
                  at android.os.AsyncTask.execute(AsyncTask.java:534)
                  at com.fredycom.myyoutube.GetYoutubeUrl$2.onClick(GetYoutubeUrl.java:43)
                  at android.view.View.performClick(View.java:4212)
                  at android.view.View$PerformClick.run(View.java:17476)
                  at android.os.Handler.handleCallback(Handler.java:800)
                  at android.os.Handler.dispatchMessage(Handler.java:100)
                  at android.os.Looper.loop(Looper.java:194)
                  at android.app.ActivityThread.main(ActivityThread.java:5371)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:525)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
                  at dalvik.system.NativeStart.main(Native Method)

I/Process: Sending signal. PID: 21771 SIG: 9 Application terminated.

Upvotes: 0

Views: 164

Answers (1)

Paresh
Paresh

Reputation: 6857

download this video file only when the button is clicked.

Declare String video as global variable. And call AsyncTask in button's onClick()

    download.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new DownloadFileAsync(this).execute(video);
        }
    });

How can I Assign every video id as the downloaded file name? Pass your YOUTUBE_VIDEO_ID as an argument of AsyncTask Argument -

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

    private Context context;
    private String youtubeId;

    public DownloadFileAsync(Context context, String youtubeId){
        this.context = context;
        this.youtubeId = youtubeId; // Use youtubeId as file name
    }

    .....
}

You will be calling asyncTask like -

new DownloadFileAsync(this, YOUTUBE_VIDEO_ID).execute(video);

Upvotes: 1

Related Questions