Java tutorial
/* * </summary> * Source File : ArtistDetailFragment.java * Project : Sarigama * Owner : Kasun * </summary> * * <license> * Copyright 2016 Kasun Gunathilaka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http:www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </license> */ package com.kasungunathilaka.sarigama.fragment; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.CollapsingToolbarLayout; import android.support.v4.app.Fragment; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.Toast; import com.kasungunathilaka.sarigama.R; import com.kasungunathilaka.sarigama.adapter.SongAdapter; import com.kasungunathilaka.sarigama.business.URLBusiness; import com.kasungunathilaka.sarigama.domain.Song; import com.kasungunathilaka.sarigama.domain.URLDomain; import com.kasungunathilaka.sarigama.ui.HomeActivity; import com.kasungunathilaka.sarigama.util.PlayerQueue; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.squareup.picasso.Picasso; import java.util.ArrayList; import cz.msebera.android.httpclient.Header; /** * A simple {@link Fragment} subclass. */ public class ArtistDetailFragment extends Fragment { public final static String ARTIST_NAME = "artist_name"; public final static String ARTIST_URL = "artist_url"; public final static String SONG_COUNT = "song_count"; public final static String IMG_URL = "image_url"; ArrayList<Song> songs; CollapsingToolbarLayout collapsingToolbar; RelativeLayout rlPb, rlRecyclerView; ImageView ivArtist; RecyclerView rv; Toolbar toolbar; String artistURL, artistName, imageURL, songCount; IFragmentCommunicator iFragmentCommunicator; HomeActivity activity; BroadcastReceiver broadcastReceiver; URLBusiness uRLBusiness; PlayerQueue playerQueue = PlayerQueue.getInstance(getActivity()); Song currentSong; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_artist_detail, container, false); activity = (HomeActivity) getActivity(); uRLBusiness = new URLBusiness(activity); toolbar = (Toolbar) view.findViewById(R.id.toolbar); activity.setSupportActionBar(toolbar); activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true); collapsingToolbar = (CollapsingToolbarLayout) view.findViewById(R.id.collapsing_toolbar); rlPb = (RelativeLayout) view.findViewById(R.id.rlPb); rlRecyclerView = (RelativeLayout) view.findViewById(R.id.rlRecyclerView); ivArtist = (ImageView) view.findViewById(R.id.ivArtist); rv = (RecyclerView) view.findViewById(R.id.rv); setHasOptionsMenu(true); return view; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.action_refresh) { try { uRLBusiness = new URLBusiness(activity); showProgressBar(true); AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); asyncHttpClient.post(getActivity(), artistURL, null, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { try { getData(new String(responseBody)); URLDomain uRLDomain = new URLDomain(); uRLDomain.setUrlAddress(artistURL); uRLDomain.setUrlContent(new String(responseBody)); uRLBusiness.Update(uRLDomain); uRLBusiness.Close(); showProgressBar(false); rv.setHasFixedSize(true); rv.setLayoutManager(new LinearLayoutManager(getActivity())); rv.setAdapter(new SongAdapter(getActivity(), songOnclick, songs)); } catch (Exception e) { e.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { showProgressBar(false); switch (statusCode) { case 404: Toast.makeText(getActivity(), "Server not Found", Toast.LENGTH_SHORT).show(); break; case 500: Toast.makeText(getActivity(), "Server Error", Toast.LENGTH_SHORT).show(); break; } } }); } catch (Exception e) { e.printStackTrace(); } } return super.onOptionsItemSelected(item); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Picasso.with(getActivity()).load(imageURL).into(ivArtist); if (songCount.contentEquals("")) collapsingToolbar.setTitle(artistName); else collapsingToolbar.setTitle(artistName + " (" + songCount + ")"); uRLBusiness = new URLBusiness(activity); try { showProgressBar(true); if (uRLBusiness.Exist(artistURL)) { getData(uRLBusiness.SelectSingle(artistURL).getUrlContent()); uRLBusiness.Close(); showProgressBar(false); rv.setHasFixedSize(true); rv.setLayoutManager(new LinearLayoutManager(getActivity())); rv.setAdapter(new SongAdapter(getActivity(), songOnclick, songs)); } else { AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); asyncHttpClient.post(getActivity(), artistURL, null, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { try { getData(new String(responseBody)); URLDomain uRLDomain = new URLDomain(); uRLDomain.setUrlAddress(artistURL); uRLDomain.setUrlContent(new String(responseBody)); uRLBusiness.Save(uRLDomain); uRLBusiness.Close(); showProgressBar(false); rv.setHasFixedSize(true); rv.setLayoutManager(new LinearLayoutManager(getActivity())); rv.setAdapter(new SongAdapter(getActivity(), songOnclick, songs)); } catch (Exception e) { e.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { showProgressBar(false); Bundle bundle = new Bundle(); bundle.putString(HomeActivity.FRAGMENT_NAME, "ConnectionFailFragment"); iFragmentCommunicator.fragmentData(bundle); switch (statusCode) { case 404: Toast.makeText(getActivity(), "Server not Found", Toast.LENGTH_SHORT).show(); break; case 500: Toast.makeText(getActivity(), "Server Error", Toast.LENGTH_SHORT).show(); break; } } }); } } catch (Exception e) { e.printStackTrace(); } iFragmentCommunicator = (IFragmentCommunicator) getActivity(); } public void setData(Bundle bundle) { artistURL = bundle.getString(ARTIST_URL); artistName = bundle.getString(ARTIST_NAME); imageURL = bundle.getString(IMG_URL); songCount = bundle.getString(SONG_COUNT) == null ? "" : bundle.getString(SONG_COUNT); } private void getData(String body) { if (songCount.contentEquals("")) { int startIndex = body.indexOf("artists-profile-detail-name"); startIndex = body.indexOf("<label>", startIndex + 1); startIndex = startIndex + 7; int endIndex = body.indexOf("</label>", startIndex + 1); songCount = body.substring(startIndex, endIndex).trim(); System.out.println(songCount); collapsingToolbar.setTitle(artistName + " (" + songCount + ")"); } songs = new ArrayList<>(); int startIndex = body.indexOf("http://sarigama.lk/profile/song_profile/"); while (startIndex >= 0) { Song song = new Song(); int endIndex = body.indexOf(">", startIndex + 1); endIndex = endIndex - 2; song.setSongItem(body.substring(startIndex, endIndex).trim()); System.out.println(body.substring(startIndex, endIndex).trim()); startIndex = body.indexOf("<label>", endIndex + 1); startIndex = body.indexOf("-", startIndex + 1); startIndex = startIndex + 2; endIndex = body.indexOf("</label>", startIndex + 1); song.setSongTitle(body.substring(startIndex, endIndex).trim()); System.out.println(body.substring(startIndex, endIndex).trim()); song.setSongArtist(artistName); System.out.println(artistName); songs.add(song); startIndex = body.indexOf("http://sarigama.lk/profile/song_profile/", startIndex + 1); } } private void showProgressBar(Boolean show) { rlPb.setVisibility(show ? View.VISIBLE : View.GONE); rlRecyclerView.setVisibility(show ? View.GONE : View.VISIBLE); } SongAdapter.OnItemClickListener songOnclick = new SongAdapter.OnItemClickListener() { @Override public void onItemClick(final Song song, final int position) { try { playerQueue.clearQueue(); activity.getPlayerService().stopPlayerQueue(); playerQueue.addSongs(songs); playerQueue.setCurrentPosition(position); Bundle bundle = new Bundle(); bundle.putString(HomeActivity.FRAGMENT_NAME, "PlayerFragment"); bundle.putString(HomeActivity.PLAYER_FRAGMENT_LAUNCH_MODE, HomeActivity.PLAYER_FRAGMENT_LAUNCH_MODE_NEW_QUEUE); iFragmentCommunicator.fragmentData(bundle); } catch (Exception e) { e.printStackTrace(); } } }; @Override public void onDestroy() { super.onDestroy(); LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(broadcastReceiver); showProgressBar(false); } @Override public void onResume() { super.onResume(); broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Bundle bundle; switch (intent.getAction()) { case HomeActivity.ON_ADDED_TO_QUEUE: if (!activity.getPlayerService().isPlaying()) { bundle = new Bundle(); bundle.putBoolean(PlayerFragment.PREVIOUS_AUDIO, false); bundle.putString(HomeActivity.FRAGMENT_NAME, "PlayerFragment"); iFragmentCommunicator.fragmentData(bundle); } break; case HomeActivity.ON_SAME_ADDED_TO_QUEUE: bundle = new Bundle(); bundle.putBoolean(PlayerFragment.PREVIOUS_AUDIO, true); bundle.putString(HomeActivity.FRAGMENT_NAME, "PlayerFragment"); iFragmentCommunicator.fragmentData(bundle); break; case HomeActivity.ON_CURRENT_POSITION_CHANGED: bundle = new Bundle(); bundle.putBoolean(PlayerFragment.PREVIOUS_AUDIO, false); bundle.putString(HomeActivity.FRAGMENT_NAME, "PlayerFragment"); iFragmentCommunicator.fragmentData(bundle); break; } } }; LocalBroadcastManager.getInstance(getActivity()).registerReceiver((broadcastReceiver), new IntentFilter(HomeActivity.ON_ADDED_TO_QUEUE)); LocalBroadcastManager.getInstance(getActivity()).registerReceiver((broadcastReceiver), new IntentFilter(HomeActivity.ON_SAME_ADDED_TO_QUEUE)); LocalBroadcastManager.getInstance(getActivity()).registerReceiver((broadcastReceiver), new IntentFilter(HomeActivity.ON_CURRENT_POSITION_CHANGED)); } }