Other class:
SpotifyTask st = new SpotifyTask(new Closure<JSONObject>() {
#Override
public void executeOnSuccess(JSONObject result) {
track.setJson(result);
}
});
st.execute("asd");
Being SpotifyTask:
public class SpotifyTask extends AsyncTask<Object, Void, JSONObject> {
private final Closure<JSONObject> closure;
public SpotifyTask(Closure<JSONObject> closure) {
this.closure = closure;
}
public static void getTrack(Closure<JSONObject> closure) {
new SpotifyTask(closure).execute("asd");
}
#Override
protected JSONObject doInBackground(Object... params) {
JSONObject result = null;
SpotifyCall spcall = new SpotifyCall();
try {
result = spcall.getTrack();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(JSONObject result) {
System.out.println("ASD: on post execute "+result);
closure.executeOnSuccess(result);
}
}
So... doInBackground is running OK, and and returning a JSONObject all right; I know because Im debbuging it and "result" IS a JSONObject.
But onPostExecute is never executed, the debugger never gets there and "ASD: on postexecute "+result is never logged.
Any suggestions?
Thanks in advance!
The problem was that I was "holding" the UI Thread:
this.status = "loading";
final Track track = new Track();
SpotifyTask.getTrack(new Closure<JSONObject>() {
#Override
public void executeOnSuccess(JSONObject result) {
track.setJson(result);
}
});
while (this.status.equals("loading")) {
if (track.getJson() != null) {
this.trackUno = track.getJson();
this.status = "ready";
} else {
try {
System.out.println("Not ready, waiting.");
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
As soon I removed the while block, it worked perfectly.
I would have to find another way to "wait" for the call to be complete.
Thanks for your time fellas!
Related
I am having a problem which is I think that I can't access th,e ListView from the asyncTask
Actually, I really don't know the real problem here
Let me show you what is happening
I have an activity which is executing AsyncTask and creates HttpURLConnection. Sometimes I get an exception (ProtocolException) because the stream un-expectedly ends.
So, I created a handler for this exception that calls a function or a method inside the class of the activity to display a message to the user
Here is a picture so you understand what is my project.
image
the problem here whenever the exception is thrown, the same function/method that I use to add the text to the listView is called, but after it called the listView disappear, but when I minimize the soft keyboard manually the everything becomes fine.
the structure of my class is
public class MainActivity extends AppCompatActivity
{
protected void onCreate(Bundle savedInstanceState)
{
addMessageToListView()//works fin here
}
protected void addMessage(String message, int userMessage, ListView listView) // the function
{
try
{
messages.add(new Message(message,userMessage));
MessagesAdapter messagesAdapter = new MessagesAdapter(messages, getBaseContext());
messagesAdapter.notifyDataSetChanged();
listView.setAdapter(messagesAdapter);
}
catch (Exception exception)
{
}
}
private class HttpPostAsyncTask extends AsyncTask<String, Void, String>
{
...
#Override
protected void onPostExecute(String result)
{
try
{
addMessageToListView()//works fin here
}
catch (Exception exception)
{
}
}
protected String doInBackground(String... params)
{
String result = "";
for (int i = 0; i <= 0; ++i)
{
result = this.invokePost(params[i], this.postData);
}
return result;
}
private String invokePost(String requestURL, HashMap<String, String> postDataParams)// called from doInBackground
{
try
{
addMessageToListView()//works fin here
}
catch (Exception exception)
{
addMessageToListView()//not orking here
}
}
}
}
I don't know how to explain more actually.
You can change Views only in mainthread of your app. The doInBackground doesn't run in mainthread of your app.
Solved by adding:
new Thread()
{
#Override
public void run()
{
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
addMessageToListView()//not orking here
}
});
super.run();
}
}.start();
Editing the previous code in my question:
public class MainActivity extends AppCompatActivity
{
protected void onCreate(Bundle savedInstanceState)
{
addMessageToListView()//works fin here
}
protected void addMessage(String message, int userMessage, ListView listView) // the function
{
try
{
messages.add(new Message(message,userMessage));
MessagesAdapter messagesAdapter = new MessagesAdapter(messages, getBaseContext());
messagesAdapter.notifyDataSetChanged();
listView.setAdapter(messagesAdapter);
}
catch (Exception exception)
{
}
}
private class HttpPostAsyncTask extends AsyncTask<String, Void, String>
{
...
#Override
protected void onPostExecute(String result)
{
try
{
addMessageToListView()//works fin here
}
catch (Exception exception)
{
}
}
protected String doInBackground(String... params)
{
String result = "";
for (int i = 0; i <= 0; ++i)
{
result = this.invokePost(params[i], this.postData);
}
return result;
}
private String invokePost(String requestURL, HashMap<String, String> postDataParams)// called from doInBackground
{
try
{
addMessageToListView()//works fin here
}
catch (Exception exception)
{
new Thread()
{
#Override
public void run()
{
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
addMessageToListView()//not orking here
}
});
super.run();
}
}.start();
}
}
}
}
I am writing a programm that returns me a ArrayList of Strings. Problem is, when I call the method the list is not filled yet so I get an empty list back .
I tried it with a thread but now I get a null reference when I call the method. By the way i had to implement a async task, otherwise I get an exception when trying to use InetAddress.
private class DeviceManager extends Thread {
private ArrayList<String> deviceList;
private String networkIP;
public DeviceManager(String networkIP) {
this.networkIP = networkIP;
}
public void run() {
getDeviceList();
}
public ArrayList<String> getDeviceList() {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
deviceList = new ArrayList<String>();
InetAddress address;
Log.i("NetworkIPgetDeviceList", networkIP);
String deviceIP = networkIP;
for (int i = 0; i < 255; i++) {
address = InetAddress.getByName(deviceIP += "" + i);
if (address.isReachable(2000)) {
Log.i("Devicefound", deviceIP);
deviceList.add(deviceIP);
}
deviceIP = networkIP;
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}.execute();
return deviceList;
}
public ArrayList<String> getList() {
return this.deviceList;
}
}
Artur what you are doing in your code is starting a thread to retrieve device list and then another thread(AsyncTask) to actually creates the device list. So you have three threads running here simultaneously (assuming you are using DeviceManager class in UIThread). The reason getDeviceList() is returning null is because AsyncTasks doInBackground hasn't run yet to collect your device list it might be waiting for its chance to get scheduled. so to conclude that, you just need one thread(other than UIThread), it can either be a Thread or AsyncTask (more preferable as it gives better control) as rusted brain has used in his answer. I prefer to make DeviceManager as AsyncTask (just a bit cleaner and if device managers only task is to retrieve device list) as code below.
in AsyncTask doInBackground runs in a background thread(as name suggests) and onPostExecute runs on the UI thread after doInBackground
class DeviceManager extends AsyncTask<String, Void, List<String>> {
private ConnectionCompleteListener listener;
public interface ConnectionCompleteListener {
void onSuccess(List<String> deviceList);
// if you need to know reason for failure you can add
// parameter to onFailure
void onFailure();
}
public DeviceManager(ConnectionCompleteListener listener) {
this.listener = listener;
}
#Override
protected List<String> doInBackground(String... params) {
List<String> deviceList = new ArrayList<>();
String networkIP = params[0];
try {
InetAddress address;
Log.i("NetworkIPgetDeviceList", networkIP);
String deviceIP = networkIP;
for (int i = 0; i < 255; i++) {
address = InetAddress.getByName(deviceIP += "" + i);
if (address.isReachable(2000)) {
Log.i("Devicefound", deviceIP);
deviceList.add(deviceIP);
}
deviceIP = networkIP;
}
} catch (IOException e) {
deviceList = null;
e.printStackTrace();
}
return deviceList;
}
#Override
protected void onPostExecute(List<String> deviceList) {
if (deviceList == null) {
this.listener.onFailure();
} else {
this.listener.onSuccess(deviceList);
}
}
}
so in your activity you can call
new DeviceManager(new DeviceManager.ConnectionCompleteListener
() {
#Override
public void onSuccess(List<String> deviceList) {
}
#Override
public void onFailure() {
}
}).execute("YOUR_NETWORK_IP");
You are doing it completely wrong. A Thread runs in the background and so does AsyncTask, so basically you are making a background task run in background. Inception.
Try this:
public class DeviceManager {
private ArrayList<String> deviceList;
private String networkIP;
private ConnectionCompleteListener listener;
public interface ConnectionCompleteListener {
void onSuccess();
void onFailure();
}
public void setConnectionCompleteListener(ConnectionCompleteListener listener) {
this.listener = listener;
}
public DeviceManager(String networkIP) {
this.networkIP = networkIP;
}
public void getDeviceList() {
new AsyncTask<Void, Void, Boolean>() {
#Override
protected void onPostExecute(Boolean result) {
if(result) listener.onSuccess();
else listener.onFailure();
}
#Override
protected Boolean doInBackground(Void... params) {
try {
deviceList = new ArrayList<String>();
InetAddress address;
Log.i("NetworkIPgetDeviceList", networkIP);
String deviceIP = networkIP;
for (int i = 0; i < 255; i++) {
address = InetAddress.getByName(deviceIP += "" + i);
if (address.isReachable(2000)) {
Log.i("Devicefound", deviceIP);
deviceList.add(deviceIP);
}
deviceIP = networkIP;
}
return true;
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return null;
}
}.execute();
}
public ArrayList<String> getList() {
return this.deviceList;
}
}
Then in your other class:
private class classname{
DeviceManager manager=new DeviceMnager(networkIp);
manger.setConnectionCompleteListener(new DeviceManager.ConnectionCompleteListener() {
#Override
public void onSuccess() {
// get your list here
manager.getList();
}
#Override
public void onFailure() {
// connection failed show error
}
});
}
You are getting empty array list because as you are using async task for getting array list and async task doINBackground method runs on different thread(means not on main thread). So when your program runs then your program doesn't wait for async task response.
You can solve this like that...
Use onPostExecute method in async task class and return the arraylist
#Override
protected void onPostExecute(Void result) {
//return array list here
getList();
}
Hope this will help you
First of All you don't need to make DeviceManager a thread as the task which you are running in getDeviceList will start in another new thread. Second You shouldn't wait on main(UI) thread so instead of waiting callback is a better mechanism.
If you insist on the same code try this..
public class DeviceManager extends Thread {
private ArrayList<String> deviceList;
private String networkIP;
private boolean dataAvailable;
public DeviceManager(String networkIP) {
this.networkIP = networkIP;
}
public void run() {
getDeviceList();
}
public ArrayList<String> getDeviceList() {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
deviceList = new ArrayList<String>();
InetAddress address;
Log.i("NetworkIPgetDeviceList", networkIP);
String deviceIP = networkIP;
for (int i = 0; i < 255; i++) {
System.out.println("checking " + i);
address = InetAddress.getByName(deviceIP += "" + i);
if (address.isReachable(2000)) {
Log.i("Devicefound", deviceIP);
deviceList.add(deviceIP);
}
deviceIP = networkIP;
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
dataAvailable = true;
synchronized (DeviceManager.this) {
DeviceManager.this.notify();
}
return null;
}
}.execute();
return deviceList;
}
synchronized public ArrayList<String> getList() {
while (!dataAvailable) {
try {
wait();
} catch (InterruptedException e) {
}
}
return this.deviceList;
}
}
How can you call a method within an AsyncTask? In my asynctask,which is an inner class in my java file 'xyz', when the user clicks a button, it should call a method within 'xyz' which also happens to be an alertDialog, i know it calls it, but when it reaches the method, the app crashes and gives a runtime exception, which says 'Can't create handler inside thread that has not called Looper.prepare()'. I looked up examples here but it threw the same runtime exception. How can i make it work? isn't calling an outer method from within the asynctask a possibility?
this is the snippet to call the method:
private class DownloadFilesTask extends AsyncTask<Void,Void,Void> {
private LoginActivity loginActivity;
public DownloadFilesTask(LoginActivity loginActivity){
this.loginActivity=loginActivity;
}
#Override
protected Void doInBackground(Void... voids) {
long start=System.currentTimeMillis();
in=null;
try {
website=new URI(URL);
request.setURI(website);
} catch (URISyntaxException e) {
e.printStackTrace();
}
HttpPost httpPost=new HttpPost(URL);
List<NameValuePair>nameValuePairs=new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("name",name));
nameValuePairs.add(new BasicNameValuePair("pwd",pwd));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
response=httpClient.execute(request);
} catch (IOException e) {
e.printStackTrace();
}
try {
in=new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
} catch (IOException e) {
e.printStackTrace();
}
try {
String line=in.readLine();
long end=System.currentTimeMillis();
long times=end-start;
String time=String.valueOf(times);
System.out.println(name);
System.out.println(NAME_PATTERN);
System.out.println(pwd);
System.out.println(PWD_PATTERN);
if (name.equals(NAME_PATTERN) && (pwd.equals(PWD_PATTERN))) {
bloggedIn=true;
System.out.println("Youre right");
}else
{
bloggedIn=false;
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private void onPostExecute(String line, String time) {
if(bloggedIn=true){
navigateToMainActivity(time);
}else{ if (bloggedIn=false){
newp(line,time);
}
}
}
}
and this is the method called:
public void navigateToMainActivity(String timetoo) {
al=new AlertDialog.Builder(LoginActivity.this);
al.setTitle("Welcome");
al.setMessage("Hey there");
al.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(new Intent(LoginActivity.this, Main.class));
}
});
al.show();
}
It looks like you need doInBackground to return true or false when it's finsished. You need doInBackground to return the boolean. Try this:
#Override
protected Boolean doInBackground(Void... arg0)
{
// your stuff
return bloggedIn; // instead of null or return the boolean where you are setting it true or false
}
Then your onPostExecute should look like this:
#Override
protected void onPostExecute(Boolean result)
{
super.onPostExecute(result);
if(result){
navigateToMainActivity(time);
}else{
newp(line,time);
}
}
I coded a class which starts a http connection for getting the text of e.g. website.
I used AsyncTask but I got NetworkOnMainException. May u help me?
The class
public class getXMLData extends AsyncTask<String, Void, String> {
TextView _textview;
public getXMLData(TextView textview) {
_textview = textview;
}
protected String doInBackground(String... url)
{
String _text = "";
try {
try {
URL _url = new URL(url[0]);
HttpURLConnection con = (HttpURLConnection) _url.openConnection();
_text = readStream(con.getInputStream());
}
catch (Exception e) {
e.printStackTrace();
}
}
catch (Exception e) {
e.printStackTrace();
}
return _text;
}
protected void onPostExecute(String result)
{
_textview.setText(result.toCharArray(), 0, result.length());
}
private String readStream(java.io.InputStream in) {
java.io.BufferedReader reader = null;
String result = "";
reader = new BufferedReader(new InputStreamReader(in));
try {
while ((reader.readLine() != null)) {
result = result + reader.readLine();
}
}
catch (java.io.IOException i)
{
}
finally
{
try {
reader.close();
}
catch (java.io.IOException e) {
e.printStackTrace();
}
}
return result;
}
Here how I start the AsyncTask:
bu_aktualize.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
_getXMLData.doInBackground("http://www.google.de");
}
});
Thanks for your help.
You do not call doInBackground() yourself. Instead, you call execute() or executeOnExecutor() to start the AsyncTask.
You may wish to review the documentation for AsyncTask, which shows an example of setting up an AsyncTask, including a call to execute().
This code is causing ANR force close any idea how to improve this code? i try with asynctask and i cant make it work in this code :
What i try to do here is updater activity will check for latest version and if got new version it will pop up alertdialog to ask user to update in the market
public class Updater extends Activity {
private int newVerCode = 0;
private String newVerName = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (getServerVerCode()) {
int vercode = Config.getVerCode(this);
if (newVerCode > vercode) {
doNewVersionUpdate();
} else {
notNewVersionShow();
}
}
}
//check version using json
private boolean getServerVerCode() {
try {
String verjson = NetworkTool.getContent(Config.UPDATE_SERVER
+ Config.UPDATE_VERJSON);
JSONArray array = new JSONArray(verjson);
if (array.length() > 0) {
JSONObject obj = array.getJSONObject(0);
try {
newVerCode = Integer.parseInt(obj.getString("verCode"));
newVerName = obj.getString("verName");
} catch (Exception e) {
newVerCode = -1;
newVerName = "";
return false;
}
}
} catch (Exception e) {
return false;
}
return true;
}
//Found No new version
private void notNewVersionShow() {
Updater.this.finish(); // End updater activity
}
//Found New version
private void doNewVersionUpdate() {
//Display alertdialog
}
}
You can use an AsyncTask - yes. In doInBackground you can add the code from getServerVerCode() and in onPostExecute everything in the if (getServerVerCode()).
doInBackground can return boolean so you know in onPostExecute what the result is.
Something like this:
private class GetServerVerCode extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
try {
String verjson = NetworkTool.getContent(Config.UPDATE_SERVER
+ Config.UPDATE_VERJSON);
JSONArray array = new JSONArray(verjson);
if (array.length() > 0) {
JSONObject obj = array.getJSONObject(0);
try {
newVerCode = Integer.parseInt(obj.getString("verCode"));
newVerName = obj.getString("verName");
} catch (Exception e) {
newVerCode = -1;
newVerName = "";
return false;
}
}
} catch (Exception e) {
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
if (result) {
int vercode = Config.getVerCode(this);
if (newVerCode > vercode) {
doNewVersionUpdate();
} else {
notNewVersionShow();
}
}
}
}