doInBackground of asyncTask not getting called? - java

In my app, when I call new RetrieveFirstThreeArtUrl().execute() doInBackground isn't getting called.. does anyone know why? This code was working a few days ago, so I have no idea what's going on..
public class RetrieveFirstThreeArtUrl extends AsyncTask<String, Void, Void> {
static final String APIURL = "http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=2ead17554acf667f27cf7dfd4c368f15&artist=%s&album=%s";
static final String APIURL_ARTIST = "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&api_key=2ead17554acf667f27cf7dfd4c368f15&artist=%s";
#Override
public void onPreExecute() {
super.onPreExecute();
Log.v("", "Pre");
}
#Override
public Void doInBackground(String... args) {
Log.v("", "Background");
return null;
}
#Override
public void onPostExecute(Void args) {
list = (ListView) rootView.findViewById(R.id.list);
adapter = new LiveAdapter(LiveStreamFragment.this.getActivity(), oslist, LiveStreamFragment.this, list);
list.setAdapter(adapter);
}
}

Replace your code with this
before calling RetrieveFirstThreeArtUrl method, write these two lines
static final String APIURL = "http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=2ead17554acf667f27cf7dfd4c368f15&artist=%s&album=%s";
static final String APIURL_ARTIST = "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&api_key=2ead17554acf667f27cf7dfd4c368f15&artist=%s";
And than call method RetrieveFirstThreeArtUrl, one more thing, use protected instead of public
public class RetrieveFirstThreeArtUrl extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.v("", "Pre");
}
#Override
protected void onPostExecute(Void result) {
list = (ListView) rootView.findViewById(R.id.list);
adapter = new LiveAdapter(LiveStreamFragment.this.getActivity(), oslist, LiveStreamFragment.this, list);
list.setAdapter(adapter);
}
#Override
protected Void doInBackground(String... params) {
Log.v("", "Background");
return null;
}
}

Related

Android: AsyncTask Object[] cannot be cast in doInBackground

So, I'm trying to run the simplest AsyncTask possible: it doesn't accept parameters, it just runs a function, gets the result string and displays is. And no matter what I try, I get this error:
java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.lang.Void[] at (...)$AsyncTaskRunner.doInBackground
The AsyncTask:
private class AsyncTaskRunner extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
resultText.setText("");
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(Void... params) {
return "test";
}
#Override
protected void onPostExecute(String result) {
progressBar.setVisibility(View.GONE);
resultText.setText(result);
}
}
And this is how I call it:
buttonCalculate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (AsyncTaskRunner != null) {
AsyncTaskRunner.cancel(true);
}
AsyncTaskRunner = new AsyncTaskRunner();
AsyncTaskRunner.execute();
}
});
What am I doing wrong here?
OK, so curiously it works if I call it like this:
AsyncTask<Void, Void, String> asyncTaskRunner = new AsyncTaskRunner();
asyncTaskRunner.execute();

Handling AsyncTask warning class should be static or leaks might occur

