I've been trying to write a simple 3 class java app for android but i can't figure out one thing. How would one approach the problem of passing data between classes? In my case I have 3 classes:
The third class cannot do the network part because it involves a waiting loop which cannot be done in the Activity class.
So how should I do that?
You can define a Listener which is implemented by the "writes-on-the-screen" class and which the "parses-the-data" class uses to talk to it. Example:
class Parser {
private ParsingFinishedListener callback;
public Parser(ParsingFinishedListener c) {
this.callback = c;
}
//some code
public void parse(String stuffToParse) {
//code
callback.onTextParsed(parsedText);
}
public interface ParsingFinishedListener {
public void onTextParsed(String textToVizualize);
}
}
class MyTask extends AsyncTask<Void, Void, Void> {
private ParsingFinishedListener callback;
public MyTask(ParsingFinishedListener c) {
this.callback = c;
}
..doInBackground..
..onPostExecute(String result) {
Parser p = new Parser(callback);
p.parse(result);
}
}
class MyActivity extends Activity implements ParsingFinishedListener {
...onCreate(...) {
...
MyTask task = new MyTask((ParsingFinishedListener) this);
task.execute();
}
//some code
@Override
public void onTextParsed(String result) {
//do something with the result
}
}
You define your listener in the Parser and when finished parsing, you use it to get to the Activity, which should have implemented it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.