Android development Local and network MP3 Music Player (12) Create Netmusiclistadapter, SearchResult display network music list

Source: Internet
Author: User
Tags call back event listener


Implementation features:
Implement Netmusiclistadapter (Network music list adapter)
Implementing SearchResult (Searching for music objects)
Use the Jsoup component to request the network and parse the music data, and the music data is loaded into the list
Implement Footerview

Until the current source download:
http://download.csdn.net/detail/iwanghang/9507635

Jsoup Component Import:
Androidstudio Simple and fast import of third-party components in GitHub:
http://blog.csdn.net/iwanghang/article/details/51283763

Jsoup Introduction and Chinese API:
http://blog.csdn.net/iwanghang/article/details/51282403
http://blog.csdn.net/iwanghang/article/details/51283638
http://blog.csdn.net/iwanghang/article/details/51283659

Welcome to Mobile development enthusiasts Exchange: mine is Iwanghang

In addition, I intend to start looking for a job, if Shenyang or the surrounding city company is interested, please contact me.


Achieve results













Footerview:






The implementation code is as follows:
Netmusiclistfragment as follows:
package com.iwanghang.drmplayer;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


import com.iwanghang.drmplayer.adapter.MyMusicListAdapter;
import com.iwanghang.drmplayer.adapter.NetMusicListAdapter;
import com.iwanghang.drmplayer.utils.AppUtils;
import com.iwanghang.drmplayer.utils.Constant;
import com.iwanghang.drmplayer.utils.SearchMusicUtils;
import com.iwanghang.drmplayer.vo.Mp3Info;
import com.iwanghang.drmplayer.vo.SearchResult;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;

public class NetMusicListFragment extends Fragment implements OnItemClickListener, OnClickListener {

    private ListView listView_net_music;

    // private ArrayList <Mp3Info> mp3Infos;

    private LinearLayout load_layout;
    private LinearLayout ll_search_btn_container;
    private LinearLayout ll_search_container;
    private ImageButton ib_search_btn;
    private EditText et_search_content;

    private NetMusicListAdapter netMusicListAdapter;

    // Store collection of network music
    private ArrayList <SearchResult> searchResults = new ArrayList <SearchResult> ();

    private int page = 1; // Search music page number

    private MainActivity mainActivity;

    // private boolean isPause = false; // Pause status during song playback

    private int position = 0; // The current playing position, provided to PlayActivity

    // onAttach (), called when the fragment is bound to the activity (Activity will be passed in.)
    @Override
    public void onAttach (Context context) {
        super.onAttach (context);
        // mainActivity = (MainActivity) context;
        mainActivity = (MainActivity) getActivity ();
    }

    public static NetMusicListFragment newInstance () {
        NetMusicListFragment net = new NetMusicListFragment ();
        return net;
    }

    @Nullable
    @Override
    public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // UI component initialization
        View view = inflater.inflate (R.layout.net_music_list_layout, null);
        // item
        listView_net_music = (ListView) view.findViewById (R.id.listView_net_music);
        // findViewById
        load_layout = (LinearLayout) view.findViewById (R.id.load_layout);
        ll_search_btn_container = (LinearLayout) view.findViewById (R.id.ll_search_btn_container);
        ll_search_container = (LinearLayout) view.findViewById (R.id.ll_search_container);
        ib_search_btn = (ImageButton) view.findViewById (R.id.ib_search_btn);
        et_search_content = (EditText) view.findViewById (R.id.et_search_content);

