Android- API 검색 (지역, 쇼핑, 영화)
- 안드로이드 어플만들기
-> 지역검색이 가능하고 쇼핑검색 그리고 영화검색이 가능한 기능을 구현할것이다.
먼저 총 생성한 파일들의 모습으로는 아래 그림과 같다.
1. 메인
Kakao.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Kakao {
public static String connect(String apiURL) {
try {
URL url = new URL(apiURL);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Authorization", "KakaoAK 04ce4bf8002de6c8466523c16b6de483");
int responseCode = con.getResponseCode();
BufferedReader br;
if(responseCode==200) { // 정상 호출인 경우
br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
} 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) {
return e.toString();
}
}
}
Naver
package com.example.ex10;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class Naver {
public static String connect(String url, String query) {
String clientId = "DC8ojH4p4RE2lMhourmV"; //애플리케이션 클라이언트 아이디값"
String clientSecret = "1KTqGCjPFg"; //애플리케이션 클라이언트 시크릿값"
String text = null;
try {
text = URLEncoder.encode(query, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("검색어 인코딩 실패",e);
}
String apiURL = url +"?query=" + text; // json 결과
//String apiURL = "https://openapi.naver.com/v1/search/blog.xml?query="+ text; // xml 결과
Map<String, String> requestHeaders = new HashMap<>();
requestHeaders.put("X-Naver-Client-Id", clientId);
requestHeaders.put("X-Naver-Client-Secret", clientSecret);
String responseBody = get(apiURL,requestHeaders);
System.out.println(responseBody);
return responseBody;
}
private static String get(String apiUrl, Map<String, String> requestHeaders){
HttpURLConnection con = connect(apiUrl);
try {
con.setRequestMethod("GET");
for(Map.Entry<String, String> header :requestHeaders.entrySet()) {
con.setRequestProperty(header.getKey(), header.getValue());
}
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // 정상 호출
return readBody(con.getInputStream());
} else { // 에러 발생
return readBody(con.getErrorStream());
}
} catch (IOException e) {
throw new RuntimeException("API 요청과 응답 실패", e);
} finally {
con.disconnect();
}
}
private static HttpURLConnection connect(String apiUrl){
try {
URL url = new URL(apiUrl);
return (HttpURLConnection)url.openConnection();
} catch (MalformedURLException e) {
throw new RuntimeException("API URL이 잘못되었습니다. : " + apiUrl, e);
} catch (IOException e) {
throw new RuntimeException("연결이 실패했습니다. : " + apiUrl, e);
}
}
private static String readBody(InputStream body){
InputStreamReader streamReader = new InputStreamReader(body);
try (BufferedReader lineReader = new BufferedReader(streamReader)) {
StringBuilder responseBody = new StringBuilder();
String line;
while ((line = lineReader.readLine()) != null) {
responseBody.append(line);
}
return responseBody.toString();
} catch (IOException e) {
throw new RuntimeException("API 응답을 읽는데 실패했습니다.", e);
}
}
}
MainActivity
package com.example.ex10;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.LinearLayout;
import com.google.android.material.tabs.TabLayout;
public class MainActivity extends AppCompatActivity {
DrawerLayout drawer;
LinearLayout open;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("API검색");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu);
drawer= findViewById(R.id.drawer);
open = findViewById(R.id.open_drawer);
TabLayout tab = findViewById(R.id.tab);
tab.addTab(tab.newTab().setText("지역"));
tab.addTab(tab.newTab().setText("쇼핑"));
tab.addTab(tab.newTab().setText("영화"));
tab.getTabAt(0).setIcon(R.drawable.ic_local);
tab.getTabAt(1).setIcon(R.drawable.ic_shop);
tab.getTabAt(2).setIcon(R.drawable.ic_baseline_movie_24);
PagerAdapter pagerAdapter = new pagerAdapter(getSupportFragmentManager());
final ViewPager pager = findViewById(R.id.pager);
pager.setAdapter(pagerAdapter);
//viewpager를 드래그한경우
pager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tab));
tab.addOnTabSelectedListener(new TabLayout.BaseOnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch(item.getItemId()){
case android.R.id.home:
if(drawer.isDrawerOpen(open)){
drawer.closeDrawer(open);
}else {
drawer.openDrawer(open);
}
break;
}
return super.onOptionsItemSelected(item);
}
//어댑터 정의
class pagerAdapter extends FragmentPagerAdapter{
public pagerAdapter(@NonNull FragmentManager fm) {
super(fm);
}
@NonNull
@Override
public Fragment getItem(int position) {
switch(position){
case 0:
return new LocalFragment();
case 1:
return new ShopFragment();
case 2:
return new MovieFragment();
default:
return null;
}
}
@Override
public int getCount() {
return 3;
}
}
}
1. 지역검색
LocalFragment
package com.example.ex10;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class LocalFragment extends Fragment {
String url ="https://dapi.kakao.com/v2/local/search/keyword.json?";
String strQuery ="인천 버거킹";
JSONArray array= new JSONArray();
LocalAdapter localAdapter = new LocalAdapter();
int page=1;
boolean is_end=false;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.fragment_local, container, false);
new LocalThread().execute();
RecyclerView list = view.findViewById(R.id.list);
list.setAdapter(localAdapter);
list.setLayoutManager(new LinearLayoutManager(getActivity()));
final EditText query = view.findViewById(R.id.query);
query.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
strQuery = query.getText().toString();
array = new JSONArray();
page=1;
new LocalThread().execute();
}
});
//더보기 버튼을 클릭한 경우
FloatingActionButton more =view. findViewById(R.id.more);
more.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(is_end){
Toast.makeText(getActivity(),"마지막 데이터입니다.",Toast.LENGTH_SHORT).show();
}else{
page++;
new LocalThread().execute();
}
}
});
return view;
}
//로컬쓰레드
class LocalThread extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... strings) {
return Kakao.connect(url+"query="+strQuery+"&page"+page);
}
@Override
protected void onPostExecute(String s) {
try {
JSONArray newArray = new JSONObject(s).getJSONArray("documents");
JSONObject meta = new JSONObject(s).getJSONObject("meta");
is_end= meta.getBoolean("is_end");
for(int i=0; i<newArray.length(); i++){
array.put(newArray.getJSONObject(i));
}
localAdapter.notifyDataSetChanged();
} catch (JSONException e) {e.printStackTrace(); }
super.onPostExecute(s);
}
}
//어댑터
class LocalAdapter extends RecyclerView.Adapter<LocalAdapter.ViewHolder>{
@NonNull
@Override
public LocalAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = getActivity().getLayoutInflater().inflate(R.layout.item_local, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull LocalAdapter.ViewHolder holder, int position) {
try {
final JSONObject obj = array.getJSONObject(position);
final String strName = obj.getString("place_name");
String strAddress = obj.getString("address_name");
final String strTel =obj.getString("phone");
final String x = obj.getString("x");
final String y = obj.getString("y");
holder.name.setText(String.valueOf(position+1)+":"+strName);
holder.address.setText(strAddress);
holder.tel.setText(strTel);
//전화번호를 클릭한 경우
holder.tel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Uri number = Uri.parse("tel" +strTel);
Intent intent = new Intent(Intent.ACTION_DIAL, number);
getActivity().startActivity(intent);
}
});
holder.address.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), MapsActivity.class);
intent.putExtra("x",x);//경도
intent.putExtra("y",y); //위도
intent.putExtra("name",strName);
getActivity().startActivity(intent);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public int getItemCount() {
return array.length();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView name, address, tel;
public ViewHolder(@NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name);
address = itemView.findViewById(R.id.address);
tel = itemView.findViewById(R.id.tel);
}
}
}
}
MapsActivity
package com.example.ex10;
import androidx.fragment.app.FragmentActivity;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
Double x;
Double y;
String name;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
Intent intent = getIntent();
x=Double.parseDouble(intent.getStringExtra("x"));
y=Double.parseDouble(intent.getStringExtra("y"));
name = intent.getStringExtra("name");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng sydney = new LatLng(y, x);
mMap.addMarker(new MarkerOptions().position(sydney).title(name));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.moveCamera(CameraUpdateFactory.zoomTo(15));
}
}
fragment_local
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".LocalFragment">
<EditText
android:id="@+id/query"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="검색어"
android:padding="20sp"
android:textSize="20sp"
android:fontFamily="@font/ho"/>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/query" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/more"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="#00539C"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="10sp"
android:src="@drawable/ic_down"
app:borderWidth="0sp"/>
</RelativeLayout>
item_local
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="10sp"
app:cardCornerRadius="20sp"
android:id="@+id/item">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#FFD662"
android:padding="10sp">
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="여기에는 장소명을 출력"
android:lines="1"
android:ellipsize="end"
android:fontFamily="@font/kang"/>
<TextView
android:id="@+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="여기에는 주소를 출력"
android:lines="1"
android:ellipsize="end"
android:fontFamily="@font/kang"/>
<TextView
android:id="@+id/tel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="여기에는 전화번호를 출력"
android:lines="1"
android:ellipsize="end"
android:fontFamily="@font/kang"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
버거킹을 검색했을때 결과가 나오는것을 볼수있다!.
2. 쇼핑검색
ShopActivity
package com.example.ex10;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class ShopActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shop);
Intent intent = getIntent();
String title = intent.getStringExtra("title");
getSupportActionBar().setTitle(Html.fromHtml(title));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
String url = intent.getStringExtra("url");
WebView web = findViewById(R.id.web);
web.setWebViewClient(new MyWebView());
WebSettings webSettings =web.getSettings();
webSettings.setJavaScriptEnabled(true);
web.loadUrl(url);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch(item.getItemId()){
case android.R.id.home:
finish();
}
return super.onOptionsItemSelected(item);
}
class MyWebView extends WebViewClient{
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
@Override
public void onPageFinished(WebView view, String url) {
ProgressBar progressBar= findViewById(R.id.progress);
progressBar.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
}
}
ShopFragment
package com.example.ex10;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DecimalFormat;
public class ShopFragment extends Fragment {
String url ="https://openapi.naver.com/v1/search/shop.json";
String strQuery="노트북";
JSONArray array = new JSONArray();
ShopAdapter shopAdapter =new ShopAdapter();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.fragment_local, container, false);
new ShopThread().execute();
RecyclerView list= view.findViewById(R.id.list);
list.setAdapter(shopAdapter);
list.setLayoutManager(new LinearLayoutManager(getActivity()));
final EditText query = view.findViewById(R.id.query);
query.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
strQuery = query.getText().toString();
array = new JSONArray();
new ShopThread().execute();
}
});
return view;
}
//쇼핑쓰레드
class ShopThread extends AsyncTask<String, String, String>{
@Override
protected String doInBackground(String... strings) {
return Naver.connect(url, strQuery);
}
@Override
protected void onPostExecute(String s) {
try {
JSONArray newArray = new JSONObject(s).getJSONArray("items");
for(int i=0; i<newArray.length(); i++){
array.put(newArray.getJSONObject(i));
}
shopAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(s);
}
}
//쇼핑 어댑터
class ShopAdapter extends RecyclerView.Adapter<ShopAdapter.ViewHolder>{
@NonNull
@Override
public ShopAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view =getActivity().getLayoutInflater().inflate(R.layout.item_shop, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ShopAdapter.ViewHolder holder, int position) {
try {
JSONObject obj = array.getJSONObject(position);
final String title = obj.getString("title");
DecimalFormat df=new DecimalFormat("#,###원");
String price = df.format(obj.getInt("lprice"));
final String shop = obj.getString("mallName");
final String image = obj.getString("image");
final String link = obj.getString("link");
holder.title.setText(String.valueOf(position+1)+":<b>"+ Html.fromHtml(title));
holder.price.setText(price);
holder.shop.setText(shop);
Picasso.with(getActivity()).load(image).into(holder.image);
holder.item.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ShopActivity.class);
intent.putExtra("title",title);
intent.putExtra("title",title);
intent.putExtra("url",link);
getActivity().startActivity(intent);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public int getItemCount() {
return array.length();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CardView item;
ImageView image;
TextView title, price, shop;
public ViewHolder(@NonNull View itemView) {
super(itemView);
image= itemView.findViewById(R.id.image);
title = itemView.findViewById(R.id.title);
price = itemView.findViewById(R.id.price);
shop=itemView.findViewById(R.id.shop);
item = itemView.findViewById(R.id.item);
}
}
}
}
item_shop
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="10sp"
app:cardCornerRadius="20sp"
android:id="@+id/item">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/image"
android:layout_width="70sp"
android:layout_height="60sp"
android:src="@mipmap/ic_launcher"
android:layout_marginRight="30sp" />
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="상품명"
android:layout_toRightOf="@id/image"
android:lines="1"
android:ellipsize="end"
android:fontFamily="@font/kang"
/>
<TextView
android:id="@+id/price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="가격"
android:layout_toRightOf="@id/image"
android:layout_below="@id/title"
android:lines="1"
android:ellipsize="end"
android:fontFamily="@font/kang"/>
<TextView
android:id="@+id/shop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="판매처"
android:layout_toRightOf="@id/image"
android:layout_below="@id/price"
android:src="@mipmap/ic_launcher"
android:fontFamily="@font/kang"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
쇼핑검색이잘된다.
3. 영화검색
MovieActivity
package com.example.ex10;
import androidx.fragment.app.FragmentActivity;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
Double x;
Double y;
String name;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
Intent intent = getIntent();
x=Double.parseDouble(intent.getStringExtra("x"));
y=Double.parseDouble(intent.getStringExtra("y"));
name = intent.getStringExtra("name");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng sydney = new LatLng(y, x);
mMap.addMarker(new MarkerOptions().position(sydney).title(name));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.moveCamera(CameraUpdateFactory.zoomTo(15));
}
}
MovieFragment
package com.example.ex10;
import android.app.AlertDialog;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MovieFragment extends Fragment {
String url ="https://openapi.naver.com/v1/search/movie.json";
String strQuery="노트북";
JSONArray array = new JSONArray();
MovieAdapter movieAdapter=new MovieAdapter();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.fragment_local, container, false);
new MovieThread().execute();
RecyclerView list= view.findViewById(R.id.list);
list.setAdapter(movieAdapter);
list.setLayoutManager(new LinearLayoutManager(getActivity()));
//검색어입력
final EditText query = view.findViewById(R.id.query);
query.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
strQuery = query.getText().toString();
array = new JSONArray();
new MovieThread().execute();
}
});
return view;
}
//영화 쓰레드
class MovieThread extends AsyncTask<String, String,String>{
@Override
protected String doInBackground(String... strings) {
return Naver.connect(url, strQuery);
}
@Override
protected void onPostExecute(String s) {
try {
JSONArray newArray = new JSONObject(s).getJSONArray("items");
for(int i=0; i<newArray.length(); i++){
array.put(newArray.getJSONObject(i));
}
movieAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(s);
}
}
//영화어댑터
class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.ViewHolder>{
@NonNull
@Override
public MovieAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = getActivity().getLayoutInflater().inflate(R.layout.item_movie,parent,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MovieAdapter.ViewHolder holder, int position) {
try {
final JSONObject obj=array.getJSONObject(position);
final String title = obj.getString("title");
final String actor = obj.getString("actor");
final String director = obj.getString("director");
final String image = obj.getString("image");
holder.title.setText(String.valueOf(position+1)+ ":" + Html.fromHtml(title));
holder.actor.setText(actor);
holder.director.setText(director);
if(image!=null && !image.equals(""))
Picasso.with(getActivity()).load(image).into(holder.image);
holder.rating.setRating(Float.parseFloat(obj.getString("userRating")));
holder.item.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LinearLayout layout= (LinearLayout) getLayoutInflater().inflate(R.layout.layout_movie,null);
ImageView timage = layout.findViewById(R.id.image);
TextView tactor = layout.findViewById(R.id.actor);
TextView tdirector = layout.findViewById(R.id.director);
tactor.setText("배우 : "+actor);
tdirector.setText("감독 : "+director);
Picasso.with(getActivity()).load(image).into(timage);
AlertDialog.Builder box = new AlertDialog.Builder(getActivity());
box.setTitle(Html.fromHtml(title));
box.setView(layout);
box.setPositiveButton("닫기",null);
box.show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public int getItemCount() {
return array.length();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView image;
TextView title,actor,director;
CardView item;
RatingBar rating;
public ViewHolder(@NonNull View itemView) {
super(itemView);
image=itemView.findViewById(R.id.image);
title=itemView.findViewById(R.id.title);
actor=itemView.findViewById(R.id.actor);
director=itemView.findViewById(R.id.director);
item=itemView.findViewById(R.id.item);
rating=itemView.findViewById(R.id.rating);
}
}
}
}
item_movie
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="10sp"
app:cardCornerRadius="20sp"
android:id="@+id/item">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/image"
android:layout_width="70sp"
android:layout_height="60sp"
android:src="@mipmap/ic_launcher"
android:layout_marginRight="30sp" />
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="상품명"
android:layout_toRightOf="@id/image"
android:lines="1"
android:ellipsize="end"
android:fontFamily="@font/kang"
/>
<TextView
android:id="@+id/actor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="가격"
android:layout_toRightOf="@id/image"
android:layout_below="@id/title"
android:lines="1"
android:ellipsize="end"
android:fontFamily="@font/kang"/>
<TextView
android:id="@+id/director"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="판매처"
android:layout_toRightOf="@id/image"
android:layout_below="@id/actor"
android:src="@mipmap/ic_launcher"
android:fontFamily="@font/kang"/>
<RatingBar
android:id="@+id/rating"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/director"
android:layout_toRightOf="@id/image"
style="?android:attr/ratingBarStyleSmall"
android:progressTint="#FFD662"
android:numStars="5"
android:stepSize="0.01"
android:layout_marginTop="5sp"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
검색기능에 별점도 가져와서 보여주고, 눌럿을때 영화 이름과 사진 그리고 배우와 감독도 보여진다.
댓글남기기