使用 rxjava 的 merge 方法將兩個 api 傳回的資料物件結合得到 Object,然後我想使用 SharedPreferences 方法快取Object。
我嘗試按照網路上的方法保存Objcet,卻沒有效果。請大夥幫忙看看。
Bean:
public class LifeSuggestionResult implements Serializable{ ... }
public class WeatherFuture implements Serializable { ... }
ObjectUtil( 使用 SharedPreferences 儲存並取得 Object):
public class ObjectUtil {
public static void setObject(String key, Object object, Context context) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(baos);
out.writeObject(object);
String objectVal = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
editor.putString(key, objectVal);
editor.commit();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (baos != null) {
baos.close();
}
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static <T> T getObject(String key, Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
if (sp.contains(key)) {
String objectVal = sp.getString(key, null);
byte[] buffer = Base64.decode(objectVal, Base64.DEFAULT);
ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(bais);
T t = (T) ois.readObject();
return t;
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (bais != null) {
bais.close();
}
if (ois != null) {
ois.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
rxjava部分:
public void getCurrentWeather(final String city) {
Observable<WeatherFuture> weatherFutureObservable = new WeatherService().getFutureWeather(city, "zh-Hans", "c");
Observable<LifeSuggestionResult> lifeSuggestionResultObservable = new WeatherService().getAirQuality(city, "zh-Hans", "city");
Observable.merge(weatherFutureObservable, lifeSuggestionResultObservable)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<Object>() {
@Override
public void onCompleted() {
}
@Override
public void onNext(Object o) {
setWeatherInfo(o);
}
@Override
public void onError(Throwable e) {
}
});
}
public void setWeatherInfo(Object o) {
if (o instanceof WeatherFuture) {
ObjectUtil.setObject("WeatherFuture", o, MainActivity.this);
...
}
} else if (o instanceof LifeSuggestionResult) {
ObjectUtil.setObject("LifeSuggestion", o, MainActivity.this);
...
}
大家讲道理2017-05-16 13:36:50
給你一個思路,使用排除法
1、在其他地方單獨使用ObjectUtil,看是否可以儲存和取出一個假資料Object
2、在onNext中列印出Object的內容,看是否是預期的Object
3、假如兩者都沒問題,那就看你的setWeatherInfo方法有沒有問題