        // Item click event listener
        listView_net_music.setOnItemClickListener (this);
        // Button click event listener
        ll_search_btn_container.setOnClickListener (this);
        ib_search_btn.setOnClickListener (this);
        loadNetData (); // Load network music
        return view;
    }

    private void loadNetData () {
        load_layout.setVisibility (View.VISIBLE);
        // Asynchronous task to load network music
        new LoadNetDataTask (). execute (Constant.BAIDU_URL + Constant.BAIDU_DAYHOT);
    }

    @Override
    public void onClick (View v) {
        switch (v.getId ()) {
            case R.id.ll_search_btn_container:
                ll_search_btn_container.setVisibility (View.GONE);
                ll_search_container.setVisibility (View.VISIBLE);
                break;
            case R.id.ib_search_btn:
                // Search for events
                searchMusic ();
                break;
        }
    }

    // Search for music
    private void searchMusic () {
        // Hide the keyboard
        AppUtils.hideInputMethod (et_search_content);
        ll_search_btn_container.setVisibility (View.VISIBLE);
        ll_search_container.setVisibility (View.GONE);
        // Get the entered text
        String key = et_search_content.getText (). ToString ();
        if (TextUtils.isEmpty (key))
            Toast.makeText (mainActivity, "Please enter a singer or lyrics", Toast.LENGTH_SHORT) .show ();
            return;
        }
        load_layout.setVisibility (View.VISIBLE); // Load the layout effect. Show
        // Fill in the item Use SearchMusicUtils to search for music tool classes, and, using the observer design pattern, call back yourself and listen on your own
        // SearchMusicUtils.
    }

    // Asynchronous task to load network music
    // Android 1.5 provides the tool class android.os.AsyncTask, which makes it easier to create asynchronous tasks. It is no longer necessary to write a task thread and a Handler instance to complete the same task.
    class LoadNetDataTask extends AsyncTask <String, Integer, Integer> {
        // onPreExecute method is used to do some UI operations before executing background tasks
        @Override
        protected void onPreExecute () {
            super.onPreExecute ();
            lo
ad_layout.setVisibility (View.VISIBLE); // Load layout. display
            listView_net_music.setVisibility (View.GONE); / item.Hide
            searchResults.clear (); // Search results. Clear
        }

        // doInBackground method performs background tasks internally, UI cannot be modified within this method
        @Override
        protected Integer doInBackground (String ... params) {
            String url = params [0];
            try {
                // Use Jsoup component to request network and parse music data
                Document doc = Jsoup.connect (url) .userAgent (Constant.USER_AGENT) .timeout (6 * 1000) .get ();
// </ span> </ span> <span class = "song-title" style = 'width: 240px;'> <a href = "/ song / 121353608" target = "_ blank" title = "刘 珂 矣 半Pot yarn "data-film =" null "> half pot yarn </a> </ span> <span class =" singer "style =" width: 240px; "> <span class =" author_list "title =" 刘 珂矣 ">
// <a hidefocus="true" href="/artist/132632388"> 刘 珂 矣 </a> </ span>
// </ span> </ span> <span class = "song-title" style = 'width: 240px;'> <a href = "/ song / 264506450" target = "_ blank" title = "Han Lei Millennium General If "data-film =" null "> Millennium General If </a> <div class =" extra-info "> <span class =" appendix "> Movie Soundtrack </ span> </ div> </ span> < span class = "singer" style = "width: 240px;"> <span class = "author_list" title = "韩磊">
// <a hidefocus="true" href="/artist/1302"> HAN Lei </a> </ span>
                // Analyze the above html code from the doc; find out the song-title under all span tags, and save it in the songTitles collection; that is, the song title collection;
                // Analyze the above html code from the doc; find out the author_list under all span tags and store it in the artists collection; that is, the singer collection;
                Elements songTitles = doc.select ("span.song-title");
                Elements artists = doc.select ("span.author_list");
                //System.out.println(artists);
                for (int i = 0; i <songTitles.size (); i ++) {
                    SearchResult searchResult = new SearchResult ();
                    //System.out.println("@searchResult: "+ searchResult);

                    // <a href = "/ song / 121353608"
                    // <a href = "/ song / 264506450"
                    // a link, stored in the urls collection; that is, the song url collection;
                    // a link, the first a link, the value of the href attribute; that is, the final url;
                    // a link, the first a link, text (the content of a link, for example:> half pot yarn <, half pot yarn is the content of a link); that is, the final song name;
                    Elements urls = songTitles.get (i) .getElementsByTag ("a");
                    //System.out.println("@urls: "+ urls);
                    searchResult.setUrl (urls.get (0) .attr ("href")); // Set the final URL
                    searchResult.setMusicName (urls.get (0) .text ()); // Set the final song name

                    // a link, stored in the urls collection; that is, the song url collection;
                    Elements artistElements = artists.get (i) .getElementsByTag ("a");
                    //System.out.println("@artistElements: "+ artistElements);
                    searchResult.setArtist (artistElements.get (0) .text ()); // Set the final artist

                    searchResult.setAlbum ("Hot Song List"); // Set the final album

                    System.out.println ("@ searchResult:" + searchResult);
                    searchResults.add (searchResult); // Add all the final information to the collection
                }
                System.out.println ("@ searchResults:" + searchResults);
                //System.out.println ("@ songTitles.size ():" + searchResults.size ());
            } catch (IOException e) {
                e.printStackTrace ();
                return -1;
            }
            return 1;
        }

        // onPostExecute method is used to update the UI after executing the background task and display the result
        @Override
        protected void onPostExecute (Integer result) {
            super.onPostExecute (result);
            if (result == 1) {
                netMusicListAdapter = new NetMusicListAdapter (mainActivity, searchResults);
                //System.out.println(searchResults);
                listView_net_music.setAdapter (netMusicListAdapter);
                listView_net_music.addFooterView (LayoutInflater.from (mainActivity) .inflate (R.layout.footviwe_layout, null));
            }
            load_layout.setVisibility (View.GONE);
            listView_net_music.setVisibility (View.VISIBLE);
        }
    }




    @Override
    public void onItemClick (AdapterView <?> parent, View view, int position, long id) {

    }
}

