This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Trouble with reading file from assets folder in Android
Hey I'm trying to read a file from the assets folder in android and this is what i have so far
public class TestingMusicDAO {
private static final String TAG_NAME = "MUSIC_TESTING_DAO";
private static List<Song> songs;
private ContentResolver contentResolver;
private static Context testingcontext;
private File fFile;
InputStream inputStream = null;
public TestingMusicDAO( Context context) throws IOException{
Log.d(TAG_NAME, "Setting up testing songs");
contentResolver = context.getContentResolver();
testingcontext = context;
getAllSongsFromFile();
}
public static void getAllSongsFromFile() throws IOException{
Log.d( TAG_NAME, "Tryign to Get all Songs" );
InputStream is;
is = testingcontext.getAssets().open("testing");
Log.d( TAG_NAME, "Did that work?" );
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(is));
String inputLine;
while((inputLine = bufferReader.readLine()) != null){
processLine(inputLine);
}
bufferReader.close();
}
private static void logSongs() {
for(Song song : songs)
Log.d( TAG_NAME, song.toString() );
}
public List<Song> getAllSongs() {
return songs;
}
public static void processLine(String aLine) {
Scanner scanner = new Scanner(aLine);
scanner.useDelimiter("=");
if(scanner.hasNext()){
String title = scanner.next();
String artist = scanner.next();
String album = scanner.next();
String id = scanner.next();
String albumId = scanner.next();
String trackOrder = scanner.next();
Log.d(TAG_NAME, "Title = " + title + "Artist = " + artist + "Album = " + album + "ID = " + id + "AlbumID = " + albumId);
}
else {
Log.d(TAG_NAME, "Empty or invalid line. Unable to process");
}
}
}
So I basically call the TestingMusicDAO constructor and from there I want to read each line of the file individually to be able to parse them but it keeps giving me a FileNotFoundExecption: testing. Any ideas would be great thanks!
Peter,
Assuming that the exception is coming from the is = testingcontext.getAssets().open("testing"); line, then you do not have a file named testing in the root of your assets/ folder.
Related
Problem Statement
1)I am a beginner at implementing youtube api and I want to retrieve VideoMetaData such as duration of video and stream url.
MyAnalysis :
1)I have used the youtube api to retrieve this metaData such as Video Tilte,VideoID and creation Date.
2)The problem is I am not able to see other data such as Video duration and stream url in the Response.
//Also,StartTime and EndTime has been depreciated.So I cannot find duration
Then,how can I fetch these details related to video.
Below is the response I am getting.
https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.playlistItems.list?part=snippet%252CcontentDetails&maxResults=25&playlistId=PL8WtjSOdakGuBu0q9EKLXndc4jcAQxs2Y&_h=1&
Code for the Same :
public class Search1 {
private static YouTube.PlaylistItems.List playlistItemRequest;
private static String PLAYLIST_ID = "PL8WtjSOdakGuBu0q9EKLXndc4jcAQxs2Y";
private static final Long NUMBER_OF_VIDEOS_RETURNED = (long) 10;
private static String apiKey="AIzaSyDJAaPLW5wbWdfKX6CjfvSo5yrF3K3rlwc";
private static YouTube youtube;
public static void main(String s[]){
youtube = new YouTube.Builder(new NetHttpTransport(),
new JacksonFactory(), new HttpRequestInitializer()
{
#Override
public void initialize(HttpRequest hr) throws IOException {}
}).setApplicationName("youtube-cmdline-search-sample").build();
List<PlaylistItem> playlistItemList = new ArrayList<PlaylistItem>();
try
{
playlistItemRequest = youtube.playlistItems().list("snippet,contentDetails");
playlistItemRequest.setPlaylistId(PLAYLIST_ID);
playlistItemRequest.setFields("items(snippet/title,snippet/playlistId,snippet/publishedAt,snippet/description,snippet/thumbnails/default/url,contentDetails/videoId,contentDetails/startAt,contentDetails/endAt,contentDetails/videoPublishedAt),nextPageToken,pageInfo");
playlistItemRequest.setKey(apiKey);
// videoItem.setId(item.getContentDetails().getVideoId());
String nextToken = "";
do {
playlistItemRequest.setPageToken(nextToken);
PlaylistItemListResponse playlistItemResult = playlistItemRequest.execute();
playlistItemList.addAll(playlistItemResult.getItems());
nextToken = playlistItemResult.getNextPageToken();
} while (nextToken != null);
}catch(IOException e)
{
System.out.println("Exception"+e);
}
Iterator iteratorSearchResults=playlistItemList.iterator();
while (iteratorSearchResults.hasNext()) {
PlaylistItem playlist = (PlaylistItem) iteratorSearchResults.next();
// String duration=(playlist.getContentDetails().getStartAt()-playlist.getContentDetails().getEndAt());
System.out.println(" Title: " + playlist.getSnippet().getTitle());
System.out.println(" Video Created Date" + playlist.getContentDetails().getVideoPublishedAt());
System.out.println(" PlayList ID: " + playlist.getSnippet().getPlaylistId());
System.out.println(" Video ID: " + playlist.getContentDetails().getVideoId());
System.out.println(" Stream url of PlayList: ");
System.out.println(" Start Time: " + playlist.getContentDetails().getStartAt());
System.out.println(" End Time: " + playlist.getContentDetails().getEndAt());
System.out.println(" Duration " );
}
}
}
I had the same issue and proceeded as bellow to retrieve the duration. Note that i had to make a separate request just for video duration. First i had to read the json response using the video ID and of course the "part" and my APIkey.
the part here is "contentDetails"
String retrieveVideoJSON(String videoID, String part, String APIkey) {
String postURL = "https://www.googleapis.com/youtube/v3/videos?id=" + videoID + "&part=" + part + "&key=" + APIkey;
String output = "";
try {
URL url = new URL(postURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
BufferedReader br1 = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String line1;
while ((line1 = br1.readLine()) != null) {
output = output + line1;
}
conn.disconnect();
br1.close();
} catch (IOException e) {
System.out.println("\ne = " + e.getMessage() + "\n");
}
return output;
}
Then i used JSONObject Class from org.json api to parse the json and get the duration
String videoJSON = retrieveVideoJSON(videoID, "contentDetails", myAPIkey);
JSONObject jsonObj = new JSONObject(videoJSON).getJSONArray("items").getJSONObject(0).getJSONObject("contentDetails");
long seconds = Duration.parse(jsonObj.getString("duration")).getSeconds();
You can notice that i used java.time.Duration object to parse the duration format to seconds.
it's available id JDK 1.8
I hope it helps someone
As stated in this thread, you may get the duration using the part=contentDetails. Sample response:
"contentDetails": {
"duration": string,
"dimension": string,
"definition": string,
...
},
Regarding stream URL, check this cdn.ingestionInfo.ingestionAddress.
The primary ingestion URL that you should use to stream video to YouTube. You must stream video to this URL.
Depending on which application or tool you use to encode your video stream, you may need to enter the stream URL and stream name separately or you may need to concatenate them in the following format:
STREAM_URL/STREAM_NAME
Check these Java Code Samples.
I used th following changes in the Code to access Video MetaData
1)Change was done to retrieve url where I concatinated the url along with videoId
2)Made a Connection with youtube api again to retrieve video metadata
public static final MediaType JSON= MediaType.parse("application/json; charset=utf-8");
static String url="http://eventapi-dev.wynk.in/tv/events/v1/event";
static OkHttpClient client = new OkHttpClient();
private static YouTube.PlaylistItems.List playlistItemRequest;
private static String PLAYLIST_ID = "PL8WtjSOdakGuBu0q9EKLXndc4jcAQxs2Y";
private static String apiKey="AIzaSyDJAaPLW5wbWdfKX6CjfvSo5yrF3K3rlwc";
private static YouTube youtube;
public static void main(String s[]) throws IOException {
//Create a Bean
WynkData wd=new WynkData();
String videoID=null;
//Make a Connection with YouTubeApi
youtube = new YouTube.Builder(new NetHttpTransport(),
new JacksonFactory(), new HttpRequestInitializer()
{
#Override
public void initialize(HttpRequest hr) throws IOException {}
}).setApplicationName("youtube-cmdline-search-sample").build();
List<PlaylistItem> playlistItemList = new ArrayList<PlaylistItem>();
try
{
//Specify the search Params
playlistItemRequest = youtube.playlistItems().list("snippet,contentDetails");
playlistItemRequest.setPlaylistId(PLAYLIST_ID);
playlistItemRequest.setFields("items(snippet/title,snippet/playlistId,snippet/publishedAt,contentDetails/videoId,contentDetails/videoPublishedAt),nextPageToken,pageInfo");
playlistItemRequest.setKey(apiKey);
String nextToken = "";
do
{
// Execute and add in a list
playlistItemRequest.setPageToken(nextToken);
PlaylistItemListResponse playlistItemResult = playlistItemRequest.execute();
playlistItemList.addAll(playlistItemResult.getItems());
nextToken = playlistItemResult.getNextPageToken();
}while (nextToken != null);
}
catch(IOException e)
{
System.out.println("Exception"+e);
}
// Retrieve the Recods
Iterator<PlaylistItem> iteratorSearchResults=playlistItemList.iterator();
while (iteratorSearchResults.hasNext()) {
PlaylistItem playlist = (PlaylistItem) iteratorSearchResults.next();
wd.setTitle(playlist.getSnippet().getTitle());
System.out.println(" Title: " + playlist.getSnippet().getTitle());
System.out.println(" Video Created Date" + playlist.getContentDetails().getVideoPublishedAt());
wd.setCreatedDate(playlist.getContentDetails().getVideoPublishedAt());
//Change1
System.out.println("Video Url https://www.youtube.com/watch?v="+playlist.getContentDetails().getVideoId());
videoID=playlist.getContentDetails().getVideoId();
System.out.println(" Stream url of PlayList: ");
String streamurl="https://www.youtube.com/watch?v="+videoID;
wd.setStreamurl(streamurl);
System.out.println(" PlayList ID: " + playlist.getSnippet().getPlaylistId());
System.out.println(" Video ID: " + playlist.getContentDetails().getVideoId());
}
Change2
// Make a Connection with YouTube Api again to retrieve Video Duration
System.out.println(videoID);
final String videoId = videoID;
YouTube.Videos.List videoRequest = youtube.videos().list("snippet,statistics,contentDetails");
videoRequest.setId(videoId);
videoRequest.setKey(apiKey);
VideoListResponse listResponse = videoRequest.execute();
List<Video> videoList = listResponse.getItems();
Video targetVideo = videoList.iterator().next();
System.out.println(targetVideo.getSnippet().getTitle());
System.out.println(targetVideo.getStatistics().getViewCount());
String duration=targetVideo.getContentDetails().getDuration();
StringBuilder sb=new StringBuilder(duration);
duration=sb.substring(2).replaceAll("[A-Z]",":").toString();
wd.setDuration(duration);
System.out.println(wd);
import java.util.Scanner;
import java.util.Formatter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
class Enrolment{
public static void main(String[] args)
{
System.out.println("/*-------------------------------------");
System.out.println("My name: XIANGYU QIAO");
System.out.println("My student number: 5089864");
System.out.println("My email address: xq907#uowmail.edu.au");
System.out.println("Assignment number: 2");
System.out.println("-------------------------------------*/");
System.out.print("\nStudent " + Fullname + Email + Course+ Studentnumber);
System.out.print("\nEnrolment " + Subjectcode + session + Year);
}
}
class Student{
private static Formatter outStream;
private static Scanner inStream;
public Student() throws IOException
{
outStream = new Formatter(new File("student1.txt"));
String fullName = "David Black";
String email = "davblk#ipw.edu.au";
String course = "1853E";
sNumber = 375428;
outStream.format("%s %s %s %i", fullName, email, course, sNumber);
outStream.close();
inStream = new Scanner( new File("student1.txt"));
String Fullname = inStream.next();
String Email = inStream.next();
String Course = inStream.next();
int Studentnumber = inStream.nextInt();
inStream.close();
}
public void displayStudInfo()
{
System.out.print("\nStudent " + Fullname + Email + Course+ Studentnumber);
}
}
class Subject{
private static Formatter outStream;
private static Scanner inStream;
public Subject() throws IOException
{
outStream = new Formatter(new File("subject1.txt"));
String sCode = "CSIT455";
String session = "Autmn";
int year = 2017;
outStream.format("%s %s %i", sCode, session, year);
outStream.close();
inStream = new Scanner( new File("subject1.txt"));
String Subjectcode = inStream.next();
String Session = inStream.next();
int Year = inStream.nextInt();
inStream.close();
System.out.print("\nEnrolment " + Subjectcode + session + Year);
}
}
i am trying to create a file of student information and display it but i could not find a way to do that. could anyone help me to fix the code?
i am asked to display the student information in class Enrolment(main method here)and subject information that is given in class Student and Subject.i have no idea how to link these three things though it requires to use displayStudInfo method in class Student and displaySubjectInfo in class Subject.
If I correctly understand, you cannot access properties from constructor in displayStudInfo method. So assigning those properties to class properties will resolve the issue.
class Student {
private final String fullname;
private final String email;
private final String course;
private final int studentNumber;
public Student() throws IOException {
writeStudent();
Scanner inStream = new Scanner(new File("student1.txt"));
fullname = inStream.next();
email = inStream.next();
course = inStream.next();
studentNumber = inStream.nextInt();
inStream.close();
}
private void writeStudent() throws FileNotFoundException {
Formatter outStream = new Formatter(new File("student1.txt"));
outStream.format("%s %s %s %i", "David Black", "davblk#ipw.edu.au", "1853E", 375428);
outStream.close();
}
public void displayStudInfo() {
System.out.print("\nStudent " + fullname + email + course + studentNumber);
}
}
If you do not want to add any more class prop, you will need to ad arguments to your method:
public void displayStudInfo( String fullname,String email,String course, int studentNumber) {
System.out.print("\nStudent " + fullname + email + course + studentNumber);
}
This question already has answers here:
Ship an application with a database
(15 answers)
Closed 6 years ago.
recently i am trying to build an application that can open existing SQLite database using Android Studio, and i am still a newbie on android programming...when i was searching for the way to open the database, i found this link :
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
btw i still don't know how to implement the code on that link into my project...is there anyone here who is kind enough to help make the examples (or at least give some direction) about how to use it? Just a simple example is really enough for me...thx before :)
You can just use new DBManager().getAllCities() in activity.
/**
* author zaaach on 2016/1/26.
*/
public class DBManager {
private static final String ASSETS_NAME = "china_cities.db";
private static final String DB_NAME = "china_cities.db";
private static final String TABLE_NAME = "city";
private static final String NAME = "name";
private static final String PINYIN = "pinyin";
private static final int BUFFER_SIZE = 1024;
private String DB_PATH;
private Context mContext;
// public static DBManager init(){
// if (mInstance == null){
// synchronized (DBManager.class){
// if (mInstance != null){
// mInstance = new DBManager();
// }
// }
// }
// return mInstance;
// }
public DBManager(Context context) {
this.mContext = context;
DB_PATH = File.separator + "data"
+ Environment.getDataDirectory().getAbsolutePath() + File.separator
+ context.getPackageName() + File.separator + "databases" + File.separator;
}
#SuppressWarnings("ResultOfMethodCallIgnored")
public void copyDBFile(){
File dir = new File(DB_PATH);
if (!dir.exists()){
dir.mkdirs();
}
File dbFile = new File(DB_PATH + DB_NAME);
if (!dbFile.exists()){
InputStream is;
OutputStream os;
try {
is = mContext.getResources().getAssets().open(ASSETS_NAME);
os = new FileOutputStream(dbFile);
byte[] buffer = new byte[BUFFER_SIZE];
int length;
while ((length = is.read(buffer, 0, buffer.length)) > 0){
os.write(buffer, 0, length);
}
os.flush();
os.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public List<City> getAllCities(){
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(DB_PATH + DB_NAME, null);
Cursor cursor = db.rawQuery("select * from " + TABLE_NAME, null);
List<City> result = new ArrayList<>();
City city;
while (cursor.moveToNext()){
String name = cursor.getString(cursor.getColumnIndex(NAME));
String pinyin = cursor.getString(cursor.getColumnIndex(PINYIN));
city = new City(name, pinyin);
result.add(city);
}
cursor.close();
db.close();
Collections.sort(result, new CityComparator());
return result;
}
}
I'm trying to get mp3 files from a folder path of my system to list it in my listView, but unfortunately there's always the same error. (java.lang.NullPointerException: Attempt to get length of null array)
class Mp3Filter implements FilenameFilter{
public boolean accept(File dir, String name){
return (name.endsWith(".mp3"));
}
}
private static final String SD_PATH = new String(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).toString());
public void searchForSongs() {
ListView listView;
listView = (ListView) findViewById(R.id.listView);
File f = new File(SD_PATH);
try {
if (f.listFiles(new Mp3Filter()).length > 0){
for (File file : f.listFiles(new Mp3Filter())){
list.add(file.getName());
}
}
}
catch(Exception e) {
textView2.setText(""+e);
return;
}
final ArrayAdapter songList = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(songList);
}
Here is your solution use the following code to Read the MP3 file from the Specific Folder..
First of all Create 1 Model class as Given Below, to GET and SET Files in list.
AudioModel.class
public class AudioModel {
String aPath;
String aName;
String aAlbum;
String aArtist;
public String getaPath() {
return aPath;
}
public void setaPath(String aPath) {
this.aPath = aPath;
}
public String getaName() {
return aName;
}
public void setaName(String aName) {
this.aName = aName;
}
public String getaAlbum() {
return aAlbum;
}
public void setaAlbum(String aAlbum) {
this.aAlbum = aAlbum;
}
public String getaArtist() {
return aArtist;
}
public void setaArtist(String aArtist) {
this.aArtist = aArtist;
}
}
Now We have our Model Class Now use the below code to Read the all MP3 files from your Folder.
This will return list of all MP3 Files with Music NAME, PATH, ARTIST, ALBUM and if you wants more detail please refer Media.Store.Audio doc..
https://developer.android.com/reference/android/provider/MediaStore.Audio.html
public List<AudioModel> getAllAudioFromDevice(final Context context) {
final List<AudioModel> tempAudioList = new ArrayList<>();
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.Audio.AudioColumns.DATA, MediaStore.Audio.AudioColumns.ALBUM, MediaStore.Audio.ArtistColumns.ARTIST,};
Cursor c = context.getContentResolver().query(uri, projection, MediaStore.Audio.Media.DATA + " like ? ", new String[]{"%yourFolderName%"}, null);
if (c != null) {
while (c.moveToNext()) {
AudioModel audioModel = new AudioModel();
String path = c.getString(0);
String album = c.getString(1);
String artist = c.getString(2);
String name = path.substring(path.lastIndexOf("/") + 1);
audioModel.setaName(name);
audioModel.setaAlbum(album);
audioModel.setaArtist(artist);
audioModel.setaPath(path);
Log.e("Name :" + name, " Album :" + album);
Log.e("Path :" + path, " Artist :" + artist);
tempAudioList.add(audioModel);
}
c.close();
}
return tempAudioList;
}
To Read Files of Specific Folder, use below Query and write your folder name in Query..
Cursor c = context.getContentResolver().query(uri,
projection,
MediaStore.Audio.Media.DATA + " like ? ",
new String[]{"%yourFolderName%"}, // yourFolderName
null);
If you wants All Files of device use below Query..
Cursor c = context.getContentResolver().query(uri,
projection,
null,
null,
null);
Don't forget to add Storage Permission .. enjoy.
I wrote a simple java application, I have a problem please help me;
I have a file (JUST EXAMPLE):
1.TXT
-------
SET MRED:NAME=MRED:0,MREDID=60;
SET BCT:NAME=BCT:0,NEPE=DCS,T2=5,DK0=KOR;
CREATE LCD:NAME=LCD:0;
-------
and this is my source code
import java.io.IOException;
import java.io.*;
import java.util.StringTokenizer;
class test1 {
private final int FLUSH_LIMIT = 1024 * 1024;
private StringBuilder outputBuffer = new StringBuilder(
FLUSH_LIMIT + 1024);
public static void main(String[] args) throws IOException {
test1 p=new test1();
String fileName = "i:\\1\\1.txt";
File file = new File(fileName);
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, ";|,");
while (st.hasMoreTokens()) {
String token = st.nextToken();
p.processToken(token);
}
}
p.flushOutputBuffer();
}
private void processToken(String token) {
if (token.startsWith("MREDID=")) {
String value = getTokenValue(token,"=");
outputBuffer.append("MREDID:").append(value).append("\n");
} else if (token.startsWith("DK0=")) {
String value = getTokenValue(token,"=");
outputBuffer.append("DK0=:").append(value).append("\n");
} else if (token.startsWith("NEPE=")) {
String value = getTokenValue(token,"=");
outputBuffer.append("NEPE:").append(value).append("\n");
}
if (outputBuffer.length() > FLUSH_LIMIT) {
flushOutputBuffer();
}
}
private String getTokenValue(String token,String find) {
int start = token.indexOf(find) + 1;
int end = token.length();
String value = token.substring(start, end);
return value;
}
private void flushOutputBuffer() {
System.out.print(outputBuffer);
outputBuffer = new StringBuilder(FLUSH_LIMIT + 1024);
}
}
I want this output :
MREDID:60
DK0=:KOR
NEPE:DCS
But this application show me this :
MREDID:60
NEPE:DCS
DK0=:KOR
please tell me how can i handle this , because of that DK0 must be at first and this is just a sample ; my real application has 14000 lines
Thanks ...
Instead of outputting the value when you read it, put it in a hashmap. Once you've read your entire file, output in the order you want by getting the values from the hashmap.
Use a HashTable to store the values and print from it in the desired order after parsing all tokens.
//initialize hash table
HashTable ht = new HashTable();
//instead of outputBuffer.append, put the values in to the table like
ht.put("NEPE", value);
ht.put("DK0", value); //etc
//print the values after the while loop
System.out.println("MREDID:" + ht.get("MREDID"));
System.out.println("DK0:" + ht.get("DK0"));
System.out.println("NEPE:" + ht.get("NEPE"));
Create a class, something like
class data {
private int mredid;
private String nepe;
private String dk0;
public void setMredid(int mredid) {
this.mredid = mredid;
}
public void setNepe(String nepe) {
this.nepe = nepe;
}
public void setDk0(String dk0) {
this.dk0 = dk0;
}
public String toString() {
String ret = "MREDID:" + mredid + "\n";
ret = ret + "DK0=:" + dk0 + "\n";
ret = ret + "NEPE:" + nepe + "\n";
}
Then change processToken to
private void processToken(String token) {
Data data = new Data();
if (token.startsWith("MREDID=")) {
String value = getTokenValue(token,"=");
data.setMredid(Integer.parseInt(value));
} else if (token.startsWith("DK0=")) {
String value = getTokenValue(token,"=");
data.setDk0(value);
} else if (token.startsWith("NEPE=")) {
String value = getTokenValue(token,"=");
data.setNepe(value);
}
outputBuffer.append(data.toString());
if (outputBuffer.length() > FLUSH_LIMIT) {
flushOutputBuffer();
}
}