import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnSystemResolverJson = (Button) findViewById(R.id.btnSystemResolverJson);
btnSystemResolverJson.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
StringBuffer sb = new StringBuffer();
String json = readText("weatherjson.txt");
JSONObject jo = new JSONObject(json);
int error = jo.getInt("error");
String status = jo.getString("status");
String date = jo.getString("date");
sb.append("error:"+error+" status:"+status+" date:"+date);
JSONArray array = jo.getJSONArray("results");
for (int i = 0; i < array.length(); i++) {
JSONObject jo2 = array.getJSONObject(i);
String currentCity = jo2.getString("currentCity");
sb.append("currentCity:"+currentCity);
JSONArray array2 = jo2.getJSONArray("weather_data");
for (int j = 0; j < array2.length(); j++) {
JSONObject jo3 = array2.getJSONObject(j);
String date2 = jo3.getString("date");
String dayPictureUrl = jo3.getString("dayPictureUrl");
String nightPictureUrl = jo3.getString("nightPictureUrl");
String weather = jo3.getString("weather");
String wind = jo3.getString("wind");
String temperature = jo3.getString("temperature");
sb.append("date2:"+date2+" dayPictureUrl:"+dayPictureUrl+" nightPictureUrl:"+nightPictureUrl+" weather"+weather+" wind"+wind+" temperature"+temperature);
}
}
System.out.println("查询结果:"+sb.toString());
Toast.makeText(MainActivity.this, sb.toString(), 0).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//读取方法
/*** 读取文件里面json串数据
*/
private String readText(String fileName) {
try {
//字节数组输出流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = getAssets().open(fileName);
byte[] buffer = new byte[1024];
int length = 0;
while ((length = is.read(buffer)) != -1) {
baos.write(buffer, 0, length);
}
baos.close();
return baos.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}