마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

서버 연결 안될때 팝업창 보여주기

0 추천

안녕하세요 처음 글을 남겨봅니다

지금 제가 하려는건 톰캣으로 서버를 열어놓고

안드로이드로 게시판에 들어가는데

 

인터넷은 연결이 되어있는데(3g, wifi) 서버가 꺼져있을때

팝업을 띄어주려고 합니다

err = false 일때 interface로 writeArticle에 가서 팝업을 띄우던가

try - catch로 exception 처리를 통해서 alertDialog를 띄우려고 하는데

어떻게 하는게 좋을까요??

 

exception처리를 할거면 어디서 해야하고

err = false를 주려면 어디서 줘야하는지 알려주시면 감사하겠습니다

 

도와주세요 ㅜㅜ

 

package com.example.mActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.net.ConnectException;
import java.nio.charset.Charset;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

import com.example.board.Myip;
import com.example.network.NetworkCheck;

public class WriteThread extends AsyncTask<String, Void, Bundle> {
	Myip ip = new Myip();

	private String postUrl = ip.ip() + "board/writeAndroidPro.jsp?";
	private Context mContext;
	private InputStream result = null;
	private Bundle rowData = new Bundle();
	private WriteThreadListener onListner;
	ProgressDialog dialog = null;
	private boolean err = true;
	NetworkCheck nc = new NetworkCheck();
	private int resizeMoreSample = 0;

	public interface WriteThreadListener {
		void onAsyncListener(Bundle data, boolean err);
	}

	public WriteThread(Context writeArticle) {
		mContext = writeArticle;
		dialog = new ProgressDialog(mContext);
	}

