MainActivity.java
manifest.xml
package com.json.test_02;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
private Button button;
private MyHandler handler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button) findViewById(R.id.button1);
button.setOnClickListener(this);
handler=new MyHandler();
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.button1){
MyThread thread=new MyThread();
thread.start();
}
}
public String readData(InputStream inSream, String charsetName)
throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = inSream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();
outStream.close();
inSream.close();
return new String(data, charsetName);
}
class MyThread extends Thread{
@Override
public void run() {
try {
URL url=new URL("http://192.168.43.78:8080/MyWeb_Json/myjson.json");
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
InputStream input=conn.getInputStream();
String str=readData(input,"utf-8");
JSONArray array=new JSONArray(str);
for (int i = 0; i < array.length(); i++) {
JSONObject jobj=array.getJSONObject(i);
int id=jobj.getInt("id");
String name=jobj.getString("name");
Message message=new Message();
Bundle data=new Bundle();
data.putInt("id", id);
data.putString("name", name);
message.setData(data);
handler.sendMessage(message);
System.out.println(id+"---------"+name);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class MyHandler extends Handler{
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
Bundle data=msg.getData();
int id=data.getInt("id");
String name=data.getString("name");
Toast.makeText(MainActivity.this, "id:"+id+"name:"+name, Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
manifest.xml
<uses-permission android:name="android.permission.INTERNET"/>