我正在尝试使用okhttp实现主题/观察者模式以通过网络填充ArrayList。我肯定会对这些接口的工作方式有一个基本的误解,因为它们感觉像是伏都教徒,我无法解释它们应该如何工作,更不用说有效地排除故障了。我希望在这里有所了解。
有四个部分。两个接口(主题和观察者)以及两个实现这些接口的类(请原谅“ Activity”的使用。它与Android活动无关。它是我尚未更正的pojo自动化的json) 首先,观察者界面:
package come.myapp.app
import java.util.ArrayList;
public interface Observer {
void onUpdate(ArrayList<Activity> events);
}
主题界面:
package come.myapp.app
public interface Subject {
void registerThis(Observer o);
void unregisterThis (Observer o);
void sendNotice();
}
主要:
package come.myapp.app
//import things
public class MainActivity extends AppCompatActivity implements Observer {
private ArrayList <Activity> eventList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetOBEvents getOBEvents = new GetOBEvents();
getOBEvents.registerThis(this);
getOBEvents.getEvents(); // This is a failure point (null pointer)
}
具体主题:
public class GetOBEvents implements Subject
{
ArrayList<Activity> eventList = new ArrayList<>();
ArrayList<Observer> mObservers;
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
...//data is taken and processed here
ArrayList<Activity> eventArray = new ArrayList<>();
public void getEvents () {
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure ...
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String callResponseText = response.body().string();
Venues venues = Json.fromJson(callResponseText,Venues.class);
List<Venue> listhere = venues.getVenues();
List<Activity> allEvents = listhere.get(0).getActivities();
for (Activity activity : allEvents) {
eventArray.add(activity);} //This works
setEvents(eventArray);// This fails with a null point exception
}
});
}
@Override
public void registerThis(Observer o) {
mObservers.add(o);
}
@Override
public void unregisterThis(Observer o) {
mObservers.remove(o);
}
@Override
public void sendNotice() {
for (Observer observers : mObservers) {
observers.onUpdate(eventList);
}
}
public void setEvents(ArrayList<Activity> mEvents){
eventList = mEvents;
sendNotice();
}
}
我整天都在忙碌,我一直在努力了解这些接口在逻辑上是如何工作的。如果有人有一个虚拟的人可以跟随的启发性资源,我将不胜感激。