Netmusiclistadapter as follows:
package com.iwanghang.drmplayer.adapter;

import android.content.Context;
import android.graphics.Bitmap;
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.iwanghang.drmplayer.R;
import com.iwanghang.drmplayer.utils.MediaUtils;
import com.iwanghang.drmplayer.vo.Mp3Info;
import com.iwanghang.drmplayer.vo.SearchResult;

import java.util.ArrayList;

/ **
 * Custom music list adapter (network)
 * For easy expansion, because the album art was not considered before
 * Created by iwanghang on 30/4/16.
 * /
public class NetMusicListAdapter extends BaseAdapter {

    private Context ctx; // Context object reference
    private ArrayList <SearchResult> searchResults; // Store the collection referenced by SearchResult
    private SearchResult searchResult; // SearchResult object reference
    // private int pos = -1; // list position

    / **
     * Constructor
     * @param ctx context
     * @param searchResults collection object
     * /
    public NetMusicListAdapter (Context ctx, ArrayList <SearchResult> searchResults) {
        this.ctx = ctx;
        this.searchResults = searchResults;
        //System.out.println("MyMusicListAdapter.java # 0: ctx = "+ ctx +", mp3Infos = "+ mp3Infos.size ());
    }

    public ArrayList <SearchResult> searchResults () {
        System.out.println ("NetMusicListAdapter.java # 1: public ArrayList <SearchResult> searchResults () {");
        return searchResults;
    }

    public void setSearchResults (ArrayList <SearchResult> searchResults) {
        System.out.println ("NetMusicListAdapter.java # 2: public void setMp3Infos (ArrayList <SearchResult> searchResults) {");
        this.searchResults = searchResults;
    }


    @Override
    public int getCount () {
        //System.out.println("NetMusicListAdapter.java # 3: public int getCount () {"+ mp3Infos.size ());
        // return mp3Infos.size ();
        return searchResults.size ();
    }

    @Override
    public Object getItem (int position) {
        System.out.println ("NetMusicListAdapter.java # 4: public Object getItem (int position) {");
        return searchResults.get (position);
    }

    @Override
    public long getItemId (int position) {
        //System.out.println("NetMusicListAdapter.java # 5: public long getItemId (int position) {");
        return position;
    }