I have created as asynctask to upload data to a server as below. But it shows this warning.
This AsyncTask class should be static or leaks might occurs......
I have read and tried the weak reference style but i cant be able to integrate in this code.
How can I get rid of this warning in the code below?.
public void ImageUploadToServerFunction(){
final String imageName1 = GetImageNameEditText1.trim();
final String userName = GetUserName.trim();
final String imageView1 = getStringImage1(bitmap1);
class AsyncTaskUploadClass extends AsyncTask<Void,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(UploadActivity.this,"Your Data is Uploading....",false,false);
}
#Override
protected void onPostExecute(String string1) {
super.onPostExecute(string1);
progressDialog.dismiss();
}
#Override
protected String doInBackground(Void... params) {
ImageProcessClass imageProcessClass = new ImageProcessClass();
HashMap<String,String> HashMapParams = new HashMap<>();
HashMapParams.put(ImageName1, imageName1);
HashMapParams.put(UserName, userName);
HashMapParams.put(ImagePath1, imageView1);
return imageProcessClass.ImageHttpRequest(ServerUploadPath, HashMapParams);
}
}
AsyncTaskUploadClass AsyncTaskUploadClassOBJ = new AsyncTaskUploadClass();
AsyncTaskUploadClassOBJ.execute();
}
If you're executing this in the context of a function, you need to make your AsyncTask anonymous. Something like:
public void ImageUploadToServerFunction(){
final String imageName1 = GetImageNameEditText1.trim();
final String userName = GetUserName.trim();
final String imageView1 = getStringImage1(bitmap1);
new AsyncTask<Void,Void,String>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(UploadActivity.this,"Your Data is Uploading....",false,false);
}
#Override
protected void onPostExecute(String string1) {
super.onPostExecute(string1);
progressDialog.dismiss();
}
#Override
protected String doInBackground(Void... params) {
ImageProcessClass imageProcessClass = new ImageProcessClass();
HashMap<String,String> HashMapParams = new HashMap<>();
HashMapParams.put(ImageName1, imageName1);
HashMapParams.put(UserName, userName);
HashMapParams.put(ImagePath1, imageView1);
return imageProcessClass.ImageHttpRequest(ServerUploadPath,HashMapParams);
}
}.execute();
}
But I highly recommend not using AsyncTask in Android anymore. It's a very dirty way to do asynchronous operations and it rightfully should be deprecated. A better way to solve this would be with RxJava.

Simple Todo android app with mlab dont add or edit

I created an application with android studio and connected it to mLab, the application is a simple task list (toDo App). I can see perfectly the records of the mLab database. The problem is that I can not edit or create new records. Deleting works perfects, If I delete them, they are removed from the app and mLab. I do not see any visible error.
Anyone can help me to spot the error?
i leave here the repo from my project TodoApp
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView lstViewItems;
Button btnAdd, btnEdit, btnDelete;
EditText edtItem;
item itemSelected=null;
List<item> items = new ArrayList<item>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstViewItems = (ListView)findViewById(R.id.lstView);
btnAdd = (Button)findViewById(R.id.btnAddItem);
btnEdit = (Button)findViewById(R.id.btnEdit);
btnDelete = (Button)findViewById(R.id.btnDelete);
edtItem = (EditText) findViewById(R.id.edtItem);
//LOAD DATA WHEN APP OPENED
new GetData().execute(Common.getAddressAPI());
lstViewItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
itemSelected = items.get(position);
//SET TEXT TO EDIT TEXT
edtItem.setText(itemSelected.getItem());
}
});
//ADD EVENT TO BUTTON
btnAdd.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
new PostData(edtItem.getText().toString()).execute(Common.getAddressAPI());
}
});
//BECAUSE THIS FUNCTION WE NEED PARAMETER ITEMSELECTED, SO WE NEED SET ITEMSELECTED
//WHEN USER CLICK ON ITEM IN LISTVIEW
btnEdit.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
}
});
btnDelete.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
new DeleteData(itemSelected).execute(Common.getAddressSingle(itemSelected));
}
});
}
//FUNCTION PROCESS DATA
class GetData extends AsyncTask<String, Void, String>{
ProgressDialog pd = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute(){
super.onPreExecute();
//Pre process
pd.setTitle("Please wait...");
pd.show();
}
#Override
protected String doInBackground(String... params){
// RUNNING PROCCESS..
String stream = null;
String urlString = params[0];
HTTPDataHandler http = new HTTPDataHandler();
stream = http.GetHTTPData(urlString);
return stream;
}
#Override
protected void onPostExecute(String s){
super.onPostExecute(s);
//Done process
//WE WILL USE GSON TO PARSE JSON TO CLASS
Gson gson = new Gson();
Type listType = new TypeToken<List<item>>(){}.getType();
items=gson.fromJson(s,listType); // PARSE TO LIST
CustomAdapter adapter = new CustomAdapter(getApplicationContext(),items); // CREATE ADAPTER
lstViewItems.setAdapter(adapter); // SET ADAPTER TO LIST VIEW
pd.dismiss();
}
}
// FUNCTION TO ADD NEW ITEM
class PostData extends AsyncTask<String,String,String> {
ProgressDialog pd = new ProgressDialog(MainActivity.this);
String item;
public PostData(String item){
this.item = item;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd.setTitle("Please wait...");
pd.show();
}
#Override
protected String doInBackground(String... params) {
String urlString = params[0];
HTTPDataHandler hh = new HTTPDataHandler();
String json="(\"item\":\""+item+"\")";
hh.PostHTTPData(urlString,json);
return "";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//REFRESH DATA
new GetData().execute(Common.getAddressAPI());
pd.dismiss();
}
}
// FUNCTION TO EDIT ITEM
class PutData extends AsyncTask<String,String,String> {
ProgressDialog pd = new ProgressDialog(MainActivity.this);
String item;
public PutData(String item){
this.item = item;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd.setTitle("Please wait...");
pd.show();
}
#Override
protected String doInBackground(String... params) {
String urlString = params[0];
HTTPDataHandler hh = new HTTPDataHandler();
String json="(\"item\":\""+item+"\")";
hh.PutHTTPData(urlString,json);
return "";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//REFRESH DATA
new GetData().execute(Common.getAddressAPI());
pd.dismiss();
}
}
// FUNCTION TO DELETE ITEM
class DeleteData extends AsyncTask<String,String,String> {
ProgressDialog pd = new ProgressDialog(MainActivity.this);
item item;
public DeleteData(item item){
this.item = item;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd.setTitle("Please wait...");
pd.show();
}
#Override
protected String doInBackground(String... params) {
String urlString = params[0];
HTTPDataHandler hh = new HTTPDataHandler();
String json="(\"item\":\""+item.getItem()+"\")";
hh.DeleteHTTPData(urlString,json);
return "";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//REFRESH DATA
new GetData().execute(Common.getAddressAPI());
pd.dismiss();
}
}
}
}
The first error is that you are sending a wrong json format so you need to change it to the right format, second you are indexing the id variable but you are noting sending it. change your json variable in the post method to :
String json = "{'item' :'" + item + "', 'id' : '"+ UUID.randomUUID().toString() +"'}";

