olipinski
olipinski

Reputation: 103

Communicating between Java Classes

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:

  1. Waits on a socket for data
  2. Parses the data
  3. Writes the data on the screen

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?

Upvotes: 1

Views: 1425

Answers (1)

Teodor Kostadinov
Teodor Kostadinov

Reputation: 119

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.

Upvotes: 2

Related Questions