본문 바로가기

JAVA/Android

안드로이드 DaumAPI를 활용한 도서검색 예제 따라하기

- Daum에서 제공하는 API를 활용해서 도서검색 App을 만들어보자.
- 따로 서버를 두지 않고 데이터를 사용 API를 활용해서 데이터를 활용 할 수 있다.
- 퍼미션 추가는 잊지말자.

-Java 소스 
public class Ex14_DaumapiActivity extends Activity implements OnClickListener,
OnItemClickListener {
ArrayList<MyItem> mItems;
CustomAdater mAdapter;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

mItems = new ArrayList<MyItem>();

mAdapter = new CustomAdater(this, R.layout.item, mItems);
ListView list = (ListView) this.findViewById(R.id.list);
list.setAdapter(mAdapter);
list.setOnItemClickListener(this);

Button btn = (Button) this.findViewById(R.id.button1);
btn.setOnClickListener(this);
}

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {

case R.id.button1:
EditText edit = (EditText) this.findViewById(R.id.editname);
String mName = edit.getText().toString();
if (mName != null) {
mItems.clear();
String url = "http://apis.daum.net/search/book?q=" + mName
+ "&apikey=af0374a169c37f9d94ee8f47da127252d0d5e975";
JXMLParser jxml = new JXMLParser(this);
String xml = jxml.downloadURL(url);
jxml.parseXML(xml, mItems);

// String xml = downloadURL(url);
// parseXML(xml);
mAdapter.notifyDataSetChanged();

}

break;
}

}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent(this, BookLink.class);
intent.putExtra("param1", mItems.get(arg2).booklink);
startActivity(intent);

}

-------------------------------------------------------------------------------------------------------
public class JXMLParser { //파싱해서 tag 짜르는 클래스
Context mContext;

public JXMLParser(Context context) {
// TODO Auto-generated constructor stub
mContext = context;
}

void parseXML(String xml, ArrayList<MyItem> arrayItems) {
// TODO Auto-generated method stub
int itemtype = 0;
int startItem = 0;

String coverImage = "";
String author = "";
String publisher = "";
String title = "";
String pubdate = "";
String booklink = "";

try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
parser.setInput(new StringReader(xml));

int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.END_DOCUMENT:
break;
case XmlPullParser.START_TAG:
if (parser.getName().equals("cover_s_url")) {
itemtype = 1;
}
if (parser.getName().equals("author")) {
itemtype = 2;
}
if (parser.getName().equals("pub_nm")) {
itemtype = 3;
}
if (parser.getName().equals("title")) {
itemtype = 4;
}
if (parser.getName().equals("pub_date")) {
itemtype = 5;
}
if (parser.getName().equals("link")) {
itemtype = 6;
}
if (parser.getName().equals("item")) {
startItem = 1;
}
break;
case XmlPullParser.END_TAG:
if (parser.getName().equals("item")) {
arrayItems.add(new MyItem(coverImage, author,
publisher, title, pubdate, booklink));
coverImage = "";
author = "";
publisher = "";
title = "";
pubdate = "";
booklink = "";
}
break;
case XmlPullParser.TEXT:
if (startItem == 0) {
break;
}
if (itemtype == 1) {
coverImage = parser.getText();
}
if (itemtype == 2) {
author = parser.getText();
}
if (itemtype == 3) {
publisher = parser.getText();
}
if (itemtype == 4) {
title = parser.getText();
}
if (itemtype == 5) {
pubdate = parser.getText();
}
if (itemtype == 6) {
booklink = parser.getText();
}
itemtype = 0;
break;
}
eventType = parser.next();
}
} catch (Exception e) {
;
}
}

