1:activity_main.xml
2:MainActivity.java
public class MainActivity extends Activity implements OnClickListener { private Button btnGetTitles=null; private ListView lvShow=null; private ListtitleList=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initUI(); btnGetTitles.setOnClickListener(this); } private void initUI(){ btnGetTitles=(Button)findViewById(R.id.btn_get_titles); lvShow=(ListView)findViewById(R.id.lv_show); } @Override public void onClick(View arg0) { new Thread(new GetTitlesThread()).start(); } Handler getTitlesHandler=new Handler(){ public void handleMessage(Message msg){ if(msg.what==100){ ArrayAdapter adapter=new ArrayAdapter ( MainActivity.this, android.R.layout.simple_list_item_1, titleList); lvShow.setAdapter(adapter); } } }; class GetTitlesThread implements Runnable{ @Override public void run() { //1:判断缓存文件是否存在。/data/data/com.yan.example/jsontest/files/titles.txt String path=getFilesDir().getPath()+"//" ; File file=new File(path+"titles.txt"); if(file.exists()){ //2:如果缓存文件存在,就从文件取数据。 readFile("titles.txt"); getTitlesHandler.obtainMessage(100).sendToTarget(); }else{ //3:如果缓存文件不存在,就从网络取数据 ,然后将数据保存到缓存文件。 String url="http://www.zhihuiqd.com/wsht/server/selectTitle2json.php"; String res=getStringFromeNet(url); saveFile("titles.txt",res);//将内容缓存起来 try{ JSONArray json=new JSONArray(res); int len=json.length(); String title=""; titleList=new ArrayList (); for(int i=0;i (); for(int i=0;i
3:运行结果。