	@SuppressWarnings("deprecation")
	@Override
	protected Bundle doInBackground(String... params) {

		try {
			HttpClient client = new DefaultHttpClient();
			client.getParams().setParameter(
					CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

			HttpPost post = new HttpPost(postUrl);

			MultipartEntity mEntity = new MultipartEntity();
			System.out.println("params: " + params[0]); // absolute path

			// Image가 있을경우
			if (!params[0].equals("")) {
				BitmapFactory.Options option = new BitmapFactory.Options();

				option.inJustDecodeBounds = true;
				BitmapFactory.decodeFile(params[0], option); // absolutePath를 직접
																// 넣음
				int photoWidth = option.outWidth;
				int photoHeigth = option.outHeight;

				// 원래는 max가 아니라 min이었다
				int scaleFactor = Math.max(
						photoWidth / Integer.parseInt(params[5]), photoHeigth
								/ Integer.parseInt(params[6]));
				Log.d("WriteThread91",
						"scaleFactor: " + scaleFactor + " width/ " + photoWidth
								/ Integer.parseInt(params[5]) + " height / "
								+ photoHeigth / Integer.parseInt(params[6]));

				setResizeMoreSample(Integer.parseInt(params[7]));

				int sample = scaleFactor + getResizeMoreSample();
				if (sample % 2 > 0) {
					sample += 1;
				}

				option.inPreferredConfig = Bitmap.Config.RGB_565;
				option.inJustDecodeBounds = false;
				option.inSampleSize = sample;
				option.inPurgeable = true;

				Log.d("WriteThread91", " photoWidth: " + photoWidth
						+ " device width: " + Integer.parseInt(params[5])
						+ " photoHeigth: " + photoHeigth + " device height : "
						+ Integer.parseInt(params[6]) + " inSampleSize: "
						+ sample);

				Bitmap b = BitmapFactory.decodeFile(params[0], option);

				File fileCacheItem = new File(params[0] + "_"); // resize 저장할곳
				// 05-26 20:30:10.493: D/absolutePath(32337): absolute:
				// /storage/emulated/0/DCIM/Camera/20140526_202537.jpg

				OutputStream out = null;

				fileCacheItem.createNewFile(); // 주어진 경로를 이용해 파일을 만든다
				out = new FileOutputStream(fileCacheItem);
				b.compress(CompressFormat.JPEG, 100, out);

				mEntity.addPart("file", new FileBody(fileCacheItem));
			}

			// title+"", writer+"", password+"", content+
			mEntity.addPart("title",
					new StringBody(params[1], Charset.forName("utf-8")));
			mEntity.addPart("writer",
					new StringBody(params[2], Charset.forName("utf-8")));
			mEntity.addPart("password",
					new StringBody(params[3], Charset.forName("utf-8")));
			mEntity.addPart("content",
					new StringBody(params[4], Charset.forName("utf-8")));

			post.setEntity(mEntity);
			HttpResponse response = client.execute(post);
			HttpEntity respon = response.getEntity();

			if (respon != null) {
				// result = respon.getContent();
				String res = EntityUtils.toString(respon, "utf-8");
				System.out.println("res : " + res);
				err = true;

				String tag = null;
				// xml data를 바꿔줌
				XmlPullParserFactory factory = XmlPullParserFactory
						.newInstance();
				XmlPullParser xpp = factory.newPullParser();
				// factory 패턴으로 연결해서 xpp를 열어둠

				xpp.setInput(new StringReader(res));
				// xpp안에 위에서 StringReader한 내용을 담아둔다

				int eventType = xpp.getEventType();

				while (eventType != XmlPullParser.END_DOCUMENT) {
					tag = xpp.getName();

					switch (eventType) {
					case XmlPullParser.START_TAG:
						if (tag != null && tag.equalsIgnoreCase("response"))
							break;
						if (tag != null && tag.equalsIgnoreCase("returnmsg")) {
							rowData.putString(tag, xpp.nextText());
							break;
						}
						if (tag != null && tag.equalsIgnoreCase("returncode")) {
							rowData.putString(tag, xpp.nextText());
						}
						break;
					case XmlPullParser.END_TAG:
						if (xpp.getName().equalsIgnoreCase("response")) {
						}
						break;

					case XmlPullParser.START_DOCUMENT:
						break;
					}
					eventType = xpp.next();

				}

			} else {
				err = false;
			}

		} catch (HttpHostConnectException e) {
			e.printStackTrace();
			err = false;
			nc.showServerMessageFinish(mContext, WriteArticle.wActivity);
		} catch (ConnectException e) {
			e.printStackTrace();
			err = false;
			nc.showServerMessageFinish(mContext, WriteArticle.wActivity);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return rowData;

	}

	@Override
	protected void onPreExecute() {
		dialog.setMessage("로딩중!!");
		dialog.show();
	}

	@Override
	protected void onPostExecute(Bundle rowData) {
		dialog.dismiss();
		if (onListner != null) {
			onListner.onAsyncListener(rowData, err);
			// bundle만 보내주면 됨
		}

	}

	public WriteThreadListener getOnListner() {
		return onListner;
	}

	public void setOnListner(WriteThreadListener onListner) {
		this.onListner = onListner;
	}

	public int getResizeMoreSample() {
		return resizeMoreSample;
	}

	public void setResizeMoreSample(int resizeMoreSample) {
		this.resizeMoreSample = resizeMoreSample;
	}

}

지금 제가 하려는건

던져보아요 (130 포인트) 님이 2014년 5월 29일 질문

1개의 답변

–1 추천

AsyncTask<String, Void, Bundle>

위코드를 

AsyncTask<String, String, Bundle>

이렇게 고친후 

       @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
            String type =  valuse[0];
            String message =  valuse[1];
            if (type.equalse("error")) {
                Toast.make(getApplicationContext(),
                   "Error " + message, Toast.LENGTH_SHORT)
                 .show();
            }
        }

 

이렇게 WriteThread 안에 추가 해주시고 저걸 doinbackground 안에서는 

this.publishProgress("error", e.toString);

이렇게 처리하면 UI 적으로 보이게 할 수 있습니다.

 

카라드레스 (2,910 포인트) 님이 2014년 5월 29일 답변
그러지마시고..

Reciever중에 네트워크 상태에 관련 리시버가 있어서 거기에 코딩해보세요
감사합니다 이 답변이 제가 원하는답변과 좀더 유사한거 같습니다
...