I am new in java and javascript programming. Currently I am doing an app to get all mp3 in phone storage and also sd card and pass it to @javascriptinterface then to javascript in html file. When the result show at html, it shows the package file name. e.g. com.xxx.xxx.xxx@12345.
Need to get mp3 name show at html.
Any advice would be appreciated. Thank you.
Here is my code for the activity:
public ArrayList<AudioModel> getAllAudioFromDevice (final Context context){
final ArrayList<AudioModel> tempAudioList = new ArrayList<>();
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; // retrieve song info
String[] projection = {
MediaStore.Audio.AudioColumns.DATA,
MediaStore.Audio.AudioColumns.TITLE,
MediaStore.Audio.AudioColumns.ALBUM,
MediaStore.Audio.ArtistColumns.ARTIST,
MediaStore.Audio.AudioColumns.DURATION,
};
Cursor c = context.getContentResolver().query(uri, // Find from the database according to Uri
projection, null, null, null);
if (c != null) {
while (c.moveToNext()) {
AudioModel audioModel = new AudioModel();
String path = c.getString(0); // Retrieve path.
String name = c.getString(1); // Retrieve name.
String album = c.getString(2); // Retrieve album name.
String artist = c.getString(3); // Retrieve artist name.
String duration = c.getString(4);
audioModel.setaName(name);
audioModel.setaAlbum(album);
audioModel.setaArtist(artist);
audioModel.setaPath(path);
audioModel.setaDuration(duration);
Log.e("Name :" + name, " Album :" + duration);
Log.e("Path :" + path, " Artist :" + artist);
tempAudioList.add(audioModel);
}
c.close();
}
return tempAudioList; // stop getAllAudioFromDevice method
}
public class JavaScriptInterface {
private Activity activity;
Context mContext;
public void JavaScriptInterface(Context c) {
mContext = c;
}
public JavaScriptInterface(Activity activity) {
this.activity = activity;
}
@JavascriptInterface
public String getmp3all() {
getAllAudioFromDevice(MyActivity.this).toString();
}
}
Below is the html file:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table>
<tr>
<td>
<div id="divMp3"></div>
</td>
</tr>
</table>
<script type="text/javascript">
function showMP3(){
var arraymp3 = AndroidFunction.getmp3all();
document.getElementById('divMp3').innerHTML = arraymp3;
}
window.onLoad = showMP3();
</script>
</body>
</html>
Update: Manage to solve the issue above.
@JavascriptInterface
public String getmp3all() {
ArrayList<AudioModel> allMp3 = getAllAudioFromDevice(this.activity);
List<AudioModel> listStrings = new ArrayList<>(allMp3);
String temp= "";
for (int i = 0; i < listStrings.size(); i++) {
temp += listStrings.get(i).aName+",";
}
return temp;
}
HTML file:
<table>
<tbody>
<tr>
<script>
function showMP3(){
var stringmp3 = AndroidFunction.getmp3all();
var arraymp3= stringmp3.split(",");
for(var i = 0; i < arraymp3.length; i++)
{
document.write("<tr>");
document.write("<td>"+ arraymp3[i] +"</td>");
document.write("</tr>");
console.log(arraymp3[i]);
}
}
window.onLoad = showMP3();
</script>
</tr>
</tbody>
</table>