원격지 파일(json) 가져와 화면에 출력
참고url : https://www.javatpoint.com/volley-library-fetching-json-data-from-url
원격지에서 가져올 json 파일
{
"tutorials":[
{
"name":"Java",
"imageurl":"https://www.javatpoint.com/images/logo/javahome.png",
"description":"Java is a high level, robust, object-oriented and secure programming language."
},
{
"name":"Android",
"imageurl":"https://www.javatpoint.com/images/logo/androidhome.png",
"description":"Android is a complete set of software for mobile devices."
},
{
"name":"Python",
"imageurl":"https://www.javatpoint.com/images/logo/pythonhome.png",
"description":"Python is a general purpose, dynamic, high level and interpreted programming language."
},
{
"name":"C++",
"imageurl":"https://www.javatpoint.com/cpp/images/cpp-home.png",
"description":"C++ is an object-oriented programming language."
}
]
}
MainActivity.java
package com.example.mycoupang;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.ContentValues;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
ListView listView;
private static final String JSON_URL = "http://zzz.com/android.php";
//the tutorial list where we will store all the tutorial objects after parsing json
List<Tutorial> tutorialList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//세로모드
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("리뷰좋아");
/*
final ImageView img1 = findViewById(R.id.imageView2);
img1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://zzzz.com/?p=asdfaHR0cHM6Ly9jb3VwYS5uZy9iNTFqQTk="));
startActivity(intent);
}
});
*/
listView = (ListView) findViewById(R.id.listView);
tutorialList = new ArrayList<>();
//this method will fetch and parse the data
loadTutorialList();
}
private void loadTutorialList() {
//getting the progressbar
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
//creating a string request to send request to the url
StringRequest stringRequest = new StringRequest(Request.Method.GET, JSON_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//hiding the progressbar after completion
progressBar.setVisibility(View.INVISIBLE);
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response);
//we have the array named tutorial inside the object
//so here we are getting that json array
JSONArray tutorialsArray = obj.getJSONArray("naya");
//now looping through all the elements of the json array
for (int i = 0; i < tutorialsArray.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject tutorialsObject = tutorialsArray.getJSONObject(i);
//creating a tutorial object and giving them the values from json object
Tutorial tutorial = new Tutorial(tutorialsObject.getString("name"), tutorialsObject.getString("img"),tutorialsObject.getString("address"));
//adding the tutorial to tutoriallist
tutorialList.add(tutorial);
}
//creating custom adapter object
MyAdapter adapter = new MyAdapter(tutorialList, getApplicationContext());
//adding the adapter to listview
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occur
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//adding the string request to request queue
requestQueue.add(stringRequest);
}
}
activity_main.xml
<?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"
android:orientation="vertical"
tools:context=".MainActivity">
<ImageView android:id="@+id/imageView2"
android:layout_width="380dp"
android:layout_height="80dp"
android:scaleType="fitCenter"
app:srcCompat="@drawable/main_coupang" />
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginBottom="292dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>
list_item.xml
<?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="match_parent"
android:padding="16dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="@+id/imageView"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@drawable/cupang"
android:contentDescription="image view" />
<TextView
android:id="@+id/textViewName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="title"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />
</LinearLayout>
<TextView
android:id="@+id/textViewImageUrl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="url"
android:autoLink="web"
android:textColor="#08308e" />
</LinearLayout>
MyAdapter.java
package com.example.mycoupang;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.squareup.picasso.Picasso;
import java.util.List;
public class MyAdapter extends ArrayAdapter<Tutorial> {
//the tutorial list that will be displayed
private List<Tutorial> tutorialList;
private Bitmap bitmap;
private Context mCtx;
//here we are getting the tutoriallist and context
//so while creating the object of this adapter class we need to give tutoriallist and context
public MyAdapter(List<Tutorial> tutorialList, Context mCtx) {
super(mCtx, R.layout.list_item, tutorialList);
this.tutorialList = tutorialList;
this.mCtx = mCtx;
}
//this method will return the list item
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//getting the layoutinflater
ViewHolder holder;
LayoutInflater inflater = LayoutInflater.from(mCtx);
convertView = inflater.inflate(R.layout.list_item, null, true);
holder = new ViewHolder();
//getting text views
holder.textViewName = convertView.findViewById(R.id.textViewName);
holder.textDescription = convertView.findViewById(R.id.textViewImageUrl);
holder.imageView = convertView.findViewById(R.id.imageView);
convertView.setTag(holder);
//Getting the tutorial for the specified position
Tutorial tutorial = tutorialList.get(position);
String imageUrl = tutorial.getImageUrl();
String tutorialDescription = tutorial.getDescription();
String tutorialTitle = tutorial.getName();
holder.textViewName.setText(tutorialTitle);
holder.textDescription.setText(tutorialDescription);
if (holder.imageView != null) {
/*-------------fatching image------------*/;
new ImageDownloaderTask(holder.imageView).execute(imageUrl);
}
holder.imageView.setImageBitmap(bitmap);
return convertView;
}
static class ViewHolder {
TextView textViewName;
TextView textDescription;
ImageView imageView;
}
}
ImageDownloaderTask.java
package com.example.mycoupang;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;
import org.apache.http.HttpStatus;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
public class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public ImageDownloaderTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
@Override
protected Bitmap doInBackground(String... params) {
return downloadBitmap(params[0]);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
Drawable placeholder = imageView.getContext().getResources().getDrawable(R.drawable.cupang);
imageView.setImageDrawable(placeholder);
}
}
}
}
private Bitmap downloadBitmap(String imageUrl) {
HttpURLConnection urlConnection = null;
try {
URL uri = new URL(imageUrl);
urlConnection = (HttpURLConnection) uri.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
}
catch (Exception e) {
urlConnection.disconnect();
Log.w("ImageDownloader", "Error downloading image from " + imageUrl);
}
finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
}
Tutorial.java
package com.example.mycoupang;
public class Tutorial {
String name, imageUrl, description;
public Tutorial(String name, String imageUrl, String description) {
this.name = name;
this.imageUrl = imageUrl;
this.description = description;
}
public String getName() {
return name;
}
public String getImageUrl() {
return imageUrl;
}
public String getDescription() {
return description;
}
}
'프로그래밍 > Android' 카테고리의 다른 글
안드로이드 TCP Socket + Webview bridge 샘플 (0) | 2023.02.27 |
---|---|
android socket (소켓통신) 샘플 (0) | 2023.02.20 |
[안드로이드] 웹뷰 + 카카오톡 적용 (0) | 2022.02.04 |
[android] net::ERR_UNKNOWN_URL_SCHEME (0) | 2022.02.04 |
안드로이드 Recyclerview + php json 사용시 오류 (0) | 2021.10.21 |