package com.example.network_json2;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button submitButton = (Button) this.findViewById(R.id.submit_btn);
submitButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
new ReadJSONFeed().execute("http://117.16.231.212:8010/checkNewOrder");
}
});
}
private class ReadJSONFeed extends AsyncTask<String, String, String> {
protected void onPreExecute() { // 안씀.
}
@Override
protected String doInBackground(String... urls) { // 백그라운드 작업
HttpClient httpclient = new DefaultHttpClient();
StringBuilder builder = new StringBuilder();
HttpPost httppost = new HttpPost(urls[0]);
try {
HttpResponse response = httpclient.execute(httppost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent(); // 사람이 읽을수 있게해줌
BufferedReader reader = new BufferedReader(//사람이 읽을수 있게해줌
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}
} catch (Exception e) {
e.printStackTrace();
}
// TextView tv1 = (TextView) findViewById(R.id.textview1);
// tv1.setText(builder.toString());
return builder.toString();
}
protected void onPostExecute(String result) {
String stateInfo = "";
try {
JSONObject obj = new JSONObject(result); // { 의 뜻
JSONArray jArr = obj.getJSONArray("data"); // data 객체들을 배열로 얻음
for (int i = 0; i < jArr.length(); i++) { // 배열의 길이대로 포문
JSONObject jObject = new JSONObject(); // 새로 객체 생성
jObject = jArr.getJSONObject(i); // 새로만들어진 객체에 data객체들이 들어간 배열을 넣음
stateInfo += jObject.getString("menu") + "\n";
}
} catch (JSONException e) {
e.printStackTrace();
}
TextView resp = (TextView) findViewById(R.id.response);
if (stateInfo.trim().length() > 0)
resp.setText(stateInfo);
else
resp.setText("Sorry no match found");
}
}
}
http://117.16.231.212:8010/checkNewOrder 주소에서 json 을 가져와 안드로이드에서 출력하고 싶은데 잘 안되어 질문드립니다.
JSONObject obj = new JSONObject(data); 로 가져왔고 배열로 다시 가져온다음
객체에 넣었습니다.
소스가 잘못되었나요?ㅠㅠㅠ
JSONArray와 JSONObject가 너무 헷갈립니다ㅠㅠ