Currently developing a weather application . I wanna strictly observe 2 rules:
- MVC Design pattern
- Multithreading when I deals with network.
The problem is combining these things into a whole, here are parts of my code:
Weather Class (represent a Weather object) :
public class Weather {
private int mTimeInSeconds;
private String mTimeZone;
private int mTemperature;
private String mSummary;
public Weather(int timeInSeconds, String timeZone, int temperature, String summary) {
mTimeInSeconds = timeInSeconds;
mTimeZone = timeZone;
mTemperature = temperature;
mSummary = summary;
}
public String getTime() {
SimpleDateFormat formatter = new SimpleDateFormat("h:mm a");
formatter.setTimeZone(TimeZone.getTimeZone(mTimeZone));
Date dateTime = new Date(mTimeInSeconds * 1000);
String timeAsString = formatter.format(dateTime);
return timeAsString;
}
public int getTemperature() {
return mTemperature;
}
public String getSummary() {
return mSummary;
}
}
Worker Class (do all "dirty" work):
public class Worker {
private final OkHttpClient mClient = new OkHttpClient();
private String apiKey = "Secret!11";
private double latitude = 37.8267;
private double longitude = -122.423;
private String forecastUrl = "https://api.forecast.io/forecast/"
+apiKey
+"/"
+latitude
+","
+longitude;
public void getCurrentWeather() throws Exception {
final Request request = new Request.Builder()
.url(forecastUrl)
.build();
mClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
Log.v(MainActivity.TAG, e.getMessage());
}
@Override
public void onResponse(Response response) throws IOException {
try {
JSONObject weatherData = new JSONObject(response.body().string());
JSONObject currentlyWeather = weatherData.getJSONObject("currently");
Log.v(MainActivity.TAG, currentlyWeather.toString());
} catch (JSONException e) {
Log.v(MainActivity.TAG, e.getMessage());
}
}
});
}
}
Based on my understanding of MVC I put all data and logic around that data in Model (Worker and Weather classes). I wanna to achieve something like this in
MainActivity.java:
...
Worker mWorker = new Worker();
Weather mWeather = mWorker.getWeatherData();
...
2 questions:
Is this the correct design of MVC? (I mean, that all code which somehow work with data separated from the controller which only update view's)
If yes, how I can implement this? I need to return Weather object from Worker, but I can't do this because it's happen on separate thread, I wanna return Weather object to main thread, but have no idea how to implement this.