ビッグデータ入門(JSONファイルの情報を取得し、アンドロイド携帯電話ページに出力)
3607 ワード
JSON ( URL JSON )
MyAdapter3 :
public class MyAdapter3 extends BaseAdapter {
private Context context;
private List it;
public MyAdapter3(Context context, List it) {
this.context = context;
this.it = it;
}
@Override
public int getCount() {
return it.size();
}
@Override
public Object getItem(int position) {
return it.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// XML
LayoutInflater layoutInflater = LayoutInflater.from(context);
// title.xml
View view = layoutInflater.inflate(R.layout.title1, null);
//
TextView nameText = view.findViewById(R.id.textView3);
TextView ageText = view.findViewById(R.id.textView4);
//
nameText.setText(it.get(position).getName());
ageText.setText(""+ it.get(position).getAge());
return view;
}
}
JsonActivity :
public class JsonActivity extends Activity{
private List it;
private MyHandle handler;
private ListView listView2;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.index);
listView2=findViewById(R.id.ListView111);
it=new ArrayList();
MyThread myThread = new MyThread();
handler = new MyHandle();
myThread.start();
}
//
class MyThread extends Thread{
@Override
public void run() {
super.run();
try {
// JSON
URL url = new URL("http://192.168.1.107:8080/Zhenai/hg.json");
// URL connection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// connection
InputStream is = connection.getInputStream();
String neirong = "";
int data = 0;
//
while ((data = is.read()) != -1) {
neirong += (char) data;
}
// JSONArray
JSONArray array = new JSONArray(neirong);
//
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
int id = obj.getInt("id");
String name = obj.getString("name");
int age = obj.getInt("age");
User user = new User(id, name, age);
it.add(user);
}
// handler
handler.sendMessage(new Message());
}catch (Exception e){
}
}
}
//
class MyHandle extends Handler{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// MyAdapterJSON
listView2.setAdapter(new MyAdapterJSON(JsonActivity.this,it));
}
}
//Adapter
class MyAdapterJSON extends MyAdapter3{
// MyAdapterJSON MyAdapter3 ,
public MyAdapterJSON(Context context, List it) {
super(context, it);
}
}
}