默认启动Activity背景是一张图片,启动时后台加载汇率数据,加载成功后进入另一个与用户交互Activity
首先分析JsonParser代码
package com.example.zhaorunze.currencies;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
/**
* Created by zhaorunze on 2017/4/3.
*/
public class JSONParser {
// static InputStream sInputStream=null;
private static JSONObject sReturnJsonObject=null;
private static String sRwaJsonString=null;
public JSONObject getsReturnJsonObject(String url) {
StringBuilder sb = new StringBuilder();
try {
URL urlObject = new URL(url);
URLConnection uc = urlObject.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(),"iso-8859-1"));
String inputLine = null;
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
}
in.close();
sRwaJsonString=sb.toString();
}
//catch (MalformedURLException e) {
// e.printStackTrace();
// }
catch (IOException e) {
e.printStackTrace();
}
//read stream into string-builder
try {
sReturnJsonObject=new JSONObject(sRwaJsonString);
}catch (JSONException e){
Log.e("Parser","Error when parsing data"+e.toString());
}
return sReturnJsonObject;
}
}
1.从url中读取数据流存到BufferedReader。
2.从BufferedReader 中按行读取添加(每次从字符末尾开始添加)到StringBuilder 中 。
3.再把StringBuilder 转换成字符串sRwaJsonString。
4.最后用字符串作为参数,实例化JSONObject。
设置偏好,重启时自动打开上次保存的一组转换对象。
package com.example.zhaorunze.currencies;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
/**
* Created by zhaorunze on 2017/4/6.
*/
public class PrefsMgr {
private static SharedPreferences sShredPreferences;
public static void setString(Context context,String locale,String code){
sShredPreferences= PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor=sShredPreferences.edit();
editor.putString(locale,code);
editor.commit();
}
public static String getString(Context context,String locale){
sShredPreferences=PreferenceManager.getDefaultSharedPreferences(context);
return sShredPreferences.getString(locale,null);
}
}
SharedPreferences是Android平台上一个轻量级的存储类,简单的说就是可以存储一些我们需要的变量信息。
2个activity 之间的数据传递除了可以他通过intent来传递,还可以使用SharedPreferences来共享数据的方式
SharedPreferences负责根据key读取数据,而SharedPreferences.Editor则用写入数据。
这个是默认启动Activity,后台异步线程加载数据。
package com.example.zhaorunze.currencies;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Window;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Iterator;
public class SplashActivity extends Activity {
public static final String URL_CODES = "http://openexchangerates.org/api/currencies.json";
public static final String KEY_ARRAYLIST = "key_arraylist";
private ArrayList<String> mCurrencies;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_splash);
new FetchCodesTask().execute(URL_CODES);
}
private class FetchCodesTask extends AsyncTask<String, Void, JSONObject> {
@Override
protected JSONObject doInBackground(String... params) {
return new JSONParser().getsReturnJsonObject(params[0]);
}
@Override
protected void onPostExecute(JSONObject jsonObject) {
//super.onPostExecute(jsonObject);
try {
if (jsonObject == null) {
throw new JSONException("no data available.");
}
Iterator iterator=jsonObject.keys();
String key="";
mCurrencies=new ArrayList<String>();
while(iterator.hasNext()){
key=(String)iterator.next();
mCurrencies.add(key+"|"+jsonObject.getString(key));
}
Intent mainIntent=new Intent(SplashActivity.this,MainActivity.class);
mainIntent.putExtra(KEY_ARRAYLIST,mCurrencies);
startActivity(mainIntent);
finish();
}catch (JSONException e){
Toast.makeText(
SplashActivity.this,
"There is been a JSON exception:"+e.getMessage(),
Toast.LENGTH_LONG
).show();
e.printStackTrace();
finish();
}
}
}
}
doInBackground(Params…) 后台执行,比较耗时的操作都可以放在这里。注意这里不能直接操作UI。此方法在后台线程执行,完成任务的主要工作,通常需要较长的时间。在执行过程中可以调用publicProgress(Progress…)来更新任务的进度。
onPostExecute(Result) 相当于Handler 处理UI的方式,在这里面可以使用在doInBackground 得到的结果处理操作UI。 此方法在主线程执行,任务执行的结果作为此方法的参数返回
SplashActivity执行异步任务,从URL_CODES中,用JsonParser解析数据,用Iterator遍历jsonObject.keys中的key(存储方式类似map),通过key获取value。把获取到的值按key|value形式存到Arraylist中,用intent传到UIActivity。