Getting an Arraylist from an inner AsyncTask class

I've parsed some XML Data in Asynctask and printed it in the log, but whenever I try to copy the ArrayList of data into my Activity, it always remains null.
Here's the code,
public class MainActivity extends AppCompatActivity {
static ArrayList<NewsItems>myData=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ReadRss readRss = new ReadRss(this);
readRss.execute();
Log.d("TAG", String.valueOf(myData.size()));//This stays empty
}
public static void getData(ArrayList<NewsItems>items){
for (int i=0; i<items.size(); i++){
myData.add(items.get(i));
}
}
class ReadRss extends AsyncTask<Void, Void, Void>{
ArrayList<NewsItems>feedItems = new ArrayList<>();
Context context;
String address = "http://www.thedailystar.net/frontpage/rss.xml";
ProgressDialog progressDialog;
URL url;
public ReadRss(Context context) {
this.context = context;
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Loading...");
}
#Override
protected void onPreExecute() {
if(progressDialog!=null){
if (!progressDialog.isShowing()){
progressDialog.show();
}
}
super.onPreExecute();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(progressDialog!=null){
if (progressDialog.isShowing()){
progressDialog.hide();
}
}
MainActivity.getData(feedItems);
}
#Override
protected Void doInBackground(Void... params) {
ProcessXml(Getdata());
return null;
}
private void ProcessXml(Document data) {
if (data != null) {
Element root = data.getDocumentElement();
Node channel = root.getChildNodes().item(1);
NodeList items = channel.getChildNodes();
for (int i = 0; i < items.getLength(); i++) {
Node currentchild = items.item(i);
if (currentchild.getNodeName().equalsIgnoreCase("item")) {
NewsItems item=new NewsItems();
NodeList itemchilds = currentchild.getChildNodes();
for (int j = 0; j < itemchilds.getLength(); j++) {
Node current = itemchilds.item(j);
if (current.getNodeName().equalsIgnoreCase("title")){
item.setTitle(current.getTextContent());
}else if (current.getNodeName().equalsIgnoreCase("description")){
item.setDescription(current.getTextContent());
}else if (current.getNodeName().equalsIgnoreCase("media:thumbnail")){
item.setMedia(current.getAttributes().getNamedItem("url").getTextContent());
}else if (current.getNodeName().equalsIgnoreCase("link")){
item.setUrl(current.getTextContent());
}
}
feedItems.add(item);
Log.d("itemTitle", item.getTitle());
Log.d("itemDescription",item.getDescription());
Log.d("itemMediaLink",item.getMedia());
Log.d("itemLink",item.getUrl());
}
}
}
}
public Document Getdata() {
try {
url = new URL(address);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream inputStream = connection.getInputStream();
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDoc = builder.parse(inputStream);
return xmlDoc;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
}
I tried calling a static method of the Activity in the onPostExecute method, it doesn't work.
1) You should declare the ArrayList variable as a member of mainActivity and then pass its reference into the Asynctask.
2) You can verify that the data is present in the list, only after you are sure the Asynctask has completed processing. (You can do that within the onPostExecute of the AsyncTask).
public class MainActivity extends AppCompatActivity {
ArrayList<NewsItems>myData=new ArrayList<>(); //No need for static
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ReadRss readRss = new ReadRss(this,myData); //Pass the list variable reference into the asynctask instance
readRss.execute();
Log.d("TAG", String.valueOf(myData.size()));//This will be empty due to concurrent call to asynctask, which executes parallel to main thread.
}
public void getData(ArrayList<NewsItems>items){//Static qualifier unneccessary here
for (int i=0; i<items.size(); i++){
myData.add(items.get(i));
}
}
class ReadRss extends AsyncTask<Void, Void, Void>{
ArrayList<NewsItems>feedItems = new ArrayList<>();
Context context;
String address = "http://www.thedailystar.net/frontpage/rss.xml";
ProgressDialog progressDialog;
URL url;
public ReadRss(Context context,ArrayList<NewsItems> feedItems) {
this.context = context;
this.feedItems = feedItems; //Assign the reference of the list here so that modifications done within the Asynctask are reflected in the MainActivity
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Loading...");
}
#Override
protected void onPreExecute() {
if(progressDialog!=null){
if (!progressDialog.isShowing()){
progressDialog.show();
}
}
super.onPreExecute();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(progressDialog!=null){
if (progressDialog.isShowing()){
progressDialog.hide();
}
}
//Do whatever you need with the arraylist data here
getData(feedItems);
}
#Override
protected Void doInBackground(Void... params) {
ProcessXml(Getdata());
return null;
}
Avoid static variables as much as possible. Unnecessary static fields land you into problems hard to understand.
If you are populating it in an AdapterView like ListView, remember to call adapter.notifyDataSetChanged() when you have the data set ready with you.
You can actually pass the result of your doInBackground() to onPostExecute() to continue doing your work on the calling thread, which is the main thread in your case.
new AsyncTask<Void, Void, ArrayList<NewsItems>>() {
#Override
protected ArrayList<NewsItems> doInBackground(Void... params) {
ArrayList<NewsItems> response = whatEverMethodGetsMeNetworkCallResponse();
return response;
}
#Override
protected void onPostExecute(ArrayList<NewsItems> response) {
super.onPostExecute(response);
// Do whatever you want to do with the network response
}
}.execute();
Or you can even set up listeners and do it in a more sophisticated way like:
onCreate() {
...
getNewsItems(new NewsItemsListener() {
void onFetched(ArrayList<NewsItems> items) {
// Do whatever you want to do with your news items
}
});
}
public void getNewsItems(final NewsItemsListener listener)
new AsyncTask<Void, Void, ArrayList<NewsItems>>() {
#Override
protected ArrayList<NewsItems> doInBackground(Void... params) {
ArrayList<NewsItems> response = whatEverMethodGetsMeNetworkCallResponse();
return response;
}
#Override
protected void onPostExecute(ArrayList<NewsItems> response) {
super.onPostExecute(response);
listener.onFetched(response);
}
}.execute();
}
public interface NewsItemsListener {
void onFetched(ArrayList<NewsItems> items);
}

