Java tutorial
package com.esprit.lyricsplus.DAO; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.AsyncTask; import android.text.Html; import android.util.Log; import android.view.View; import android.widget.TextView; import com.android.volley.DefaultRetryPolicy; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.TimeoutError; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.esprit.lyricsplus.DetailsArtistActivity; import com.esprit.lyricsplus.HomeActivity; import com.esprit.lyricsplus.MyApplication; import com.esprit.lyricsplus.PlayerConfig; import com.esprit.lyricsplus.RVClass.Lyrics; import com.esprit.lyricsplus.SearchActivity; import com.esprit.lyricsplus.TrackActivity; import com.esprit.lyricsplus.adapter.SearchTrackRVAdapter; import com.esprit.lyricsplus.adapter.TrackRVAdapter; import com.esprit.lyricsplus.entities.Album; import com.esprit.lyricsplus.entities.Artist; import com.esprit.lyricsplus.entities.Song; import com.esprit.lyricsplus.fragments.ArtistSearchFragment; import com.esprit.lyricsplus.fragments.ListSongFragment; import com.esprit.lyricsplus.fragments.SongSearchFragment; import com.esprit.lyricsplus.R; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.regex.Matcher; import java.util.regex.Pattern; import cn.pedant.SweetAlert.SweetAlertDialog; /** * Created by Aziz on 11/22/2016. */ public class SongDAO { String url; RequestQueue queue; String link; String lyrics; JSONArray array; InputStream is; String json; //StringRequest postStringRequest; StringRequest postRequest; //StringRequest request; private static Pattern patternDomainName; private Matcher matcher; private static final String DOMAIN_NAME_PATTERN = "([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}"; static { patternDomainName = Pattern.compile(DOMAIN_NAME_PATTERN); } public final String ARTIST_KEY = "artist"; public final String SONG_KEY = "song"; public void getSongsByArtist(List<Song> cards, String jsonResponse) { try { JSONObject JObject = new JSONObject(jsonResponse); JSONObject body = JObject.getJSONObject("message").getJSONObject("body"); JSONArray array = body.getJSONArray("track_list"); for (int i = 0; i < array.length(); i++) { JSONObject j = array.getJSONObject(i).getJSONObject("track"); Song song = new Song(j); cards.add(song); } JSONObject e = array.getJSONObject(array.length() - 1).getJSONObject("track"); ((TextView) ListSongFragment.activity.findViewById(R.id.artist_name)) .setText(e.getString("artist_name")); } catch (JSONException e) { e.printStackTrace(); } } public String replace(String str) { return str.replaceAll(" ", "%20"); } // OLD public void getSuggestedTracks(List<Song> songs, String jsonResponse) { try { JSONObject JObject = new JSONObject(jsonResponse); JSONObject body = JObject.getJSONObject("message").getJSONObject("body"); JSONArray array = body.getJSONArray("track_list"); for (int i = 0; i < array.length(); i++) { JSONObject j = array.getJSONObject(i).getJSONObject("track"); if (j.optString("track_name").length() > 0 && j.optString("track_mbid").length() > 0 && j.optString("artist_name").length() > 0 && j.optString("album_name").length() > 0 && j.optString("artist_mbid").length() > 0) { Song song = new Song(j, "apiSong"); if (!song.getTitle().toLowerCase().contains("remix")) { songs.add(song); } } else { ArtistDAO artistDAO = new ArtistDAO(); String mbid = artistDAO.artistGetMbid(j.optString("artist_id")); if (mbid.length() > 0) { Song song = new Song(j, "apiSong"); if (!song.getTitle().toLowerCase().contains("remix")) { songs.add(song); } } } } } catch (JSONException e) { e.printStackTrace(); } } public void getSuggestedTrackswithLyrics(List<Lyrics> lyricss, String jsonResponse) { try { JSONObject JObject = new JSONObject(jsonResponse); JSONObject body = JObject.getJSONObject("message").getJSONObject("body"); JSONArray array = body.getJSONArray("track_list"); for (int i = 0; i < array.length(); i++) { JSONObject j = array.getJSONObject(i).getJSONObject("track"); Lyrics lyrics = new Lyrics(j); lyricss.add(lyrics); } } catch (JSONException e) { e.printStackTrace(); } } public void addLike(final int id_song, final int id_user, final int like) { link = ((MyApplication) HomeActivity.mAppContext).getLink(); url = link + "addLike.php"; postRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { if (response.equals("1")) { /* Toast.makeText(HomeActivity.mAppContext, "Successfully Added !", Toast.LENGTH_SHORT).show(); */ } else { /* Toast.makeText(HomeActivity.mAppContext, "ERROR !!!!!", Toast.LENGTH_SHORT).show(); */ } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // error Log.d("Error.Response", error.toString()); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); params.put("id_song", String.valueOf(id_song)); params.put("id_user", String.valueOf(id_user)); params.put("like", String.valueOf(like)); return params; } }; queue = Volley.newRequestQueue(HomeActivity.mAppContext); queue.add(postRequest); } public void deleteLike(final int id_song, final int id_user, final int like) { link = ((MyApplication) HomeActivity.mAppContext).getLink(); url = link + "deleteLike.php"; postRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { if (response.equals("1")) { /* Toast.makeText(HomeActivity.mAppContext, "Successfully Deleted !", Toast.LENGTH_SHORT).show(); */ } else { /* Toast.makeText(HomeActivity.mAppContext, "ERROR !!!!!", Toast.LENGTH_SHORT).show(); */ } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // error Log.d("Error.Response", error.toString()); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); params.put("id_song", String.valueOf(id_song)); params.put("id_user", String.valueOf(id_user)); params.put("like", String.valueOf(like)); return params; } }; queue = Volley.newRequestQueue(HomeActivity.mAppContext); queue.add(postRequest); } public void addLikeRecord(final int id_record, final int id_user, final int like) { link = ((MyApplication) HomeActivity.mAppContext).getLink(); url = link + "addLikeRecord.php"; postRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { if (response.equals("1")) { /* Toast.makeText(HomeActivity.mAppContext, "Successfully Added !", Toast.LENGTH_SHORT).show(); */ } else { /* Toast.makeText(HomeActivity.mAppContext, "ERROR !!!!!", Toast.LENGTH_SHORT).show(); */ } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // error Log.d("Error.Response", error.toString()); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); params.put("id_record", String.valueOf(id_record)); params.put("id_user", String.valueOf(id_user)); params.put("like", String.valueOf(like)); return params; } }; queue = Volley.newRequestQueue(HomeActivity.mAppContext); queue.add(postRequest); } public void deleteLikeRecord(final int id_record, final int id_user, final int like) { link = ((MyApplication) HomeActivity.mAppContext).getLink(); url = link + "deleteLikeRecord.php"; postRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { if (response.equals("1")) { /* Toast.makeText(HomeActivity.mAppContext, "Successfully Deleted !", Toast.LENGTH_SHORT).show(); */ } else { /* Toast.makeText(HomeActivity.mAppContext, "ERROR !!!!!", Toast.LENGTH_SHORT).show(); */ } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // error Log.d("Error.Response", error.toString()); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); params.put("id_record", String.valueOf(id_record)); params.put("id_user", String.valueOf(id_user)); params.put("like", String.valueOf(like)); return params; } }; queue = Volley.newRequestQueue(HomeActivity.mAppContext); queue.add(postRequest); } public void getAlbumSongs(final Album album, final Artist artist, final List<Song> songs, final TrackRVAdapter adapter) { songs.clear(); // MODIFIY String url = "http://api.musixmatch.com/ws/1.1/album.tracks.get?" + "album_mbid=" + album.getAlbum_mbid() + "&page=1&apikey=73ddf8ff707c806059b04faa88e4d483"; Volley.newRequestQueue(ArtistSearchFragment.activity.getApplicationContext()) .add(new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { if (response != null) { getTracks(songs, response, album, artist, "api"); adapter.notifyDataSetChanged(); for (int i = 0; i < songs.size(); i++) { addSong(songs.get(i), artist); } } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { System.out.println("error setting note : " + error.getMessage()); if (error instanceof TimeoutError) { System.out.println(error.toString()); } } })); } public void getTracks(List<Song> songs, String jsonResponse, final Album album, final Artist artist, final String api) { try { if (api.equals("api")) { array = new JSONObject(jsonResponse).getJSONObject("message").getJSONObject("body") .getJSONArray("track_list"); for (int i = 0; i < array.length(); i++) { Song song = new Song(array.getJSONObject(i).getJSONObject("track"), "api"); if (!song.getTitle().toLowerCase().contains("remix")) { song.setAlbum(album); song.setSinger(artist); System.out.println("Track added : " + song); songs.add(song); } } } else { array = new JSONArray(jsonResponse); for (int i = 0; i < array.length(); i++) { Song song = new Song(array.getJSONObject(i), "db"); songs.add(song); } } } catch (JSONException e) { e.printStackTrace(); } } public void getAlbumSongsDB(final Artist artist, final Album album, final List<Song> songs, final TrackRVAdapter adapter) { songs.clear(); link = ((MyApplication) DetailsArtistActivity.app.getApplicationContext()).getLink(); url = link + "getTracks.php"; postRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { // response if (response != null) { getTracks(songs, response, album, artist, "db"); adapter.notifyDataSetChanged(); if (adapter.getItemCount() == 0) { getAlbumSongs(album, artist, songs, adapter); Log.e("Source", "GETTING Tracks FROM API"); } else { Log.e("Source", "GETTING Tracks FROM DB"); } } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // error Log.d("Error.Response", error.toString()); /* pDialog.dismissWithAnimation(); */ } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); params.put("id", String.valueOf(album.getId())); return params; } }; queue = Volley.newRequestQueue(DetailsArtistActivity.app.getApplicationContext()); queue.add(postRequest); } public void getLyricsAPIAZlyrics(final TextView et, Song song) { Log.e("Lyrics From", "AzLyrics"); try { String artistName = URLEncoder.encode( song.getSinger().getName().toLowerCase().replace("'", "").replace(".", "").replace(" ", ""), "UTF-8"); String trackName = URLEncoder.encode( song.getTitle().toLowerCase().replace(" ", "").replace("'", "").replace(".", ""), "UTF-8"); url = "http://www.azlyrics.com/lyrics/" + artistName + "/" + trackName + ".html"; new JsoupLyricsAPI(et, url, song, "az").execute(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } public void getLyricsAPIGenius(final TextView et, Song song) { Log.e("Lyrics From", "Genius"); String artistName = null; String trackName = null; try { artistName = URLEncoder.encode( song.getSinger().getName().toLowerCase().replace("'", "").replace(".", "").replace(" ", ""), "UTF-8"); trackName = URLEncoder.encode( song.getTitle().toLowerCase().replace(" ", "+").replace("'", "").replace(".", ""), "UTF-8"); url = "http://genius.com/" + artistName + "-" + trackName + "-lyrics"; new JsoupLyricsAPI(et, url, song, "ge").execute(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } public void getLyrics(final TextView et, Song song) { Log.e("Lyrics From", "AZ"); String trackName = null; String artistName = null; artistName = song.getSinger().getName().toLowerCase(); trackName = song.getTitle().toLowerCase(); url = artistName + " " + trackName + " az lyrics"; Log.e("KHRA ->", url); Log.e("fucking URL ", url); new JsoupLyricsAPIv2(et, url, song, "az").execute(); } public void getLyricsAPIArab(final TextView et, Song song) { Log.e("Lyrics From", "ArabMusic"); String artistName = null; String trackName = null; try { artistName = URLEncoder.encode(song.getSinger().getName().toLowerCase(), "UTF-8"); trackName = URLEncoder.encode(song.getTitle().toLowerCase(), "UTF-8"); url = "http://www.arabicmusictranslation.com/search?q=" + URLEncoder.encode(artistName + "+" + trackName, "UTF-8"); new JsoupLyricsAPI(et, url, song, "ar").execute(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } private class JsoupLyricsAPI extends AsyncTask<Void, Void, Void> { public TextView et; String title; Element row; Document doc; String url; Song song; String api; public JsoupLyricsAPI(TextView et, String url, Song song, String api) { this.et = et; this.url = url; this.song = song; this.api = api; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(Void... params) { try { if (api.equals("az")) { doc = Jsoup.connect(url).userAgent("Mozilla").get(); row = doc.select("div:not([class])").get(1); title = row.text(); //} else if (api.equals("ge")) { doc = Jsoup.connect(url).userAgent("Mozilla").get(); row = doc.getElementsByClass("lyrics").first(); title = row.text(); } else { Log.e("URL ARAB : ", url); doc = Jsoup.connect(url).userAgent("Mozilla").get(); //row = doc.getElementsByClass("date-posts").first().select("span").first(); if (doc.getElementsByClass("date-posts").size() > 0 && doc.getElementsByClass("date-posts").first().select("span[style]").size() > 1) { row = doc.getElementsByClass("date-posts").first().select("span[style]").get(1); title = row.text(); } } Log.e("html text", "working"); } catch (IOException e) { Log.e("html text", e.toString()); e.printStackTrace(); } catch (NegativeArraySizeException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { if (api.equals("az")) { if (row != null) { et.setText(Html.fromHtml(title)); song.setLyrics(title); } else { getLyricsAPIGenius(et, song); } } else if (api.equals("ge")) { if (row != null) { et.setText(Html.fromHtml(title)); song.setLyrics(title); } else { getLyricsAPIArab(et, song); } } else { if (row != null) { et.setText(Html.fromHtml(title)); song.setLyrics(title); } else { et.setText("Lyrics not found"); } } } } public void addSong(final Song song, final Artist artist) { final Context context = DetailsArtistActivity.app.getApplicationContext(); link = ((MyApplication) context).getLink(); url = link + "insertTrack.php"; postRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { // response Log.e("IDIDID: ", response.toString()); if (response.startsWith("1111") && response.length() > 4) { response = response.substring(4, response.length()); song.setId(Integer.valueOf(response)); //Toast.makeText(context, "ID SONG SET: " + response.toString(), Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // error // error Log.d("Error.Response", error.toString()); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); params.put("name", (song.getTitle() != null) ? song.getTitle().replace("'", "\\'") : ""); params.put("mbid", (song.getMbid() != null) ? song.getMbid() : ""); params.put("length", (song.getLength() != null) ? song.getLength() : ""); params.put("idalbum", (song.getAlbum().getId() != 0) ? String.valueOf(song.getAlbum().getId()) : ""); params.put("idsinger", (artist.getId() != 0) ? String.valueOf(artist.getId()) : ""); return params; } }; queue = Volley.newRequestQueue(context); queue.add(postRequest); } public void addLyrics(final Song song) { link = ((MyApplication) TrackActivity.app.getApplicationContext()).getLink(); url = link + "insertLyrics.php"; postRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { // response Log.e("Database Lyrics : " + response, song.toString()); /* Toast.makeText(TrackActivity.app.getApplicationContext(), "Lyrics Added to DB", Toast.LENGTH_SHORT).show(); */ } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // error Log.d("Error.Response", error.toString()); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); params.put("mbid", (song.getMbid() != null) ? song.getMbid() : ""); params.put("lyrics", (song.getLyrics() != null) ? song.getLyrics().replace("'", "\\'") : ""); return params; } }; queue = Volley.newRequestQueue(TrackActivity.app.getApplicationContext()); queue.add(postRequest); } public void addCodeYt(final Song song) { link = ((MyApplication) TrackActivity.app.getApplicationContext()).getLink(); url = link + "insertCodeYt.php"; postRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { /* Toast.makeText(TrackActivity.app.getApplicationContext(), "CODE YT : response : "+response, Toast.LENGTH_SHORT).show(); */ } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // error Log.d("Error.Response", error.toString()); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); params.put("mbid", (song.getMbid() != null) ? song.getMbid() : ""); params.put("codeyt", (song.getCodeYt() != null) ? song.getCodeYt().replace("'", "\\'") : ""); return params; } }; queue = Volley.newRequestQueue(TrackActivity.app.getApplicationContext()); queue.add(postRequest); } public String getYTCode(String s, Song song) { String f = "nope"; try { f = new YTEmbededCode(song).execute(s).get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return f; } public class YTEmbededCode extends AsyncTask<String, Integer, String> { String s = "hi"; String codeYt = ""; String s2 = "hi2"; Boolean availability = false; Song song; public YTEmbededCode(Song s) { this.song = s; } @Override protected String doInBackground(String... params) { String url, url2; try { /* url = "https://www.googleapis.com/youtube/v3/search?part=id&order=viewCount&q="+URLEncoder.encode(params[0],"UTF-8")+"&safeSearch" + "=moderate&type=video&videoEmbeddable=true&videoSyndicated=true&key="+ PlayerConfig.API_KEY;*/ url = "https://www.googleapis.com/youtube/v3/search?part=id&q=" + URLEncoder.encode(params[0], "UTF-8") + "&safeSearch" + "=moderate&maxResults=5&type=video&key=" + PlayerConfig.API_KEY; s = getJSONFromUrl(url); JSONArray jsonArray = new JSONObject(s).getJSONArray("items"); for (int i = 0; i < jsonArray.length(); i++) { Log.e("ena", "hne " + i); codeYt = new JSONObject(s).getJSONArray("items").getJSONObject(i).getJSONObject("id") .optString("videoId"); url2 = "https://www.googleapis.com/youtube/v3/videos?id=" + codeYt + "&part=contentDetails&key=AIzaSyByp4usFJQ0srWjFv0P3QXv7WJpp1eKWQ4"; s2 = getJSONFromUrl(url2); availability = new JSONObject(s2).getJSONArray("items").getJSONObject(0) .getJSONObject("contentDetails").optBoolean("licensedContent"); if (availability) { break; } else { continue; } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return codeYt; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); song.setCodeYt(result); //addCodeYt(song); } } public void getSearchTracks(String track, final List<Song> songs, final SearchTrackRVAdapter adapter) { songs.clear(); String url = replace("http://api.musixmatch.com/ws/1.1/track.search?q_track=" + track + "&s_track_rating=DESC&apikey=73ddf8ff707c806059b04faa88e4d483" + "&format=json&page_size=15"); final SweetAlertDialog pDialog = new SweetAlertDialog(SongSearchFragment.activity, SweetAlertDialog.PROGRESS_TYPE); pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86")); pDialog.setTitleText("Loading"); pDialog.setCancelable(false); pDialog.show(); Volley.newRequestQueue(SongSearchFragment.app.getApplicationContext()) .add(new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { if (response != null) { getSuggestedTracks(songs, response); adapter.notifyDataSetChanged(); if (adapter.getItemCount() == 0) { SongSearchFragment.rv.setVisibility(View.INVISIBLE); SongSearchFragment.nfound.setVisibility(View.VISIBLE); } } pDialog.dismiss(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { System.out.println("error setting note : " + error.getMessage()); if (error instanceof TimeoutError) { System.out.println(error.toString()); } pDialog.dismiss(); } })); } /* public Boolean videoAvailable(String videoId) { Boolean a = false; try { a = new availability() .execute(videoId) .get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return a; } public class availability extends AsyncTask<String, Void, Boolean> { String s = ""; String s2 = ""; Boolean exi = false; @Override protected Boolean doInBackground(String... params) { url = "https://www.googleapis.com/youtube/v3/videos?id=" + params[0] + "&part=status&key=" + PlayerConfig.API_KEY; String urldeux = "https://www.googleapis.com/youtube/v3/search?part=id&order=viewCount&q=adele+hello&safeSearch=moderate&type=video" + "&videoEmbeddable=true&key=AIzaSyByp4usFJQ0srWjFv0P3QXv7WJpp1eKWQ4"; //https://www.googleapis.com/youtube/v3/videos?id=FLYH6rn3adw&part=status&key=AIzaSyByp4usFJQ0srWjFv0P3QXv7WJpp1eKWQ4; //s = getJSONFromUrl(url); s2 = getJSONFromUrl(urldeux); *//*"status": { "uploadStatus": "processed", "privacyStatus": "public", "license": "youtube", "embeddable": true, "publicStatsViewable": true }*//* //JSONObject j = new JSONObject(s); //Log.e("JsonResponse", s); Log.e("JsonResponse2", s2); return true; } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); } }*/ public String getJSONFromUrl(String url) { // Making HTTP request try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); // HttpPost httpPost = new HttpPost(url); HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NegativeArraySizeException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // return JSON String return json; } private class JsoupLyricsAPIv2 extends AsyncTask<Void, Void, Void> { public TextView et; String title; Element row; Document doc; String url; Song song; String api; public JsoupLyricsAPIv2(TextView et, String url, Song song, String api) { this.et = et; this.url = url; this.song = song; this.api = api; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(Void... params) { try { String googleLink = getDataFromGoogle(URLEncoder.encode(url, "UTF-8")); Log.e("ERROOOOOR : ", googleLink); if (!googleLink.equals("NOT FOUND") && (googleLink.startsWith("http://www.azlyrics.com") || googleLink.startsWith("https://www.azlyrics.com"))) { doc = Jsoup.connect(googleLink).userAgent("Mozilla").timeout(5000).get(); //Az Lyrics if (doc.select("div:not([class])").size() > 1) { row = doc.select("div:not([class])").get(1); title = row.text(); title = row.html(); } else { title = "not founde"; } } else { title = "not found"; } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NegativeArraySizeException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { if (row != null) { et.setText(Html.fromHtml(title)); song.setLyrics(title); } else { song.setLyrics("Lyrics not found for this song"); et.setText(song.getLyrics()); } //addLyrics(song); } } private String getDataFromGoogle(String query) { String result = ""; String request = "https://www.google.com/search?q=" + query + "&num=20"; System.out.println("Sending request..." + request); try { // need http protocol, set this as a Google bot agent :) Document doc = Jsoup.connect(request) .userAgent("Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)") .timeout(5000).get(); Element link = doc.select("h3.r > a").first(); String linke = link.attr("href"); if (linke.length() > 0 && linke.contains("http") && linke.contains("html") && linke.contains("azlyrics.com")) { linke = linke.substring(linke.indexOf("http"), linke.indexOf("html")) + "html"; System.out.println("linkv2: " + linke); result = linke; } else { result = "NOT FOUND"; } } catch (IOException e) { e.printStackTrace(); } catch (NegativeArraySizeException e) { e.printStackTrace(); } return result; } public void addSong2(final Song song, final Intent intent, final Context context) { link = ((MyApplication) context).getLink(); url = link + "insertTrack.php"; StringRequest postRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { // response Log.e("Track Database : ", response.toString()); if (response.startsWith("1111") && response.length() > 4) { response = response.substring(4, response.length()); /* Toast.makeText(context, "ID SONG: " + response.toString(), Toast.LENGTH_SHORT).show(); */ song.setId(Integer.valueOf(response)); intent.putExtra("song", (Serializable) song); SearchActivity.app.startActivity(intent); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // error Log.d("Error.Response", error.toString()); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); params.put("name", (song.getTitle() != null) ? song.getTitle().replace("'", "\\'") : ""); params.put("mbid", (song.getMbid() != null) ? song.getMbid() : ""); params.put("length", (song.getLength() != null) ? song.getLength() : ""); params.put("idalbum", (song.getAlbum().getId() != 0) ? String.valueOf(song.getAlbum().getId()) : ""); params.put("idsinger", (song.getSinger().getId() != 0) ? String.valueOf(song.getSinger().getId()) : ""); return params; } }; postRequest.setShouldCache(false); postRequest.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); queue = Volley.newRequestQueue(context); queue.add(postRequest); } public void addSong3(final Song song, final Context context) { link = ((MyApplication) context).getLink(); url = link + "insertTrack.php"; StringRequest postRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { // response Log.e("Track Database : ", response.toString()); if (response.startsWith("1111") && response.length() > 4) { response = response.substring(4, response.length()); /* Toast.makeText(context, "ID SONG: " + response.toString(), Toast.LENGTH_SHORT).show(); */ song.setId(Integer.valueOf(response)); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // error Log.d("Error.Response", error.toString()); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); params.put("name", (song.getTitle() != null) ? song.getTitle().replace("'", "\\'") : ""); params.put("mbid", (song.getMbid() != null) ? song.getMbid() : ""); params.put("length", (song.getLength() != null) ? song.getLength() : ""); params.put("idalbum", (song.getAlbum().getId() != 0) ? String.valueOf(song.getAlbum().getId()) : ""); params.put("idsinger", (song.getSinger().getId() != 0) ? String.valueOf(song.getSinger().getId()) : ""); return params; } }; postRequest.setShouldCache(false); postRequest.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); queue = Volley.newRequestQueue(context); queue.add(postRequest); } public void setTrackId(final Song song, final Context context) { link = ((MyApplication) context).getLink(); url = link + "getTrackId.php"; StringRequest postRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { // response if (response != null) { if (!response.equals("Houston, we have a problem !!") || !response.equals("")) { song.setId(Integer.valueOf(response)); //Toast.makeText(context, "ID SET (set artist id): "+artist.getId(), Toast.LENGTH_SHORT).show(); } else { Log.e("ArtistID", "Artist ID Not Set"); } } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // error Log.d("Error.Response", error.toString()); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); params.put("mbid", song.getMbid()); params.put("title", song.getTitle()); params.put("artist", String.valueOf(song.getSinger().getId())); params.put("album", String.valueOf(song.getAlbum().getId())); return params; } }; queue = Volley.newRequestQueue(context); queue.add(postRequest); } }