String downloadURL(String addr) {
ProgressDialog mProgress = ProgressDialog.show(mContext, "Wait",
"Downloading...");
String doc = "";
try {
URL url = new URL(addr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

if (conn != null) {
conn.setConnectTimeout(10000);
conn.setUseCaches(false);
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
for (;;) {
String line = br.readLine();
if (line == null)
break;
doc = doc + line + "\n";
}
br.close();
}
conn.disconnect();
}
} catch (Exception ex) {
;
}

mProgress.dismiss();
return doc;
}

}
-------------------------------------------------------------------------------------------------------
public class MyItem { //파싱한 데이터 가져올 클래스
String coverImage, author, publisher, title, pubdate, booklink;

public MyItem(String arg0, String arg1, String arg2, String arg3,
String arg4, String arg5) {
this.coverImage = arg0;
this.author = arg1;
this.publisher = arg2;
this.title = arg3;
this.pubdate = arg4;
this.booklink = arg5;
}
}
-------------------------------------------------------------------------------------------------------
public class CustomAdater extends BaseAdapter { //리스트를 보여주기위한 BaseAdapter
Context context;
int itemlayout; 
ArrayList<MyItem> arrayItems;
LayoutInflater inflater;
public CustomAdater(Context c, int sublayout, ArrayList<MyItem> list){
this.context=c;
this.itemlayout=sublayout;
this.arrayItems=list;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return arrayItems.size();
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrayItems.get(position);
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final int pos = position;
if(convertView == null){
convertView = inflater.inflate(itemlayout, parent,false);
}
ImageView img = (ImageView)convertView.findViewById(R.id.image1);
//img.setImageResource(arrayItems.get(position).image);
//img.setImageResource(R.drawable.icon);//초기화
try{
InputStream is = new URL(arrayItems.get(position).coverImage).openStream();
Bitmap bit = BitmapFactory.decodeStream(is); // Factory 비트맵 다운로드
img.setImageBitmap(bit);
is.close();
}
catch(Exception e){
img.setImageResource(R.drawable.icon);
}
TextView text1 = (TextView)convertView.findViewById(R.id.text1);
text1.setText(arrayItems.get(position).author+
"  "+arrayItems.get(position).publisher);
TextView text2 = (TextView)convertView.findViewById(R.id.text2);
text2.setText(arrayItems.get(position).title);
TextView text3 = (TextView)convertView.findViewById(R.id.text3);
text3.setText(arrayItems.get(position).pubdate);
return convertView;
}

}
--------------------------------------------------------------------------------------------------------
public class BookLink extends Activity implements OnClickListener { //검색된 리스트를 눌렸을때 다음 웹뷰
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.booklink);

Intent intent = getIntent();
String booklink = intent.getStringExtra("param1");

WebView web1 = (WebView) this.findViewById(R.id.web1);
web1.setWebViewClient(new WebViewClient());

WebSettings set = web1.getSettings();
set.setJavaScriptEnabled(true);
set.setBuiltInZoomControls(true);

web1.loadUrl(booklink);

Button btn = (Button) this.findViewById(R.id.btn1web);
btn.setOnClickListener(this);

}

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();

}
}
-------------------------------------------------------------------------------------------------------
-xml 소스 
<!--main.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:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/editname"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:text="load" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:orientation="vertical" >

        <ListView
            android:id="@+id/list"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >
        </ListView>
    </LinearLayout>

</LinearLayout>
 -------------------------------------------------------------------------------------------------------
<!--booklink.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:orientation="vertical" >

    <WebView
        android:id="@+id/web1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

    <Button
        android:id="@+id/btn1web"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:text="돌아가기" />

</LinearLayout>
-------------------------------------------------------------------------------------------------------
<!--item.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:orientation="horizontal" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_weight="0"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/image1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/text1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <TextView
            android:id="@+id/text2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="5" />

        <TextView
            android:id="@+id/text3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
    </LinearLayout>

</LinearLayout> 

- AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="Ex14_Daumapi.org"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="7" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Ex14_DaumapiActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".BookLink"
                  android:label="@string/app_name">
         </activity>

    </application>
         <uses-permission 
    android:name="android.permission.INTERNET"/>
</manifest>

-실행 화면