제목을 누르면 제목을 가지고 가서 새창에 출력됩니다.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.ex16.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edtsearch"
android:hint="검색어 입력"
android:padding="10sp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_search"
android:layout_alignParentRight="true"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_below="@id/edtsearch"
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/btnmore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
app:srcCompat="@drawable/ic_more"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_marginRight="20sp"
android:layout_marginBottom="20sp"/>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10sp"
android:background="#9bbbd4">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="여기는 제목이 출력됩니다."
android:textSize="15sp"
android:textColor="#000000"
android:singleLine="true"
android:id="@+id/txttitle"
android:background="#ffffff"
android:padding="10sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="여기는 내용이 출력됩니다."
android:textSize="12sp"
android:textColor="#000000"
android:singleLine="true"
android:id="@+id/txtdesc"
android:padding="10sp"/>
</LinearLayout>
package com.example.ex16;
import java.net.*;
import java.io.*;
public class NaverAPI {
//결과 값을 받기 위해서 return
public static String main(String query,int start) {
//static: 클래스 생성없이 메서드 사용가능
String clientId = "r_XLF45OBi3Xw08BTmvq";//애플리케이션 클라이언트 아이디값";
String clientSecret = "DjUKEbgt13";//애플리케이션 클라이언트 시크릿값";
try {
String text = URLEncoder.encode(query, "UTF-8");
String apiURL = "https://openapi.naver.com/v1/search/blog?query="+ text; // json 결과
//String apiURL = "https://openapi.naver.com/v1/search/blog.xml?query="+ text; // xml 결과
apiURL += "&start=" + start;
URL url = new URL(apiURL);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("X-Naver-Client-Id", clientId);
con.setRequestProperty("X-Naver-Client-Secret", clientSecret);
int responseCode = con.getResponseCode();
BufferedReader br;
if(responseCode==200) { // 정상 호출
br = new BufferedReader(new InputStreamReader(con.getInputStream()));
} else { // 에러 발생
br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
}
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = br.readLine()) != null) {
response.append(inputLine);
}
br.close();
System.out.println(response.toString());
return response.toString();
} catch (Exception e) {
System.out.println(e);
return e.toString();
}
}
}
package com.example.ex16;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import com.example.ex16.R;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
int start=1;
//초기값 설정
RecyclerView list;
BlogAdapter adapter;
String query="커피";
//데이터 저장할 곳
ArrayList<BlogVO> array;
//NaverAPI를 실행하는 곳
//Thread:작업
//멀티
//MainThread
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("블로그 검색");
list=findViewById(R.id.list);
LinearLayoutManager manager=new LinearLayoutManager(this);
list.setLayoutManager(manager);
array=new ArrayList<BlogVO>();
//MainActivity가 실행이 될때 NaverThread 실행
new NaverThread().execute();
final EditText edtsearch=findViewById(R.id.edtsearch);
edtsearch.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
start =1;
array.clear();
query=edtsearch.getText().toString();
//Toast.makeText(MainActivity.this,query,Toast.LENGTH_SHORT).show();
new NaverThread().execute();
return false;
}
});
FloatingActionButton btnmore=findViewById(R.id.btnmore);
btnmore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
start += 10;
new NaverThread().execute();
}
});
}
//BackThread
class NaverThread extends AsyncTask<String, String, String>{
//doinbackground실행후 post로 감
@Override
protected String doInBackground(String... strings) {
//결과값이 콘솔에만 찍힘->결과값을 받기위해 리턴
//NaverAPI.main(query);
//array생성
return NaverAPI.main(query,start);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
System.out.println("결과:" +s);
//결과를 하나씩 분석
//데이터 만듦
try {
//items값을 가져온다.
JSONArray jArray=new JSONObject(s).getJSONArray("items");
for(int i=0; i<jArray.length(); i++){
//하나씩 하나씩 꺼내오는 것은 object
JSONObject obj=jArray.getJSONObject(i);
BlogVO vo=new BlogVO();
vo.setTitle(obj.getString("title"));
vo.setDescription(obj.getString("description"));
vo.setLink(obj.getString("link"));
array.add(vo);
System.out.println(vo.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter=new BlogAdapter(array,MainActivity.this);
list.setAdapter(adapter);
list.scrollToPosition(start);
}
}
}
package com.example.ex16;
public class BlogVO {
private String title;
private String link;
private String description;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "BlogVO{" +
"title='" + title + '\'' +
", link='" + link + '\'' +
", description='" + description + '\'' +
'}';
}
}
BlogAdapter.java
package com.example.ex16;
import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.ex16.R;
import java.util.ArrayList;
public class BlogAdapter extends RecyclerView.Adapter<BlogAdapter.ViewHolder> {
ArrayList<BlogVO> array;
Context context;
//생성을 할때 array값과 context값을 받아서 생성을 해준다.
public BlogAdapter(ArrayList<BlogVO> array, Context context) {
this.array = array;
this.context = context;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
//view 생성
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.item,null);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
final String title=array.get(position).getTitle();
String link=array.get(position).getTitle();
//Html.fromHtml:태그를 제거하고 html으로 뽐아내는것
holder.txttitle.setText(Html.fromHtml("<u>" +array.get(position).getTitle()+"</u>"));
holder.txtdesc.setText(Html.fromHtml(array.get(position).getDescription()));
holder.txttitle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(context,DetailActivity.class);
//제목을 가져감
intent.putExtra("title",title);
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return array.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView txttitle,txtdesc;
public ViewHolder(@NonNull View itemView) {
super(itemView);
txttitle=itemView.findViewById(R.id.txttitle);
txtdesc=itemView.findViewById(R.id.txtdesc);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.ex16.DetailActivity"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/txttitle"
android:textSize="20sp"
android:text="여기에 출력합니다."
android:padding="10sp"
android:gravity="center"/>
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/web"/>
</LinearLayout>
'Android' 카테고리의 다른 글
다음API(지도검색+구글맵) (0) | 2019.11.18 |
---|---|
네이버 API를 이용한 도서검색,더보기 (2) | 2019.11.15 |
네이버 API 뉴스 검색 (0) | 2019.11.14 |
주소록 만들기 (0) | 2019.11.14 |
RecyclerView를 이용한 상품목록만들기 (0) | 2019.11.13 |