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

웹서버있는 xml에 있는 텍스트,이미지 받아오는법..

0 추천

만들려는 어플이 있는데 책보고 그대로 따라하는데 안나옵니다.ㅠㅜ 안드로이드 기초와 실전앱프로젝트 책 내용입니다.

첫화면에 리스트뷰에 웹서버에있는 food_list.xml 에 있는 내용을 받아와서 뿌려줘야하는데 흰화면만 나오네요 ㅜ

layout 폴더 안에 activity_main.xml                 list_row.xml                    detail.xml

src 폴더 안에   MainActivity.java

                     cmsHTTP.java(웹통신 클래스)

                     NetworkXMLActivity.java

이렇게 구성되어 있습니다.

웹서버에서 받아와야하는데..그냥 위에 소스만 가지고 컴파일하면 나와야하는게 아닌건가요?

따로 뭐 설정을 해줘야하나요? 리스트뷰에 나올 리스트는 http://www.owllab.com/android2/food_list.xml

에서 받아옵니다.

익스플로러에서 위에 주소 들어가보면 사진이나 글은 나오던데..왜 리스트뷰에 안나올까요 ㅜ

뭔가 연동하는 부분이 있어야될거같기도 한데...

어플은 처음만들어보고 웹서버에 대한 지식도 전무해서 뭘 어떻게 해야할지 모르겠어요 ㅠ 뭐가 문제일까요?

아래는 소스입니다.

-----------------------------------------------------------------------------

[activity_main.xml]

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Button android:id="@+id/button1" android:layout_height="wrap_content"
    android:layout_width="match_parent" android:text="제            목"
    android:onClick="reLoadList"></Button>

    <ListView
        android:layout_height="350dp" android:id="@+id/listView1"
        android:layout_width="match_parent"
        ></ListView>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent" android:layout_height="wrap_content">
       
    <Button android:id="@+id/button2" android:layout_height="wrap_content" android:layout_weight="1"
    android:layout_width="wrap_content"  android:text="버튼 1"
    ></Button>
     <Button android:id="@+id/button3" android:layout_height="wrap_content" android:layout_weight="1"
    android:layout_width="wrap_content"  android:text="버튼 2"
    ></Button>
     </LinearLayout>
</LinearLayout>

-----------------------

[cmsHTTP.java]

package com.owl.test4;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.app.Activity;
import android.util.Log;
import android.widget.Toast;

public class cmsHTTP {

 public String mimeType = "text/html";
 public String encoding = "UTF-8";
 public int REGISTRATION_TIMEOUT = 10 * 1000;
 public String TAG = "cmsHTTP";
 public Activity act;
 public String noData = "네트워크 장애 \n다시 시도해주세요";
 public cmsHTTP(){
 }
 public String sendGet(String url){
  String result=null;
  HttpResponse resp;
  HttpGet httpGet = new HttpGet(url);
  HttpClient httpClient = new DefaultHttpClient();
  HttpParams tmpparms = httpClient.getParams();
  HttpConnectionParams.setConnectionTimeout(tmpparms,REGISTRATION_TIMEOUT);
  HttpConnectionParams.setSoTimeout(tmpparms,REGISTRATION_TIMEOUT);
  ConnManagerParams.setTimeout(tmpparms,REGISTRATION_TIMEOUT);
  try{
   resp = httpClient.execute(httpGet);
   if(resp.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
    if(Log.isLoggable(TAG,Log.VERBOSE))
     Log.v(TAG,"Successful authentication");
    HttpEntity respEntity = resp.getEntity();
    if(respEntity != null){
     InputStream instream = respEntity.getContent();
     result = convertStreamToString(instream);
     instream.close();
    }
   }else{
    if(Log.isLoggable(TAG,Log.VERBOSE))
     Log.v(TAG,"Error Process"+ resp.getStatusLine());
   }
  }catch(final IOException e){
   if(Log.isLoggable(TAG, Log.VERBOSE))
    Log.v(TAG, "IOException when getting authtoken",e);
  }finally{
   if(Log.isLoggable(TAG,Log.VERBOSE))
    Log.v(TAG,"completing");
  }
  if(result==null){
   Toast.makeText(act, noData, Toast.LENGTH_SHORT).show();
  }
  return result;
 }
 public String convertStreamToString(InputStream is){
  StringBuilder sb = new StringBuilder();
  String line = null;
  try{
   BufferedReader reader = new BufferedReader(new InputStreamReader(is,encoding),8);
   while((line=reader.readLine())!=null){
    sb.append(line + "\n");
   }
  }catch(IOException e){
   e.printStackTrace();
  }finally{
   try{
    is.close();
   }catch(IOException e){
    e.printStackTrace();
   }
  }
  return sb.toString();
 }
}

-----------------------------

