Issue
I have 2 Classes: a Main Class handling the UI and a second Class for retrieving Data from SQL Server
by using PHP.
From the first class a mehtod in the second class is called with passing and retrieving variables.
Actually it is working fine without AsyncTask
.
But since I want to use the code on devices running Android 3.0 and above, I need to change the method to be an AsyncTask. Else I get this error: "android.os.networkonmainthreadexception
"
the actual working code Looks like this:
Main class:
...
String inputString="1";
String outputString;
outputString = Class2.SomeMethodInClass2(inputString);
....
Class2:
public class Class2 {
public static String SomeMethodInClass2(String input) {
String Output;
...
//Do some php-sql stuff based on "input"-variable
//and return the "output"-variable
...
return output;
}
}
This code works perfectly on Android 2.0 but I need to change it to AsyncTask
, because Andoid 3.0
and above is giving me: "android.os.networkonmainthreadexception
"
I have read a lot of threads about AsyncTask
, but I can not get it to work with Input and Output in my code.
Eclipse
allways tells me there is something wrong with my code.
How do I have to change my code, to be a working async Task? (please explain using my above code sample)
--edit: if there is an easier way to get rid of "android.os.networkonmainthreadexception
" on 3.0 an above than AsyncTask, this would be fine too! --
Solution
Have a Callback in SecondClass
Extend your SecondClass
with Asynctask
Implement preExecute
,doinbackground
, postExecute
methods
Do your stuff in doinbackground
return result in doinbackground
In postExecute
pass result to the Callback
Implement SecondClass.Callback
in FirstClass
start SecondClass
(execute) and pass a Callback
reference from FirstClass
In Callback just handle your next operations with the result
EDIT :
public class SecondClass extends AsyncTask<String, Void, String> {
public interface Callback {
public void update(String result);
}
Callback mCallback;
public SecondClass(Callback callback) {
super();
mCallback = callback;
}
@Override
protected String doInBackground(String... params) {
String result = null;
//do your stuff and save result
return result;
}
@Override
protected void onPostExecute(String result) {
if(mCallback != null)
mCallback.update(result)
super.onPostExecute(e);
}
}
public class FirstClass implements SecondClass.Callback{
@Override
public void update(String result){
//do your stuff with result
}
return_type someMethod(){
SecondClass sc = new SecondClass(this) ;
sc.execute(someurl);
}
}
Answered By - BlackBeard
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.