As far as I know you need to specify the types that the asynctask will work, pass the parameters in your asynctask.execute(the input type if not void is an array), and recover in doInBackground(Params...), where Params... is an array of the type you specified, then recover as an array, example String str = params[0];
Edited:
To simplify I’ll leave an example of my app
Pagetask is an interface I use to recover data:
package com.samuelives.videoplayer.system;
import java.util.ArrayList;
public interface PageTask {
public void finishDownload(ArrayList<String>data);
}
Pagedownloader is my Asynctask responsible for extracting data from a page:
package com.samuelives.videoplayer.system;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import android.util.Patterns;
import android.webkit.MimeTypeMap;
import android.webkit.URLUtil;
import com.samuelives.videoplayer.R;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import javax.net.ssl.HttpsURLConnection;
public class PageDownloader extends AsyncTask<String, String, ArrayList<String>>{
private PageTask mPt;
private Context mContext;
private ProgressDialog mProgress;
public PageDownloader(PageTask pt, Context context){
this.mPt = pt;
this.mContext = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
Log.i("Page Downloader", "Baixando pagina da web...");
mProgress = new ProgressDialog(mContext);
mProgress.setTitle(mContext.getResources().getString(R.string.pageDownloader_proDlgTitle));
mProgress.setMessage(mContext.getResources().getString(R.string.pageDownloader_proDlgInitialMessage));
mProgress.show();
}
@Override
protected ArrayList<String> doInBackground(String... strings) {
ArrayList<String>content = new ArrayList<>();
try{
Document page = null;
String ua = getUserAgent();
Connection.Response response = Jsoup.connect(strings[0]).userAgent(ua).execute();
if(testConnection(response)){
page = Jsoup.connect(strings[0]).userAgent(getUserAgent()).get();
String videoSrc = getVideoSource(page);
content.add(0, videoSrc);
content.add(1, getVideoTitle(page));
if(Patterns.WEB_URL.matcher(videoSrc).matches()){
content.add(2, getVideoMime(videoSrc));
}else{
content.add(2, "null");
}
}else{
content.add(0,"null");
content.add(1,"null");
content.add(2,"null");
}
}catch (IllegalArgumentException | IOException e){
Log.e("Could connect to page", e.getMessage());
}
return content;
}
@Override
protected void onPostExecute(ArrayList<String> strings) {
super.onPostExecute(strings);
mProgress.dismiss();
Log.i("Page Downloader", "Download completo");
Log.i("Video src", strings.get(0));
Log.i("Video title", strings.get(1));
Log.i("Video MIME", strings.get(2));
mPt.finishDownload(strings);
}
private boolean testConnection(Connection.Response response){
//Check if exist response of connection
if(response != null){
//Check if connection is OK
if(response.statusCode() != 200){
Log.e("Page downloader", "Failed to connect, Response Code: " + response.statusCode());
return false;
}else{
Log.i("Page downloader", "Connection OK");
return true;
}
}else{
Log.e("Page downloader", "Error, have not response of connection!");
return false;
}
}
private String getVideoSource(Document doc){
try {
Element videoSrc = doc.getElementsByTag("video").first();
Element sourceSrc = null;
if (videoSrc != null) {
if(videoSrc.attr("src") != null){
return videoSrc.attr("src");
}else{
sourceSrc = videoSrc.getElementsByTag("source").first();
if(sourceSrc != null){
if(sourceSrc.attr("src") != null){
return sourceSrc.attr("src");
}
}
}
}
}catch (NullPointerException e){
Log.e("Page downloader", "Failed to get source: " + e.getMessage());
}
return "null";
}
private String getVideoTitle(Document doc){
String title = "videoplayback";
try {
Element titleTag = doc.getElementsByTag("title").first();
if((titleTag != null) && (titleTag.text() != null)){
title = titleTag.text();
}
}catch (NullPointerException e){
Log.e("Page downloader", "Could get page title: " + e.getMessage());
}
return title;
}
private String getVideoMime(String input){
String mimeType = "null";
URL url = null;
try {
url = new URL(input);
if(URLUtil.isHttpsUrl(input)){
Log.d("Page downloader", "HTTPS Url source.");
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
con.setRequestProperty("User-Agent", getUserAgent());
String ct = con.getContentType();
if((ct.equals("text/html")) || (ct.equals("application/xhtml+xml")) || (ct.equals("text/php")) || (ct.equals("application/php")) || (ct.equals("application/x-php") || (ct.equals("text/x-php")))){
if(con.getHeaderField("Location") != null){
String urlLocation = con.getHeaderField("Location");
String extension = MimeTypeMap.getFileExtensionFromUrl(urlLocation);
if(extension != null){
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
}
}else{
mimeType = con.getContentType();
}
con.disconnect();
}else{
Log.d("Page downloader", "HTTPS Url source.");
HttpURLConnection con = (HttpsURLConnection)url.openConnection();
con.setRequestProperty("User-Agent", getUserAgent());
String ct = con.getContentType();
if((ct.equals("text/html")) || (ct.equals("application/xhtml+xml")) || (ct.equals("text/php")) || (ct.equals("application/php")) || (ct.equals("application/x-php") || (ct.equals("text/x-php")))){
if(con.getHeaderField("Location") != null){
String urlLocation = con.getHeaderField("Location");
String extension = MimeTypeMap.getFileExtensionFromUrl(urlLocation);
if(extension != null){
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
}
}else{
mimeType = con.getContentType();
}
con.disconnect();
}
}catch (NullPointerException | IOException e){
Log.e("Page downloader", "Could get mimetype: " + e.getMessage());
}
return mimeType;
}
private String getUserAgent(){
String ua = null;
boolean isTablet = mContext.getResources().getBoolean(R.bool.isTablet);
if(!isTablet){
ua = "Mozilla/5.0 (Linux; Android " + Build.VERSION.RELEASE + "; Mobile; rv: 41.0) Gecko/41.0 Firefox/41.0";
Log.d("User-Agent", ua);
}else{
ua = "Mozilla/5.0 (Linux; Android " + Build.VERSION.RELEASE + "; Tablet; rv: 41.0) Gecko/41.0 Firefox/41.0";
Log.d("User-Agent", ua);
}
return ua;
}
}
Note that when I Xting my class to Asynctask I specify the input and output parameters Note that String is the input parameter because it is a URL the second parameter is the data type for progress and Arraylist is the resulting data type with the extracted data that I recover onPostExecute for my interface.
And this is the fragment where I execute the asynctask:
package com.samuelives.videoplayer.fragments;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.preference.PreferenceManager;
import android.util.Log;
import android.util.Patterns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.samuelives.videoplayer.R;
import com.samuelives.videoplayer.player.Player;
import com.samuelives.videoplayer.system.PageDownloader;
import com.samuelives.videoplayer.system.PageTask;
import java.util.ArrayList;
import static android.content.Context.CONNECTIVITY_SERVICE;
public class MainFragment extends Fragment implements PageTask{
private Button btnOpenUrl = null;
private EditText etInputUrl = null;
private PageDownloader mPageDownloader = null;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mPageDownloader = new PageDownloader(this, getActivity());
btnOpenUrl.setOnClickListener(btnListener);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View layout = inflater.inflate(R.layout.fragment_main, container, false);
etInputUrl = (EditText)layout.findViewById(R.id.etInputUrl);
btnOpenUrl = (Button)layout.findViewById(R.id.btnOpenUrl);
return layout;
}
private View.OnClickListener btnListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if(etInputUrl.getText().toString() != null){
if(Patterns.WEB_URL.matcher(etInputUrl.getText().toString()).matches()){
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if((activeNetwork != null) && (activeNetwork.isConnectedOrConnecting())){
processUrl(etInputUrl.getText().toString());
}else{
Toast.makeText(getActivity(), R.string.toastConnectionOffline, Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(getActivity(), R.string.toastInvalidUrl, Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(getActivity(), getResources().getString(R.string.toastEmptyUrl), Toast.LENGTH_LONG).show();
}
}
};
@Override
public void finishDownload(ArrayList<String> data) {
if((data.get(0) != null) && (data.get(0).equals("null")) && (Patterns.WEB_URL.matcher(data.get(0)).matches())) {
Intent it = new Intent(getActivity(), Player.class);
it.putExtra("videoSrc", data.get(0));
it.putExtra("videoTitle", data.get(1));
it.putExtra("videoMime", data.get(2));
startActivity(it);
}else{
Toast.makeText(getActivity(), R.string.toastNoContent, Toast.LENGTH_LONG).show();
}
}
private void processUrl(String url){
if(isWatchOnlyWifi()){
if(!connectionIsWifi()){
Toast.makeText(getActivity(), getResources().getString(R.string.toastOnlyWatchWifi), Toast.LENGTH_LONG).show();
return;
}else{
if(!url.isEmpty()) {
if (url.contains(".mp4") || url.contains(".3gp") || url.contains(".ogv")) {
Intent it = new Intent(getActivity(), Player.class);
it.putExtra("videoTitle", "Video Playback");
it.putExtra("videoSrc", url);
startActivity(it);
} else {
mPageDownloader = new PageDownloader(this, getActivity());
mPageDownloader.execute(url);
}
}else{
Toast.makeText(getActivity(), getResources().getString(R.string.toastEmptyUrl), Toast.LENGTH_LONG).show();
}
}
}else {
if(!url.isEmpty()) {
if (url.contains(".mp4") || url.contains(".3gp") || url.contains(".ogv")) {
Intent it = new Intent(getActivity(), Player.class);
it.putExtra("videoTitle", "Video Playback");
it.putExtra("videoSrc", url);
startActivity(it);
} else {
mPageDownloader = new PageDownloader(this, getActivity());
mPageDownloader.execute(url);
}
}else{
Toast.makeText(getActivity(), getResources().getString(R.string.toastEmptyUrl), Toast.LENGTH_LONG).show();
}
}
}
private boolean isWatchOnlyWifi(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
return prefs.getBoolean("pref_key_is_watch_only_wifi", false);
}
private boolean connectionIsWifi(){
try {
ConnectivityManager manager = (ConnectivityManager) getActivity().getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (info.isConnected()) {
return true;
} else {
return false;
}
}catch (NullPointerException e){
Log.e("Main", "Error: " + e.getMessage());
}
return false;
}
}
I pass the parameters and run the task with execute() where the input value is an array of the type you specified, when the task finishes the method of my interface I am implementing finishDownload(ArrayList<String> data)
is called retrieving the data, that’s it, it doesn’t have much secret, I took a while to understand the functioning too.
This video helped me a lot to understand asynctask.
In the Controlbank class that is responsible for access to the bd has a method that returns this array of objects, so in Asynctask I call this method but by the way this object does not arrive complete there always passes only the first index that is user [0]. If I call this method in my Activity to pass users as parameter in asynctask can lock the app when the bank has many users. I need to carry them from Async even. But thanks for answering.
– Gustavo Almeida Cavalcante
@Gustavoalmeidacavalcante I put an example of Asynctask from my app for you to understand better.
– Samuel Ives
Thank you, but I’ve solved it.
– Gustavo Almeida Cavalcante