    @Override
    public View getView (int position, View convertView, ViewGroup parent) {
        //System.out.println("NetMusicListAdapter.java # 6: public View getView ");
        ViewHolder vh;
        if (convertView == null) {
            // vh = new ViewHolder ();
            convertView = LayoutInflater.from (ctx) .inflate (R.layout.item_net_music_list, null);
            vh = new ViewHolder ();
            vh.textView1_title = (TextView) convertView.findViewById (R.id.textView1_title);
            vh.textView2_singer = (TextView) convertView.findViewById (R.id.textView2_singer);
            //vh.textView3_time = (TextView) convertView.findViewById (R.id.textView3_time);
            //vh.imageView1_ablum = (ImageView) convertView.findViewById (R.id.imageView1_ablum);

            //System.out.println("NetMusicListAdapter.java # 7: textView1_title = "+ vh.textView1_title);
            convertView.setTag (vh); // Indicates that you add extra data to the View,
        } else {
            vh = (ViewHolder) convertView.getTag (); // Get the data out by the getTag method
        }

        SearchResult searchResult = searchResults.get (position);
        vh.textView1_title.setText (searchResult.getMusicName ()); // Show title
        vh.textView2_singer.setText (searchResult.getArtist ()); // Show artist
        //vh.textView3_time.setText(MediaUtils.formatTime(mp3Info.getDuration()));//Display duration

        // Get album cover image
        // Bitmap albumBitmapItem = MediaUtils.getArtwork (ctx, mp3Info.getId (), mp3Info.getAlbumId (), true, true);
        //System.out.println("NetMusicListAdapter.java # 8: albumBitmapItem = "+ albumBitmapItem.getConfig ());

        // Change album cover image in playback interface
        //vh.imageView1_ablum.setImageBitmap(albumBitmapItem);
        //vh.imageView1_ablum.setImageResource(R.mipmap.music);

        return convertView;
    }

    / **
     * Define an inner class
     * Declare corresponding control references
     * /
    static class ViewHolder {
        // All control object references
        TextView textView1_title; // Title
        TextView textView2_singer; // Singer
        // TextView textView3_time; // Duration
        // ImageView imageView1_ablum; // Album cover image
    }
}

SearchResult as follows:
package com.iwanghang.drmplayer.vo;

/ **
 * Created by iwanghang on 16/4/29.
 * Search for music
 * /
public class SearchResult {
    private String musicName;
    private String url;
    private String artist;
    private String album;
    private long size; // size


    // set method, get method
    public String getMusicName () {
        return musicName;
    }

    public void setMusicName (String musicName) {
        this.musicName = musicName;
    }

    public String getUrl () {
        return url;
    }

    public void setUrl (String url) {
        this.url = url;
    }

    public String getArtist () {
        return artist;
    }

    public void setArtist (String artist) {
        this.artist = artist;
    }

    public String getAlbum () {
        return album;
    }

    public void setAlbum (String album) {
        this.album = album;
    }

    public long getSize () {
        return size;
    }

    public void setSize (long size) {
        this.size = size;
    }

    @Override
    public String toString () {
        return "SearchResult {" +
                "musicName = '" + musicName +' \ '' +
                ", url = '" + url +' \ '' +
                ", artist = '" + artist +' \ '' +
                ", album = '" + album +' \ '' +
                ", size =" + size +
                '}';
    }
}


Footview_layout.xml as follows:





<? xml version = "1.0" encoding = "utf-8"?>
<TextView android: id = "@ + id / textView4"
     xmlns: android = "http://schemas.android.com/apk/res/android"
     android: layout_width = "match_parent"
     android: layout_height = "wrap_content"
     android: orientation = "vertical"
     android: padding = "10dp"
     android: gravity = "center"
     android: textSize = "10sp"
     android: textColor = "# a6a8a8"
     android: text = "It's the end">
</ TextView> 






Android development Local and network MP3 Music Player (12) Create Netmusiclistadapter, SearchResult display network music list


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.