AsyncTask onPostExecute listener [duplicate]

This question already has answers here:
how to return result from asyn call
(2 answers)
Closed 7 years ago.
Activity.java
//Activity stuff
MyClass mc = new MyClass();
mc.getText();
public void dosomething() {
textview.setText(mc.getText());
}
MyClass.java
class MyClass {
String text;
public void setText() {
class GetTextFromWEB extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String url = urls[0];
String output;
//Getting text from web
return output;
}
#Override
protected void onPostExecute(String _text) {
text = _text;
}
}
String url = "google.com";
//Doing with url something
new GetText().execute(url);
}
public String getText() {return text;}
}
Promblem is - in activity setText do faster, then AsyncTask do it's job.
So when setText run, it's run like setText(null)
I need to check in activity, is asynk ended, so i have my text to set.
I hope i explained it
And i don't even need exactly AsyncTask, i need jsoup working, so if there is solution with another thread-class, with which jsoup will work, i can use it
Edit
class GetLyrics extends AsyncTask<String, Void, String> { //Class for getting lyrics
private Context con;
public GetLyrics(Context con) {
this.con = con;
}
#Override
protected String doInBackground(String... urls) {
//do something
}
#Override
protected void onPostExecute(String _lyrics) {
lyrics = _lyrics;
con.runOnUiThread(new Runnable() {
#Override
public void run() {
((TextView) findViewById(R.id.lyricsOutput)).setText(lyrics);
}
});
}
}
Call the method setting your text in the postExecute inside your AsyncTask or set the text directly on your postExecute method.
And wrap the line with setText() inside runOnUIThread (otherwise you will get an exception saying that the view can be accessed only by the thread that created it, since you are setting the text from async task).
Setting the text would be something like this
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
((TextView) findViewById(R.id.txtFieldName)).setText("your text");
}
});
That way you can quit worrying about checking if the async task is finished. But avoid doing complex ui operations like this. Since this is just setting the text on TextView, it should be allright.
1: Make my first project from my previous post and add some new lines in it to get data from http: api's.
public class Example extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_example);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("parameter1", "xyz"));
params.add(new BasicNameValuePair("parameter2", "abc"));
params.add(new BasicNameValuePair("parameter3", "opqr"));
ServerConnection task = new ServerConnection(this, new ResultListener() {
#Override
public void result(String response) {
Toast.make(this, response, Toast.LENGTH_LONG).show();
}
#Override
public void loader(boolean visble) {
}
#Override
public void connectionLost(String error) {
Toast.make(this, error, Toast.LENGTH_LONG).show();
}
});
}
public class ServerConnection extends AsyncTask<String, String, String> implements Constant {
ResultListener listener;
private String Method = "GET";
private List<NameValuePair> params = new ArrayList<NameValuePair>();
private Context context;
private ConnectionDetector cd;
// public static Drawable drawable;
public ServerConnection(Context context, ResultListener r) {
this.context = context;
this.listener = r;
cd = new ConnectionDetector(context);
this.execute();
}
public boolean isConnection() {
return cd.isConnectingToInternet();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
if (!isConnection()) {
cancel(true);
return "Sorry!connection lost,try again or later";
}
ApiResponse air = new ApiResponse();
System.out.println("working hre" + "hi");
String json;
try {
json = air.makeHttpRequest(URL, getMethod(), getParams());
} catch (Exception e) {
json = e.getMessage();
cancel(true);
return json;
}
return json;
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCancelled(String result) {
listener.connectionLost(result);
rl.connectionLost("Sorry!connection lost,try again or later");
super.onCancelled(result);
}
#Override
protected void onPostExecute(String result) {
System.out.println("onpost" + result);
listener.result(result);
listener.loader(true);
super.onPostExecute(result);
}
public String getMethod() {
return Method;
}
public void setMethod(String method) {
Method = method;
}
public List<NameValuePair> getParams() {
return params;
}
public void setParams(List<NameValuePair> params) {
this.params = params;
}
}
Example

Categories

Resources