익명사용자 님이 2014년 5월 1일 질문
추가 입니다.
[NetworkXMLActivity.java]
package com.owl.test4;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class NetworkXMLActivity extends Activity{
 @Override
 public void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  loadList();
 }
 public void reLoadList(View view){
  loadList();
 }
 HashMap<String, String> hm = new HashMap<String, String>();
 public void loadList(){
  String theUrl = http://www.owllab.com/android2/food_list.xml
  cmsHTTP cmsHttp = new cmsHTTP();
  cmsHttp.encoding = "UTF-8";
  cmsHttp.act = this;
  String tmpData = cmsHttp.sendGet(theUrl);
  if(tmpData==null)return;
  hm = xml2HashMap(tmpData, "UTF-8");
  theListAdapter listAdapter = new theListAdapter(this, R.layout.list_row,hm);
  ListView listView = (ListView)findViewById(R.id.listView1);
  listView.setAdapter(listAdapter);
 }
 public HashMap<String, String> xml2HashMap(String tmpData, String encoding){
  HashMap<String, String> hm = new HashMap<String, String>();
  hm.put("count","0");
  try{
   DocumentBuilderFactory docBF = DocumentBuilderFactory.newInstance();
   DocumentBuilder docB = docBF.newDocumentBuilder();
   InputStream is = new ByteArrayInputStream(tmpData.getBytes(encoding));
   Document doc = docB.parse(is);
   Element lists = doc.getDocumentElement();
   NodeList dataList = lists.getElementsByTagName("data");
   int c = 0;
   for(int i = 0; i < dataList.getLength(); i++){
    NodeList dataNodeList = dataList.item(i).getChildNodes();
    for(int j=0; j<dataNodeList.getLength();j++){
     Node itemNode = dataNodeList.item(j);
     if(itemNode.getFirstChild()!=null){
      String nodeName = itemNode.getNodeName();
      String nodeValue = itemNode.getFirstChild().getNodeValue();
      hm.put(nodeName + "["+i+"j",nodeValue);
     }
    }//for j
    c++;
   }//for i
   hm.put("count",Integer.toString(c));
  }catch (Exception e){
   Log.e("com.cms.sample.xml2HashMap",e.getMessage());
  }
  return hm;
 }
 class theListAdapter extends BaseAdapter{
  
  LayoutInflater inflater;
  HashMap<String, String> hm;
  Context mContext;
  int mListLayout;
  public int listCount = 0;
  public theListAdapter(Context tContext, int listLayout, HashMap<String, String> tmpHm){
   mContext = tContext;
   mListLayout = listLayout;
   hm = tmpHm;
   inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   listCount = Integer.parseInt(hm.get("count").toString());
  }
  @Override
  public int getCount(){
   return listCount;
  }
  @Override
  public Object getItem(int arg0){
   return arg0;
  }
  @Override
  public long getItemId(int position){
   return position;
  }
  
  public HashMap<String, Bitmap> hmImg = new HashMap<String, Bitmap>();
  
  @Override
  public View getView(int position, View convertView,ViewGroup parent){
   if(convertView == null){
    convertView = inflater.inflate(mListLayout, parent, false);
   }
   try{
    if(hmImg.get("thumb[" + position + "]")==null){
     String urlstr = hm.get("thumb[" + position + "]");
     URL url = new URL(urlstr);
     URLConnection conn = url.openConnection();
     conn.connect();
     BufferedInputStream bis = new BufferedInputStream(conn.getInputStream(), 512 * 1024);
     Bitmap bm = BitmapFactory.decodeStream(bis);
     bis.close();
     hmImg.put("thumb[" + position + "]", bm);
    }
    if(hmImg.get("thumb[" + position + "]")!=null){
    ((ImageView) convertView.findViewById(R.id.imageView1)).setImageBitmap(hmImg.get("thumb[" + position + "]"));
    }
   }catch (IOException e){}
   ((TextView) convertView.findViewById(R.id.textView1)).setText("["+hm.get("rowid["+position+"]")+"]"+hm.get("subject[" +position + "]"));
   ((TextView) convertView.findViewById(R.id.textView2)).setText("["+hm.get("rowid["+position+"]"));
   ((TextView) convertView.findViewById(R.id.textView3)).setText("["+hm.get("writer["+position+"]"));
   final int positionInt = position;
   ((LinearLayout) convertView.findViewById(R.id.linearLayout1)).setOnClickListener(new Button.OnClickListener(){
    public void onClick(View v){
     detailInfo(positionInt);
    }
   });
   return convertView;
  }
  public void detailInfo(int position){
   Dialog dialog = new Dialog(mContext);
   dialog.setContentView(R.layout.detail);
   dialog.setTitle(hm.get("rowid["+position+"]"));
   dialog.show();
   
   ((TextView) dialog.findViewById(R.id.textView1)).setText("["+hm.get("subject["+position+"]"));
   ((TextView) dialog.findViewById(R.id.textView2)).setText("["+hm.get("writer["+position+"]"));
   ((TextView) dialog.findViewById(R.id.textView3)).setText("["+hm.get("content["+position+"]"));
   Button buttonOK = (Button) dialog.findViewById(R.id.button1);
   buttonOK.setOnClickListener(new detailOKListener(dialog));
   try{
    if (hm.get("img[" + position + "]")!=null){
      String urlstr = hm.get("img[" + position + "]");
      URL url = new URL(urlstr);
      URLConnection conn = url.openConnection();
      conn.connect();
      BufferedInputStream bis = new BufferedInputStream(conn.getInputStream(), 512*1024);
      Bitmap bm = BitmapFactory.decodeStream(bis);
      ((ImageView) dialog.findViewById(R.id.imageView1)).setImageBitmap(bm);
     }
   }catch(IOException e){}
  }
  protected class detailOKListener implements OnClickListener{
   private Dialog dialog;
   public detailOKListener(Dialog dialog){
    this.dialog = dialog;
   }
   public void onClick(View v){
    dialog.dismiss();
   }
  }
 }
}
[detail.xml]

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"     android:padding="10dp"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:minWidth="600dp"
>
<ScrollView android:id="@+id/scrollView1"
    android:layout_height="wrap_content" android:layout_width="match_parent"
    android:layout_weight="1"
    >
    <LinearLayout android:id="@+id/linearLayout1"
        android:layout_width="match_parent" android:layout_height="match_parent"
        android:orientation="vertical"
        >
        <TextView android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="TextView" android:layout_height="wrap_content"
            android:id="@+id/textView1" android:layout_width="wrap_content">
            </TextView>
      <ImageView android:id="@+id/imageView1" android:src="@drawable/ic_launcher"
          android:layout_height="wrap_content" android:layout_width="wrap_content"
          android:layout_gravity="center_horizontal"></ImageView>
      <TextView android:textAppearance="?android:attr/textAppearanceSmall"
          android:text="TextView" android:layout_height="wrap_content"
          android:layout_gravity="right" android:id="@+id/textView2"
          android:layout_width="wrap_content"
          ></TextView>
      <TextView android:textAppearance="?android:attr/textAppearanceMedium"
          android:text="TextView" android:layout_height="wrap_content"
          android:id="@+id/textView3" android:layout_width="match_parent"
          ></TextView>
      </LinearLayout>
