io.tehtotalpwnage.musicphp_android.AlbumListingAdapter.java Source code

Java tutorial

Introduction

Here is the source code for io.tehtotalpwnage.musicphp_android.AlbumListingAdapter.java

Source

/*
 * Copyright 2017 Michael Nguyen
 *
 * This file is part of Music.php-Android.
 *
 * Music.php-Android is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Music.php-Android is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Music.php-Android.  If not, see <http://www.gnu.org/licenses/>.
 */

package io.tehtotalpwnage.musicphp_android;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

class AlbumListingAdapter extends BaseAdapter {
    private final String TAG = AlbumListingAdapter.class.getSimpleName();

    private Context context;
    private String sAddress;
    private String token;
    private String[][] values;

    AlbumListingAdapter(Context context, String[][] values, String token) {
        this.context = context;
        this.sAddress = context.getSharedPreferences("Prefs", 0).getString("server", null);
        this.token = token;
        this.values = values;
    }

    @Override
    public int getCount() {
        return values.length;
    }

    @Override
    public Object getItem(int position) {
        return values[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View albumView = inflater.inflate(R.layout.album_layout, parent, false);
        ViewHolder holder = new ViewHolder();
        holder.name = (TextView) albumView.findViewById(R.id.textView7);
        holder.artist = (TextView) albumView.findViewById(R.id.textView8);
        holder.image = (ImageView) albumView.findViewById(R.id.imageView4);
        albumView.setTag(holder);

        holder.name.setText(values[position][0]);
        holder.artist.setText(values[position][1]);

        final DownloadImage downloadImage = new DownloadImage();
        downloadImage.execute(values[position][2]);
        try {
            holder.image.setImageDrawable(new BitmapDrawable(context.getResources(), downloadImage.get()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        albumView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.v(TAG, "Attempting to get information for album ID " + values[position][2]);
                StringRequest req = new StringRequest(Request.Method.GET,
                        sAddress + "/api/albums/" + values[position][2], new Response.Listener<String>() {
                            public void onResponse(String response) {
                                try {
                                    JSONArray json = new JSONObject(response).getJSONArray("tracks");
                                    String[][] tracks = new String[json.length()][2];
                                    for (int i = 0; i < json.length(); i++) {
                                        JSONObject object = json.getJSONObject(i);
                                        tracks[i][0] = object.getString("id");
                                        tracks[i][1] = object.getString("title");
                                    }
                                    Intent intent = new Intent(context, AlbumActivity.class);
                                    intent.putExtra("album", tracks);
                                    intent.putExtra("token", token);
                                    Log.d(TAG, "Writing Bitmap to storage");
                                    File rootDir = new File(context.getFilesDir(), "albums");
                                    rootDir.mkdirs();
                                    FileOutputStream stream = new FileOutputStream(
                                            new File(rootDir, values[position][2] + ".jpg"));
                                    downloadImage.get().compress(Bitmap.CompressFormat.JPEG, 100, stream);
                                    stream.close();
                                    Log.d(TAG, "File writing complete");
                                    intent.putExtra("art", values[position][2] + ".jpg");
                                    context.startActivity(intent);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {

                            }
                        }) {
                    @Override
                    public Map<String, String> getHeaders() {
                        Map<String, String> params = new HashMap<>();
                        params.put("Accept", "application/json");
                        params.put("Authorization", "Bearer " + token);
                        return params;
                    }
                };
                VolleySingleton.getInstance(context).addToRequestQueue(req);
            }
        });

        return albumView;
    }

    private static class ViewHolder {
        TextView name;
        TextView artist;
        ImageView image;
    }

    private class DownloadImage extends AsyncTask<String, Integer, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... params) {
            return downloadImage(params[0]);
        }

        private Bitmap downloadImage(String url) {
            try {
                Log.d(TAG, "Fetching album art for album " + url);
                HttpURLConnection conn = (HttpURLConnection) new URL(sAddress + "/api/albums/" + url + "/image")
                        .openConnection();
                conn.setRequestProperty("Accept", "application/json");
                conn.setRequestProperty("Authorization", "Bearer " + token);
                //                conn.setInstanceFollowRedirects(true);
                conn.connect();
                Log.d(TAG, "Got response code " + conn.getResponseCode() + " for request on album ID " + url);
                InputStream in = conn.getInputStream();
                BufferedInputStream buf = new BufferedInputStream(in);
                Bitmap bMap = BitmapFactory.decodeStream(buf);
                if (bMap == null) {
                    Drawable drawable = ContextCompat.getDrawable(context, R.drawable.ic_noalbum);
                    bMap = Bitmap.createBitmap(960, 960, Bitmap.Config.ARGB_8888);
                    Canvas canvas = new Canvas(bMap);
                    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
                    drawable.draw(canvas);
                }
                in.close();
                buf.close();

                return bMap;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}