Java tutorial
/* * * * * This file is part of LyricsWithMusixMatchAPI Project. * * Created by adwardStark. * * * * LyricsWithMusixMatchAPI Project 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. * * * * LyricsWithMusixMatchAPI Project 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 LyricsWithMusixMatchAPI Project. If not, see <http://www.gnu.org/licenses/>. * * */ package com.adwardstark.lyricswithmusixmatchapi; import android.app.Dialog; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; 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 java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import java.net.URL; public class MainActivity extends AppCompatActivity { String myJSON, apiKey, detailsList = "", firstTrackID = null, songLyrics = ""; JSONArray peoples = null; private static final String TAG_MESSAGE = "message"; private static final String TAG_BODY = "body"; private static final String TAG_TRACK_LIST = "track_list"; private static final String TAG_TRACK = "track"; private static final String TAG_TRACK_ID = "track_id"; private static final String TAG_ALBUM_NAME = "album_name"; private static final String TAG_ARTIST_NAME = "artist_name"; private static final String TAG_LYRICS = "lyrics"; private static final String TAG_LYRICS_BODY = "lyrics_body"; private static final String TAG_LYRICS_COPYRIGHT = "lyrics_copyright"; private static final String TAG_LAST_UPDATE_TIME = "updated_time"; EditText songtxtbx; TextView displayTxt, displayLyricsTxt; int count = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); apiKey = getString(R.string.MusixMatchAPI_Key); songtxtbx = (EditText) findViewById(R.id.edt1); displayTxt = (TextView) findViewById(R.id.detailstxtview); displayLyricsTxt = (TextView) findViewById(R.id.lyricstxtview); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Snackbar.make(view, "Se", Snackbar.LENGTH_LONG) //.setAction("Action", null).show(); String songname = songtxtbx.getText().toString(); songname = songname.replaceAll(" ", "%20"); searchSong(songname); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { // create a Dialog component final Dialog dialog = new Dialog(this); //tell the Dialog to use the dialog.xml as it's layout description dialog.setContentView(R.layout.aboutdialog); dialog.setTitle("About Developer"); dialog.show(); return true; } return super.onOptionsItemSelected(item); } private void searchSong(final String songname) { try { class SearchSongAsync extends AsyncTask<String, Void, String> { private Dialog loadingDialog; @Override protected void onPreExecute() { super.onPreExecute(); loadingDialog = ProgressDialog.show(MainActivity.this, "Please wait", "Searching for song..."); } @Override protected String doInBackground(String... params) { String result = null; InputStream inputStream = null; try { String link = "http://api.musixmatch.com/ws/1.1/track.search?apikey=" + apiKey + "&q_track=" + songname + "&format=json&page_size=10"; URL url = new URL(link); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI(link)); HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); inputStream = entity.getContent(); // json is UTF-8 by default BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } result = sb.toString(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (inputStream != null) inputStream.close(); } catch (Exception squish) { } } return result; } @Override protected void onPostExecute(String result) { myJSON = result; loadingDialog.dismiss(); checkResult(); } } SearchSongAsync la = new SearchSongAsync(); la.execute(); } catch (Exception ex) { Toast.makeText(getBaseContext(), "You are not connected", Toast.LENGTH_LONG).show(); } } protected void checkResult() { peoples = null; detailsList = ""; if (myJSON != null && myJSON.isEmpty() != true) { try { JSONObject jsonObj = new JSONObject(myJSON); JSONObject messageOBJ = jsonObj.getJSONObject(TAG_MESSAGE); JSONObject bodyOBJ = messageOBJ.getJSONObject(TAG_BODY); peoples = bodyOBJ.getJSONArray(TAG_TRACK_LIST); for (int i = 0; i < peoples.length(); i++) { JSONObject x = peoples.getJSONObject(i); JSONObject c = x.getJSONObject(TAG_TRACK); if (count == 0) { firstTrackID = c.getString(TAG_TRACK_ID); count = 1; } detailsList = detailsList + "\nNew Data \n\n" + "Track_ID: " + c.getString(TAG_TRACK_ID) + "\n" + "Album_Name: " + c.getString(TAG_ALBUM_NAME) + "\n" + "Artist_Name: " + c.getString(TAG_ARTIST_NAME) + "\n"; } count = 0; displayTxt.setText("Total no. of enteries retrieved: " + peoples.length() + "\n" + detailsList); getLyricsForTheSong(firstTrackID); } catch (JSONException e) { e.printStackTrace(); } } else { displayTxt.setText("No data recieved.\nVerfiy that you've entered correct data."); } } private void getLyricsForTheSong(final String track_id) { try { class GetLyricsAsync extends AsyncTask<String, Void, String> { private Dialog loadingDialog; @Override protected void onPreExecute() { super.onPreExecute(); loadingDialog = ProgressDialog.show(MainActivity.this, "Please wait", "Searching for lyrics..."); } @Override protected String doInBackground(String... params) { String result = null; InputStream inputStream = null; try { String link = "http://api.musixmatch.com/ws/1.1/track.lyrics.get?apikey=" + apiKey + "&track_id=" + track_id + "&format=json"; URL url = new URL(link); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI(link)); HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); inputStream = entity.getContent(); // json is UTF-8 by default BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } result = sb.toString(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (inputStream != null) inputStream.close(); } catch (Exception squish) { } } return result; } @Override protected void onPostExecute(String result) { myJSON = result; loadingDialog.dismiss(); checkLyrics(); } } GetLyricsAsync la = new GetLyricsAsync(); la.execute(); } catch (Exception ex) { Toast.makeText(getBaseContext(), "You are not connected", Toast.LENGTH_LONG).show(); } } protected void checkLyrics() { peoples = null; if (myJSON != null && myJSON.isEmpty() != true) { try { JSONObject jsonObj = new JSONObject(myJSON); JSONObject messageOBJ = jsonObj.getJSONObject(TAG_MESSAGE); JSONObject bodyOBJ = messageOBJ.getJSONObject(TAG_BODY); JSONObject lyricsOBJ = bodyOBJ.getJSONObject(TAG_LYRICS); songLyrics = songLyrics + "\nLyrics of the first song \n\n" + lyricsOBJ.getString(TAG_LYRICS_BODY) + "\n\n" + lyricsOBJ.getString(TAG_LYRICS_COPYRIGHT) + "\n" + lyricsOBJ.getString(TAG_LAST_UPDATE_TIME); if (songLyrics != null && songLyrics.isEmpty() != true) { displayLyricsTxt.setText(songLyrics); } else { songLyrics = songLyrics + "Lyrics Not Available." + "\n\n" + lyricsOBJ.getString(TAG_LYRICS_COPYRIGHT) + "\n" + lyricsOBJ.getString(TAG_LAST_UPDATE_TIME); displayLyricsTxt.setText(songLyrics); } } catch (JSONException e) { e.printStackTrace(); } } else { displayTxt.setText("No data recieved.\nVerfiy that you've entered correct data."); } } }