My project is list of music that user can set as ringtone.
All of my music is located in raw and it works correctly and also my ringtone name is a text in raw "zeallist".
My problem is that how to put my music in asset folder.
Here is my code that play music from raw:
public ArrayList<SongInfo> getAllSong(Context context) {
ArrayList<SongInfo> listSong = new ArrayList<SongInfo>();
RingtonesSharedPreferences pref = new RingtonesSharedPreferences(
context);
Field[] fields = R.raw.class.getFields();
for (int i = 0; i < fields.length - 1; i++) {
SongInfo info = new SongInfo();
try {
String name = fields[i].getName();
if (!name.equals("ringtones")) {
info.setFileName(name + ".mp3");
info.setFavorite(pref.getString(info.getFileName()));
int audioResource = R.raw.class.getField(name).getInt(name);
info.setAudioResource(audioResource);
}
// info.setName(name);
} catch (Exception e) {
}
listSong.add(info);
}
InputStream inputStream = context.getResources().openRawResource(
R.raw.zeallist);
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
try {
String line;
int i = 0;
while ((line = reader.readLine()) != null) {
listSong.get(i).setName(line);
i++;
}
} catch (Exception e) {
// TODO: handle exception
} finally {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return listSong;
}
How to change this part of my code to read them from asset and return my listsong ?
Core part I have finished.Some details you need do yourself
public ArrayList<SongInfo> getAllSong(Context context) throws IOException {
ArrayList<SongInfo> listSong = new ArrayList<SongInfo>();
RingtonesSharedPreferences pref = new RingtonesSharedPreferences(context);
String[] files = context.getAssets().list("Your songs path");
for (int i = 0; i < files.length - 1; i++) {
SongInfo info = new SongInfo();
String name = files[i];
if (!name.equals("ringtones")) {
info.setFileName(name + ".mp3");
info.setFavorite(pref.getString(info.getFileName()));
/* int audioResource = R.raw.class.getField(name).getInt(name);
info.setAudioResource(audioResource);*/ //fileName is enough to you
}
// info.setName(name);
listSong.add(info);
}
InputStream inputStream = context.getAssets().open("Your zeallist path");
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
try {
String line;
int i = 0;
while ((line = reader.readLine()) != null) {
listSong.get(i).setName(line);
i++;
}
} catch (Exception e) {
// TODO: handle exception
} finally {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return listSong;
}
When you want to play corresponding music, you could do like this
public void play(MediaPlayer mediaPlayer, Context context, String musicName) throws IOException {
AssetFileDescriptor assetFileDescriptor = context.getAssets().openFd(musicName);
mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(),
assetFileDescriptor.getStartOffset(),
assetFileDescriptor.getLength());
mediaPlayer.prepare();
mediaPlayer.start();
}
Hope this will solve your problem .
Right click on res folder and Create new folder called raw. Now copy paste few .MP3 files inside it. Check those links for better understanding.
link1
link2
From Assest folder
public void playBeep() {
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = new MediaPlayer();
}
AssetFileDescriptor descriptor = getAssets().openFd("mysong.mp3");
mp.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
mp.prepare();
mp.setVolume(1f, 1f);
mp.setLooping(true);
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
You can read file from asset using AssetManager
AssetManager assetManager = getAssets();
String[] files = assetManager.list("");
Note that this file is String array. So don't forget to initialize new file for each element of the array before iterating over it.
Related
I'm a newbie in programming on Android Studio. I'm trying to create a simple application to gain basic experience. In the application, I would need to store individual inputs to a file (ideally CSV) in internal memory. First of all, I am trying to save user data - my name and phone number. The save method looks like this:
public void save(View view)
{
String fileName = "user.csv";
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory = contextWrapper.getDir(getFilesDir().getName(), ContextWrapper.MODE_PRIVATE);
File file = new File(directory, fileName);
String data = "FirstName,LastName,PhoneNumber";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
outputStream.write(data.getBytes());
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
The data seems to be saved and I'm redirected to MainActivity. Here is the method:
protected void onCreate(Bundle savedInstanceState) {
File file = new File(getFilesDir(),"user.csv");
if(!file.exists()) {
Intent intent = new Intent(this, activity_login.class);
startActivity(intent);
}
else {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv_name = findViewById(R.id.tv_name);
TextView tv_phone = findViewById(R.id.tv_phone);
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("user.csv"));
while ((sCurrentLine = br.readLine()) != null) {
tv_name.setText(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
No value is stored in TextView tv_name and the box is empty. Where am I making mistake?
Thank you very much for your help!
For reading data saved use this method uses, UTF_8 ENCODING
public static String readAsString(InputStream is) throws IOException {
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
String line;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
reader = new BufferedReader(new InputStreamReader(is,UTF_8));
}
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} finally {
if (reader != null) {
reader.close();
}
}
return sb.toString();
}
Use this method as follows, parsing file "user.csv".
public static String readFileAsString(File file) throws IOException {
return readAsString(new FileInputStream(file));
}
Fetch string and set textView
Use as this to read file:
FileInputStream fis = new FileInputStream("your full file path");
BufferedReader bfr = new BufferedReader(new InputStreamReader(fis));
Below is the code for creating .csv file and inserting data into it.
For more look into my answer :https://stackoverflow.com/a/48643905/8448886
CODE HERE:
String csv = (Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyCsvFile.csv"); // Here csv file name is MyCsvFile.csv
//by Hiting button csv will create inside phone storage.
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CSVWriter writer = null;
try {
writer = new CSVWriter(new FileWriter(csv));
List<String[]> data = new ArrayList<String[]>();
data.add(new String[]{"Country", "Capital"});
data.add(new String[]{"India", "New Delhi"});
data.add(new String[]{"United States", "Washington D.C"});
data.add(new String[]{"Germany", "Berlin"});
writer.writeAll(data); // data is adding to csv
writer.close();
callRead();
} catch (IOException e) {
e.printStackTrace();
}
}
});
Here I am trying to upload multiple files on google drive app folder:
#Override
protected Boolean doInBackground(DriveFile...params) {
Drive.DriveApi.requestSync(mGoogleApiClient).await();
DriveFile file = params[0];
try {
DriveApi.DriveContentsResult driveContentsResult = file.open(
mGoogleApiClient, DriveFile.MODE_WRITE_ONLY, null).await();
if (!driveContentsResult.getStatus().isSuccess()) {
return false;
}
DriveContents driveContents = driveContentsResult.getDriveContents();
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(DbHelper.databasePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(driveContents.getOutputStream());
/*reading and writing data to and from file*/
int n = 0;
byte[] data = new byte[8 * 1024];
try {
while ((n = bufferedInputStream.read(data)) > 0) {
bufferedOutputStream.write(data, 0, n);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
com.google.android.gms.common.api.Status status =
driveContents.commit(mGoogleApiClient, null).await();
return status.getStatus().isSuccess();
}
return false;
}
While trying to upload two files the doInBackground method gets called only once and only one file gets uploaded which is last in an arraylist of files.
You need to post the complete code which is calling the doInBackground. The issue is with that part of code.
backupBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
createFolderOnGoogleDrive();
multipleFilesArrayList = listFilePath();
createFileAsyncTask = new CreateFileAsyncTask();
multipleFilestoAsynchTask = multipleFilesArrayList.get(i);
createFileAsyncTask.execute(multipleFilesArrayList);
}); }
I have a file stored locally on my device that I read from perfectly fine if I don't reboot the phone. When I reboot and read the logs, new FileReader throws an NPE; why?
BufferedReader br = null;
FileReader fr = null;
try {
Log.d("DEBUG", "Before filereader");
fr = new FileReader(ABS_FILENAME);
Log.d("DEBUG", "Before BufferedReader");
br = new BufferedReader(fr);
String current;
Log.d("DEBUG", "About to read file");
while((current = br.readLine()) != null) {
}
}
} catch (Exception e) {
Log.d("DEBUG", "Exception thrown: " + e.getMessage());
} finally {
try {
if (fr != null) {
fr.close();
}
} catch (IOException ex) {
Log.d("DEBUG", "Problem closing file reader");
}
}
return null;
The above code happens in a broadcast receiver. ABS_FILENAME is a string that denotes a file. That file is written to periodically in an Activity once something is clicked:
// in an onClick that gets invoked
try {
String line = myKey + " " + myValue;
fw.write(line);
fw.write(System.getProperty("line.separator"));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fw != null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// elsewhere in the activity
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
myFile = new File(getFilesDir(), FILENAME);
try {
if (!myFile.exists()) {
myFile.createNewFile();
}
ABS_FILENAME = myFile.getAbsolutePath();
fw = new FileWriter(myFile.getAbsoluteFile(), true);
} catch(IOException e) {
}
If
new FileReader(ABS_FILENAME)
really produces a NullPointerException, clearly ABS_FILENAME must be null.
I am trying to read more than one rss link from the xml source txt file in the code below. I am using ; as the delimiter. From debug, it seems to be sending all the links to RSS_LINK, which is obviously not going to work.
StringBuilder rsslink = new StringBuilder();
InputStream is = getResources().openRawResource(R.raw.xmlsource);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
try {
while ((line = br.readLine()) != null)
{
rsslink.append(line) ;
}
String [] arr = rsslink.toString().split(";");
for (int i = 0; i < arr.length; i++)
{
}
}
catch (IOException e)
{
e.printStackTrace();
}
String RSS_LINK = rsslink.toString();
Log.d(Constants.TAG, "Service started");
List<RssItem> rssItems = null;
try
{
XMLRssParser parser = new XMLRssParser();
rssItems = parser.parse(getInputStream(RSS_LINK));
}
catch (XmlPullParserException e)
{
Log.w(e.getMessage(), e);
}
catch (IOException e)
{
Log.w(e.getMessage(), e);
}
Bundle bundle = new Bundle();
bundle.putSerializable(ITEMS, (Serializable) rssItems);
ResultReceiver receiver = intent.getParcelableExtra(RECEIVER);
receiver.send(0, bundle);
}
New Code
protected void onHandleIntent(Intent intent)
{
StringBuilder rsslink = new StringBuilder();
InputStream is = getResources().openRawResource(R.raw.xmlsource);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
try {
while ((line = br.readLine()) != null)
{
rsslink.append(line) ;
}
String [] arr = rsslink.toString().split(";");
for (int i = 0; i < arr.length; i++)
{
String RssLink = arr[i];
Log.d(Constants.TAG, "Service started");
List<RssItem> rssItems = null;
try
{
XMLRssParser parser = new XMLRssParser();
rssItems = parser.parse(getInputStream(RssLink));
}
catch (XmlPullParserException e)
{
Log.w(e.getMessage(), e);
}
catch (IOException e)
{
Log.w(e.getMessage(), e);
}
Bundle bundle = new Bundle();
bundle.putSerializable(ITEMS, (Serializable) rssItems);
ResultReceiver receiver = intent.getParcelableExtra(RECEIVER);
receiver.send(0, bundle);
}
}
catch (IOException e)
{
e.printStackTrace();
}
You split the rsslink's but instead of using the resulting arr you continue to work with rsslink which still has all links and ; combined.
You need to put all rss handling (parsing etc) into the loop:
String [] arr = rsslink.toString().split(";");
for (int i = 0; i < arr.length; i++)
{
// HERE IS THE PLACE TO HANDLE a single RSS Link. arr contains the single link
}
I have created a txt file and saved it in the file Explorer at data/data/com.xxx/files/mynote/txt when I entered a string into edit text and click the button.
I want compare txt file content and input String. In my txt file, only minimum length 5 to 6 is stored. How do I do this? I have tried but it can not compare properly - it goes to else block part when I entered the same string as i save in my txt file like "tazin".
Here is my code.
btnSubmitCode=(Button)findViewById(R.id.button_Submit);
btnSubmitCode.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(editText_Code.getText().toString().isEmpty())
{
Toast.makeText(getApplicationContext(),"Please Enter Code", Toast.LENGTH_SHORT).show();
}
else
{
String strCode = editText_Code.getText().toString().trim();
create_File(strCode);
readFile();
}
String temp;
String searchString = "tazin";
try {
File file=new File("/data/data/com.xxxxx/files/mynote.txt/");
BufferedReader in = new BufferedReader(new FileReader(file));
while (in.readLine() != null)
{
temp = in.readLine();
System.out.println("String from txt file ="+temp);
if(searchString.equals(temp))
{
System.out.println("word is match");
in.close();
return;
}
else
{
System.out.println("word is not match");
}
}
in.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
//Write File
private void create_File(String strtext)
{
FileOutputStream fos = null;
try
{
fos = openFileOutput("mynote.txt", MODE_PRIVATE);
fos.write(strtext.getBytes());
Toast.makeText(getApplicationContext(), "File created succesfully",
Toast.LENGTH_SHORT).show();
}
catch(FileNotFoundException fexception)
{
fexception.printStackTrace();
}
catch(IOException ioexception)
{
ioexception.printStackTrace();
}
finally
{
if (fos != null)
{
try
{
// drain the stream
fos.flush();
fos.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//Read File
private void readFile()
{
FileInputStream fis;
try
{
fis = openFileInput("mynote.txt");
byte[] reader = new byte[fis.available()];
while (fis.read(reader) != -1)
{
}
textView_ReadCode.setText(new String(reader));
strReadFile = new String(reader);
System.out.println("Read File Into String Format " + strReadFile);
Toast.makeText(getApplicationContext(), "File read succesfully",
Toast.LENGTH_SHORT).show();
if (fis != null)
{
fis.close();
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
Log.e("Read File", e.getLocalizedMessage());
}
}
You're misusing the BufferedReader.readLine() method. You're calling it twice each time through your while loop; once in the while conditional, and once in the loop block itself. So, when you do temp = in.readLine() and then the searchString.equals(temp) comparison, you've already skipped a line from the text file. Structure your loop like so:
temp = in.readLine();
while (temp != null)
{
System.out.println("String from txt file =" + temp);
if(searchString.equals(temp))
{
System.out.println("word is match");
in.close();
return;
}
else
{
System.out.println("word is not match");
}
temp = in.readLine();
}
Edit:
Per our chat in comments, here is the updated code for what you need:
btnSubmitCode.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
String str = editText_Code.getText().toString();
if(str == null || str.equals(""))
{
Toast.makeText(getApplicationContext(), "Please Enter Code", Toast.LENGTH_SHORT).show();
}
else
{
String strCode = str.trim();
if(checkCode(strCode))
{
System.out.println("word is match");
}
else
{
System.out.println("word is not match");
}
}
}
}
);
...
...
// Returns true if the code has already been used
// Returns false if the code is new
// Creates mynote.txt if it doesn't exist
// Appends code if it is new
private boolean checkCode(String code)
{
String temp;
File file = new File(getFilesDir() + "mynote.txt");
if(file.exists())
{
try
{
BufferedReader in = new BufferedReader(new FileReader(file));
temp = in.readLine();
while (temp != null)
{
if(code.equals(temp))
{
// Match was found
// Clean up and return true
in.close();
return true;
}
temp = in.readLine();
}
in.close();
}
catch (FileNotFoundException e)
{
}
catch (IOException e)
{
}
}
// Match was not found or File doesn't exist
// Append code to mynote.txt and return false
try
{
BufferedWriter out = new BufferedWriter(new FileWriter(file, true));
out.newLine();
out.write(code);
out.close();
}
catch (IOException e)
{
}
return false;
}
In your question you wrote different path then you write in your code so just check your path of file.