</ScrollView>
<Button android:id="@+id/button1" android:layout_height="wrap_content"
    android:layout_width="match_parent" android:text="창닫기"
    android:layout_marginTop="10dp"
    ></Button>
</LinearLayout>



-----------------------------------*---------------------------------



[list_row.xml]

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp" android:id="@+id/linearLayout1"
>
        <LinearLayout android:orientation="vertical"
            android:layout_width="match_parent" android:layout_height="wrap_content"
            android:id="@+id/linearLayout2"
            >
            <TextView android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="TextView" android:layout_height="wrap_content" android:id="@+id/textview1"
                android:layout_width="match_parent" android:ellipsize="end"
                android:lines="1"></TextView>
            <TextView android:textAppearance="?android:attr/textAppearanceSmall"
                android:text="TextView" android:layout_height="wrap_content" android:id="@+id/textview2"
                android:layout_width="match_parent"   android:lines="2" android:ellipsize="end"
              ></TextView>
               <TextView android:textAppearance="?android:attr/textAppearanceSmall"
                android:text="TextView" android:layout_height="wrap_content" android:id="@+id/textview3"
                android:layout_width="match_parent"   android:gravity="right"
              ></TextView>
        </LinearLayout>
</LinearLayout>

2개의 답변

0 추천
책에서 제공하는 소스라면 그대로 돌리면 될텐데요.. 인터넷 권한은 줬는지 확인해보시길 바랍니다.
인연 (31,880 포인트) 님이 2014년 5월 1일 답변
넵 인터넷권한을 줬는데도 상황이 같아요 ㅠ 책이랑 똑같이하면 실행이 아예 안되어서 조금 바꿨는데 안나오네요..
0 추천
머 소스의 경우 보기 힘들어 자세히 들여다 보지 못했습니다~!

대충 봤습니다~!

그런데.... 네트워크 작업을 메인쓰레드에서 진행 한걸로 보입니다~!

그래서 책의 발행일을 보니 역시나 굉장히 오래된 책이군요~~!

안드로이드에서는 성능상의 이유로 진저이후 시간이 오래걸릴 가능성이 있는 작업의

 경우 메인 쓰레드가 아닌 별도의 쓰레드에서 작업하도록 업데이트 되었습니다.

해당 서적은 위 업데이트가 이루어지기 전에 발행되어 이 부분이 빠진듯 보입니다~~!

확인 해보세요~~! ^^;
ThisPlus (46,920 포인트) 님이 2014년 5월 1일 답변
답변 너무 감사드립니다! 그러면 아예 소스를 뜯어고쳐야 되는걸까요? ㅠㅜ
...