I want to share my mp3 file with External Storage on the WhatsApp application, but when I open my application and press the button, it throws it from the application. I have codes below. Can you tell me my error?`
Button paylas ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
paylas = (Button)findViewById(R.id.paylas);
paylas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra("sms_body", "bod of sms");
sendIntent.setType("*/*");
sendIntent.setClassName("com.mec.enes", "com.mec.enes.MainActivity");
final File file1 = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"sesler");
Uri uri = Uri.fromFile(file1);
sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(sendIntent, ""));
}
});
}
public void hariciYaz(){
try {
File dosyaYolu = Environment.getExternalStorageDirectory();
File dosya = new File(dosyaYolu , "sesler");
if(!dosya.exists()){
dosya.createNewFile();
}
FileWriter fw = new FileWriter(dosya);
BufferedWriter yazici = new BufferedWriter(fw);
yazici.write("src\\main\\res\\raw\\helikopter.mp3");
yazici.flush();
yazici.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}`
yazici.write("src\main\res\raw\helikopter.mp3"); is there an error in this code? Is the audio file in the raw folder saved to external storage like this?
I'm creating an app which has a csvfile stored in its Raw resource folder and when I click on a button in main Activity , it should print the data of the csvfile in second Activity. But when I launch the app and then launch the second activity using a button ,its output is blank...
I have tried using various codes from stack overflow but I was not able to achieve the desired result. My csv File is really long, but I have kept a portion of it in here , so pls bear with me ;-) :
6200,30,10,9
6200 N,30,10,9
6200 NR,30,10,9
6200 ZNR,30,10,9
6200 ZZNR,30,10,9
6300,35,10,11
6300 2RS,35,10,11
6300 RS,35,10,11
6300 Z,35,10,11
6300 ZZ,35,10,11
6201,32,12,10
6201 2RS,32,12,10
6201 N,32,12,10
6201 NR,32,12,10
6201 RS,32,12,10
6201 Z,32,12,10
6201 ZNR,32,12,10
6201 ZZ,32,12,10
This is my code:-
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = findViewById(R.id.button1);
Button button2 = findViewById(R.id.button2);
Button button3 = findViewById(R.id.button3);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SecondActivity();
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ThirdActivity();
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FourthActivity();
}
});
}
public void SecondActivity() {
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
public void ThirdActivity(){
Intent intent = new Intent(this, ThirdActivity.class);
startActivity(intent);
}
public void FourthActivity(){
Intent intent = new Intent(this,FourthActivity.class);
startActivity(intent);
}
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
InputStream inputStream;
String[] data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
inputStream = getResources().openRawResource(R.raw.bearingdata);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String csvLine;
while ((csvLine = reader.readLine()) != null)
{
data=csvLine.split(",");
try{
Log.e("Data ",""+data[0]) ;
Log.e("Data ",""+data[0]+""+data[1]+""+data[2]) ;
}catch (Exception e){
Log.e("Problem",e.toString());
}
}
}
catch (IOException ex) {
throw new RuntimeException("Error in reading CSV file: "+ex);
}
}
So am I missing something like a create a separate java class for the csv file or is some of my code missing something??? Pls help , because I am just trying to learn some coding and also do this correctly.
Also by the way, I want to display the csv file in a list view on SecondActivity.
#Nachiketa,
I have tried your shared code and modified using asset manager and able to see the data in the logcat. Please see the below code,
AssetManager am = getAssets();
try {
InputStream is = am.open("one.csv");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String csvLine;
while ((csvLine = reader.readLine()) != null)
{
data=csvLine.split(",");
try{
Log.e("Data ",""+data[0]) ;
Log.e("Data ",""+data[0]+""+data[1]+""+data[2]) ;
}catch (Exception e){
Log.e("Problem",e.toString());
}
}
} catch (IOException e) {
e.printStackTrace();
}
Please check this and mark as answered, if solves your problem.
Thanks
Now I have app which save and read some text into .txt file by button. How can I make that app save file after app closed and reading file when app opened automatically, without any click on buttons?
public class mAcitivity extends AppCompatActivity {
private Button btn_read, btn_save;
private TextView textView;
private String txt = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveFile();
}
});
btn_read.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
readFile();
textView.setText(txt);
}
});
}
public String readFile() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/TEST");
myDir.mkdirs();
File file = new File(myDir, "file.txt");
try {
FileInputStream fis = new FileInputStream(file);
int size = fis.available();
byte[] buffer = new byte[size];
fis.read(buffer);
fis.close();
txt = new String(buffer);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(mActivity.this, "Error reading file", Toast.LENGTH_LONG).show();
}
return txt;
}
public void saveFile() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/TEST");
myDir.mkdirs();
File file = new File(myDir, "file.txt");
if (file.exists()){ file.delete();}
try {
String sometxt = "Hello world";
FileOutputStream out = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(out);
pw.println(sometxt);
pw.flush();
pw.close();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can use your MainActivity lifecycle callbacks to begin your I/O operations directly, or start BoundService which will operate them.
You can achieve this by putting your saveFile() method inside stop() lifecycle method, and putting your readFile() method inside start() lifecycle method. Activity will automatically call start() method once the application starts and it will call stop() method once the applicqtion closes/terminates.
im making an app consist of some pdf file but i dont know how i can work with that
1- where i should copy my pdf files in resource ? (which folder?)
2- what code needed to open its ? (what codes need to write in onClick method ? )
3- what class and methods is usfull for this procedure ?
leave this below codes ( they are for body error ignoring )
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.main);}
If you want to open the PDF from a webview you can use the following code:
public class ActivityName extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView mWebView=new WebView(MyPdfViewActivity.this);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginsEnabled(true);
mWebView.loadUrl("https://docs.google.com/gview?embedded=true&url="+LinkTo);
setContentView(mWebView);
}
}
If you would like to open the PDF locally, you can an place it in either the res/raw folder or the assets folder(in the following example the assets folder is used). Then you need to place the file locally using the following code:
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(getExternalFilesDir(null), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
Then you can use the following code to access the PDF, again assuming the user has a PDF viewer installed:
public class OpenPdf extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.OpenPdfButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File file = new File("/sdcard/example.pdf");
if (file.exists()) {
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
Toast.makeText(OpenPdf.this,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
If you want to open it from your application you can try this
I have an EditText in which the user inputs their name, then i want to push a button and the content of the EditText is transferred into a file.
EDITED: I have this code so far:
Button submitButton = (Button) findViewById(R.id.baddNametoFile);
submitButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try{
ETName.getText().toString();
PrintWriter writer = new PrintWriter(new BufferedWriter(
new FileWriter("/sdcard/Accelerometer.html", true)));
writer.println("<h3 style=padding-left:20px;>" + ETName
+ "</h3><br>");
// new arraylist
writer.close();
}catch (IOException e) {
// put notification here later!!!
e.printStackTrace(); }
}
});
I have it printing to the file what the actual android value is:
android.widget.Button{......./baddNametoFile}
But that is just a placeholder to know the print works. I would like to see what the user has typed printed there instead.
Any help would be great. Thanks
ETName is probably EditText. You didnt post to much code so it should be like:
ETName.getText().toString(); Change View ETName in View v (it is click on a button not on a EditText). Lets try like this:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
String etName = ETName.getText().toString();
if(!etName.trim().equals("")){
File file =new File("/sdcard/Accelerometer.html");
//if file doesnt exists, then create it
if(!file.exists()){
file.createNewFile();
}
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(etName);
bufferWritter.close();
}
}catch (IOException e) {
e.printStackTrace(); }
}
try{
File dir = new File("/mnt/sdcard/MyApp/");
if (!dir.exists()) {
dir.mkdir();
System.out.println("Directory created");
}
//ceate .rtf file with header
myFile = new File("/mnt/sdcard/MyApp/Student.rtf");
if (!myFile.exists()) {
myFile.createNewFile();
System.out.println("File created");
}
fOut = new FileOutputStream(myFile.getAbsoluteFile(),true);
myOutWriter = new OutputStreamWriter(fOut);
//Write the header : in your case it is : Student class Marsk (only one time)
myOutWriter.write("Student,class,Marks"+"\n");
myOutWriter.flush();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}