Why does my android shareIntent not work? - java

I have a soundboard app and am trying to enable the user to share the sounds from my res/raw folder. My code seems to properly create a folder and copy the resource into it. However, when trying to share, I always get an error from the external app. (e.g. gmail says: "Cannot attach file"). Can anyone please help?
The code:
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class Pls {
public void sendAudio(Activity activity){
try {
String mediaPath = copyFiletoExternalStorage(R.raw.audio_file, "audiofile.mp3",activity);
Intent shareMedia = new Intent(Intent.ACTION_SEND);
shareMedia.setType("audio/*");
shareMedia.putExtra(Intent.EXTRA_STREAM, Uri.parse(mediaPath));
activity.startActivity(Intent.createChooser(shareMedia, "Select app"));
} catch (Exception e) {
Toast.makeText(activity.getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
private String copyFiletoExternalStorage(int resourceId, String resourceName,Activity activity){
String pathSDCard = Environment.getExternalStorageDirectory() + "/Android/data/" + resourceName;
try{
InputStream in = activity.getResources().openRawResource(resourceId);
FileOutputStream out = null;
out = new FileOutputStream(pathSDCard);
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}
} catch (IOException e) {
Log.i("err",e.toString());
}
return pathSDCard;
}
}

Related

AsyncTask/doInBackground not executing

I'm trying to create an app that queries a site of cat images, saves them to the android device if the JSON ID is unique, and then display them from the device in a slideshow format. Despite everything my AsyncTask doesn't seem to actually be executing. Debugger confirms a network connection is established and doesn't feed me back any errors so I have no idea what's wrong with my code. Hoping someone can help! Code is below:
package com.example.lab2;
import androidx.appcompat.app.AppCompatActivity;
import androidx.loader.content.AsyncTaskLoader;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ProgressBar;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Array;
import java.util.ArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CatImages req = new CatImages();
req.execute();
}
class CatImages extends AsyncTask<String, Integer, String> {
ArrayList<String> ids = new ArrayList<String>();
ContextWrapper cw = new ContextWrapper(getApplicationContext());
Bitmap images;
String id;
ImageView imageView = findViewById(R.id.imageView);
ProgressBar progressBar = findViewById(R.id.progressBar);
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
boolean on = true;
#Override
protected String doInBackground(String... strings) {
while(on == true) {
try {
URL url = new URL("https://cataas.com/cat?json=true");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream response = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(response, "UTF-8"), 8);
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
builder.append(line + "\n");
}
String result = builder.toString();
JSONObject image = new JSONObject(result);
id = image.getString("id");
ids.add(id);
for (String element : ids) {
if (element.contains(id)) {
return null;
} else {
images = BitmapFactory.decodeStream(response);
File path = new File(directory, id + ".jpg");
FileOutputStream outputStream = new FileOutputStream(path);
images.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
outputStream.flush();
outputStream.close();
ids.add(id);
}
}
for (int i = 0; i < 100; i++) {
try {
publishProgress(i);
Thread.sleep(30);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException | JSONException e) {
return null;
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
for(String element : ids) {
if(element.contains(id)) {
File openedPic = new File(directory, id + ".jpg");
try {
Bitmap opener = BitmapFactory.decodeStream(new FileInputStream(openedPic));
imageView.setImageBitmap(opener);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onPostExecute(String fromDoInBackground) {
super.onPostExecute(fromDoInBackground);
}
}
}
Try changing !=null to ==null in your second while loop.
Also you just need while(on) in your first while loop.
Let me know if anything changes.

Slideshow code seems correct, but app does nothing when executing in emulator

I'm trying to build an app for school that queries a website full of random cat pictures and displays them on an emulated android TV. My code looks right, but when I run it I get the spinning wheel showing it's loading and nothing else. I'm not sure what exactly is missing, but hoping someone can point me in the right direction. Code is below:
package com.example.lab2;
import androidx.appcompat.app.AppCompatActivity;
import androidx.loader.content.AsyncTaskLoader;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.widget.ImageView;
import android.widget.ProgressBar;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Array;
import java.util.ArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> ids = new ArrayList<String>();
class CatImages extends AsyncTask<String, Integer, String> {
ContextWrapper cw = new ContextWrapper(getApplicationContext());
Bitmap images;
String id;
ImageView imageView = findViewById(R.id.imageView);
ProgressBar progressBar = findViewById(R.id.progressBar);
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
boolean on = true;
#Override
protected String doInBackground(String... strings) {
while(on == true) {
try {
URL url = new URL("https://cataas.com/cat?json=true");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream response = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(response, "UTF-8"), 8);
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
builder.append(line + "\n");
}
String result = builder.toString();
JSONObject image = new JSONObject(result);
id = image.getString("id");
for (String element : ids) {
if (element.contains(id)) {
return null;
} else {
images = BitmapFactory.decodeStream(response);
File path = new File(directory, id + ".jpg");
FileOutputStream outputStream = new FileOutputStream(path);
images.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
outputStream.flush();
outputStream.close();
ids.add(id);
}
}
for (int i = 0; i < 100; i++) {
try {
publishProgress(i);
Thread.sleep(30);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException | JSONException e) {
return null;
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
for(String element : ids) {
if(element.contains(id)) {
File openedPic = new File(directory, id + ".jpg");
try {
Bitmap opener = BitmapFactory.decodeStream(new FileInputStream(openedPic));
imageView.setImageBitmap(opener);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
}

FileOutputStream are not working

I made an android app for learning Java.
Now i like to write objects from a list with objects to a file.
like ...
private List<MyObjects> objects = new ArrayList<MyObjects>();
MyObjects is a extra class and implements "Serializable".
To write the objects in a file i use also a extra class.
Now my problem.
With the below Line i get a FileNotFoundException.
fos = new FileOutputStream(fileName);
When i change this Line with this Line ...
fos = ctx.openFileOutput(fileName, Context.MODE_PRIVATE);
... looks like good but after endig the code i can't find the file in data/data/myPakage/files/.
The file is not exist.
I read the last 4 days a lot of sites and tutorials about that but i can't find my mistake.
Please help my.
I don't need a solved code but a link to the right side or a pointer in my mistaken code is fine.
Sorry for my english. Is not my first language.
I am not sure with code parts you need to get a good overview. If you need more, please tell me.
Here parts of my main site
package com.example.myProject;
import android.os.Bundle;
import android.app.FragmentTransaction;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
public class ActivityMain extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout_calc);
TabAdapter = new TabPagerAdapter(getSupportFragmentManager());
}
}
Here parts of my fragment site
package com.example.myProject;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class Fragment_1 extends Fragment implements OnClickListener {
private Button btnOFF;
private List<Numbers> number = new ArrayList<Numbers>();
private View fragment_1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
this.fragment_1 = inflater.inflate(R.layout.fragment_layout, container, false);
this.btnOFF = (Button)elementary.findViewById(R.id.id_btnOFF_Elementary);
this.btnOFF.setOnClickListener(this);
this.number.add(new Numbers());
// Here i try to get my data back from the file.
// Every time i get the information; The file not exist
// Perhaps the "containsAll" are wrong. But this is in the moment not my problem.
this.number.containsAll(StreamControl.importNumbers(this.getActivity()));
return fragment_1;
}
#Override
public void onClick(View buttonView) {
if (buttonView == this.btnOFF) {
// Here i try to export data over extra class -- see below
// I put in my List with objects calls "number" and information
// for "Context" i hope.
StreamControl.exportNumbers(number, this.getActivity());
}
}
}
Parts of my class Numbers
package com.example.myProject;
import java.io.Serializable;
public class Numbers implements Serializable {
private static final long serialVersionUID = -5384438724532423282L;
.
.
.
}
Here the code from the file "in" and "out"
package com.example.myProject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
public class StreamControl {
public static void exportNumbers(List<Numbers> number, Context ctx) {
String fileName = "MyCacheFile.ser";
File cacheFile = new File(fileName);
FileOutputStream fos = null;
try {
// With this line is it not working everytime.
// File not found exception
// But to make my own file with "createNewFile()" is not working
// in data/data i have just read permission.
fos = new FileOutputStream(cacheFile);
// If i use this line i have less problems.
// All Informations "i used Toast on a lot of places" was god.
// But after it, it was nowhere a file to found.
//fos = ctx.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(fos);
oos.writeInt(number.size());
for (int i =0; i < number.size(); i++) {
oos.writeObject(new Numbers(((Numbers)number.get(i)).getNumbers()));
}
}
catch (IOException e1) { e1.printStackTrace(); }
finally {
try {
if (oos != null) { oos.close(); }
}
catch (IOException ex) { }
}
}
catch (FileNotFoundException e2) { e2.printStackTrace(); }
finally {
try {
if (fos != null) { fos.close(); }
}
catch (IOException ex) { ex.printStackTrace(); }
}
}
public static List<Numbers> importNumbers(Context ctx) {
String fileName = "MyCacheFile.ser";
int count = 0;
List<Numbers> number = new ArrayList<Numbers>();
FileInputStream fis = null;
try {
fis = new FileInputStream(fileName);
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(fis);
count = ois.readInt();
for (int i = 0; i < count; i++) {
number.add(new Numbers(((Numbers) ois.readObject()).getNumbers()));
}
}
catch (IOException ex) { ex.printStackTrace(); }
catch (ClassNotFoundException ex) { ex.printStackTrace(); }
finally {
try {
if (ois != null) { ois.close(); }
}
catch (IOException ex) { ex.printStackTrace(); }
}
}
catch (FileNotFoundException ex) { ex.printStackTrace(); }
finally {
try {
if (fis != null) { fis.close(); }
}
catch (IOException ex) { ex.printStackTrace(); }
}
return number;
}
}
So, i hope that's are enough information.
I looking forward
When you use Context.openFileOutput you create a file in internal storage and you can't check that directory.
Take a look at this to save a file to external storage

change name audio recorder android

I'm building an audio recorder using MediaRecorder and I want to rename the created file
So my main steps are:
import java.io.File;
import java.io.IOException;
import java.util.Locale;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private MediaRecorder recorder = null;
private int currentFormat = 0;
private int output_formats = MediaRecorder.OutputFormat.MPEG_4;
private String file_exts = AUDIO_RECORDER_FILE_EXT_MP4 ;
private String getFilename() {
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath, AUDIO_RECORDER_FOLDER);
if (!file.exists()) {
file.mkdirs();
}
return (file.getAbsolutePath() + "/" + System.currentTimeMillis() +
file_exts);
}
private void startRecording() {
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(output_formats(currentFormat));
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(getFilename());
recorder.setOnErrorListener(errorListener);
recorder.setOnInfoListener(infoListener);
try {
recorder.prepare();
recorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void stopRecording() {
if (null != recorder) {
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
}
}
}
and in AudioRecorder folder it created with name "138672.mp4"
So, how to change that, i want to it created with name a.mp4(example)
you can use this code instead of your getFilename() method:
private String getFilename() {
File file = new File(Environment.getExternalStorageDirectory(), "a.mp4");
if (!file.exists()) {
file.mkdirs();
}
set this code in startRecording() method:
recorder.setOutputFile(file+"");

error opening trace file: No such file in directory (2), cannot locate file

I am new here.
I consider myself to have broken past newbie-ism and I am breaking into intermediate programming. I am trying to read from my assets folder, and the problem I am having is that my program keeps catching the exception. Can you help me figure out what I am doing wrong? Here is my code:
package com.example.testone;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.widget.TextView;
public class AssetsTest extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
setContentView(textView);
AssetManager assetManager = getAssets();
InputStream inputStream = null;
try {
inputStream = getAssets().open("myawesometext.txt");
String text = loadTextFile(inputStream);
textView.setText(text);
} catch (IOException e) {
textView.setText("Couldn't load file");
} finally {
if (inputStream != null)
try {
inputStream.close();
} catch (IOException e) {
textView.setText("Couldn't close file");
}
}
}
public String loadTextFile(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
byte[] bytes = new byte[4096];
int len = 0;
while ((len = inputStream.read(bytes)) > 0)
byteStream.write(bytes, 0, len);
return new String(byteStream.toByteArray(), "UTF8");
}
}
I have searched every website including this one, combing over the other similar questions, and could not find an answer that worked for me. Your help would be so greatly appreciated.
Thanks in advance!

Categories

Resources