안드로이드 개발 질문/답변
(글 수 45,052)
public void onClick(View v) {
// TODO Auto-generated method stub
if(v == btn1)
asyncCalcSum();
//GetImageFromURL();
//postData() ;
Toast.makeText(this, "postData 실행!!", Toast.LENGTH_SHORT).show();
}
public void postData() {
InputStream is = null;
String totalMessage = "";
String url = "127.0.0.1";
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
//HttpPost httppost = new HttpPost(url);
try {
// 데이터 입력 < 보내는 값 >
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("test", "12341111111111111111111111111111"));
//nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// 네트워크 연결해서 데이타 받아오기
String result = "";
//5초이내에 응답이 없으면은 Exception 발동!
HttpParams params = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 5000);
HttpPost httppost = new HttpPost(url);
//입력된 데이터 전송
UrlEncodedFormEntity entityRequest = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
httppost.setEntity(entityRequest);
//실행하고 결과 response으로 받기
HttpResponse response = httpclient.execute(httppost);
HttpEntity entityResponse = response.getEntity();
//엔티티 얻어오기
is = entityResponse.getContent();
/** convert response to string */
//응답된 데이터를 읽을수 있는 입력스트림으로 넘긴다
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
//인코딩 처리 버퍼드리더 얻어오기
StringBuilder sb = new StringBuilder();
String line = null;
//한라인씩 읽어서 스트링 버퍼에 담음
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
//인풋스트림 닫음
is.close();
//문자열 반환
result = sb.toString();
//result1.setText(result);
jsonParser(result);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
httpclient.getConnectionManager().shutdown();
}
}
private void jsonParser(String result){
Random r = new Random();
String resultStr = "";
try {
//JSON String으로 부터 JSONArray 생성. [](대괄호)
JSONArray jArr = new JSONArray(result);
for (int i = 0; i < 5; i++) {
int random = r.nextInt(jArr.length());
//JSONArray에서 i번째 해당하는 JSONObject를 추출.
JSONObject jObj = jArr.getJSONObject(random);
//각 이름("id"/"tel")에 해당하는 값을 추출.
resultStr += String.format(jObj.getString("recipe_id1")+","); //, jObj.getString("recipe_name1")
Log.i("recipe_id1", ""+jObj.getString("recipe_id1"));
}
result1.setText(resultStr);
} catch (JSONException e) {
Toast.makeText(httpserver.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private Bitmap GetImageFromURL() {
Bitmap imgBitmap = null;
ImageView img = (ImageView)findViewById(R.id.imageView1);
//인터넷 연결을 위해 try/catch를 한다.
try {
//url 등록
URL url = new URL("http://sstatic.naver.net/search/img3/h1_naver.gif);
URLConnection conn = url.openConnection();
conn.connect();
int nSize = conn.getContentLength();
//접속한 url로부터 데이터값을 받아온다.
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream(), nSize);
//얻어온 이미지를 bitmap에 저장
imgBitmap = BitmapFactory.decodeStream(bis);
//BufferedInputStream 종료
bis.close();
//image저장
img.setImageBitmap(imgBitmap);
} catch (Exception e) {
e.printStackTrace();
}
return imgBitmap;
}
private void asyncCalcSum() {
new AsyncTask<Void, Void, Void>() {
private ProgressDialog mProgressDialog;
//Background 작업 시작 전
protected void onPreExecute() {
//미리 준비해야하는 작업
mProgressDialog = showLoadingDialog(httpserver.this, false);
};
//Background 작업 진행중...
@Override
protected Void doInBackground(Void... params) {
//백그라운드에서 실행되는 작업
try {
//Thread.sleep(5000);
postData();
GetImageFromURL();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//total = sum();
return null;
}
//BackGround 작업이 끝난 후에 호출
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//백그라운드 작업이 끝난 후 해줄 작업
mProgressDialog.dismiss();
Toast.makeText(httpserver.this, "계산완료!!", Toast.LENGTH_SHORT).show();
/* txtSum.setText(String.valueOf(total));
edtSum.setText(String.valueOf(total));*/
}
}.execute();
}
public ProgressDialog showLoadingDialog(Context context, boolean cancelable) {
ProgressDialog dialog = new ProgressDialog(context);
dialog.setMessage("계산중....");
dialog.setIndeterminate(true);
dialog.setCancelable(cancelable);
dialog.show();
return dialog;
}
}
Asynctask로 돌리면은 왜...빨간글씨를 체크한 부분이 안먹히고요..
Asynctask로 안돌리고 클릭이벤트에 바로 넣어주면은 먹히네요..
조언부탁드립니다!



