I am beginner android developer and trying to implement one function for overflow menu.
My menu code is like this
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id==android.R.id.home) {
finish();
}else if (id == R.id.image) {
takeScreenshot(); // getting error like The method takeScreenshot(Context, View) in the type QuoteViewActivity is not applicable for the arguments ()
return true;
}
and
function code is like
public static void takeScreenshot(Context context, View view) {
String path = Environment.getExternalStorageDirectory().toString()
+ "/" + "test.png";
View v = view.findViewById(android.R.id.content).getRootView();
v.setDrawingCacheEnabled(true);
v.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
OutputStream out = null;
File imageFile = new File(path);
try {
out = new FileOutputStream(imageFile);
// choose JPEG format
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
} catch (FileNotFoundException e) {
// manage exception
} catch (IOException e) {
// manage exception
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception exc) {
}
}
// onPauseVideo();
Intent share = new Intent(Intent.ACTION_SEND);
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imageFile));
share.setType("image/png");
((Activity) context).startActivityForResult(
Intent.createChooser(share, "Share Drawing"), 111);
}
How can I call it on menu click ?
Sorry for stupid question for developer
Thanks
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}
}
don't forget this
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
The way you handle the click on a Menu Item is like this:
First, setup your Options Menu:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mnuInflater = getSupportMenuInflater();
mnuInflater.inflate(R.menu.your_menu_xml, menu);
return true;
}
Handle the clicks here:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
// EITHER CALL THE METHOD HERE OR DO THE FUNCTION DIRECTLY
yourMethod();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
And do the function in the yourMethod() here:
private void yourMethod() {
// TODO Auto-generated method stub
}
From what I see, it should be the following:
takeScreenshot(this, findViewById(R.id.your_root_layout));
However, you can call takeScreenshot(); if takeScreenshot is not static and inside your activity.
Related
this is my code I and I want to save this bitmap on my internal storage. The public boolean saveImageToInternalStorage is a code from google but I don't know how to use it. when I touch button2 follow the button1 action.
public class MainActivity extends Activity implements OnClickListener {
Button btn, btn1;
SurfaceView sv;
Bitmap bitmap;
Canvas canvas;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.button1);
btn1=(Button)findViewById(R.id.button2);
sv=(SurfaceView)findViewById(R.id.surfaceView1);
btn.setOnClickListener(this);
btn1.setOnClickListener(this);
bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
}
#Override
public void onClick(View v) {
canvas=sv.getHolder().lockCanvas();
if(canvas==null) return;
canvas.drawBitmap(bitmap, 100, 100, null);
sv.getHolder().unlockCanvasAndPost(canvas);
}
public boolean saveImageToInternalStorage(Bitmap image) {
try {
// Use the compress method on the Bitmap object to write image to
// the OutputStream
FileOutputStream fos = openFileOutput("desiredFilename.png", Context.MODE_PRIVATE);
// Writing the bitmap to the output stream
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
Log.e("saveToInternalStorage()", e.getMessage());
return false;
}
}
}
To Save your bitmap in sdcard use the following code
Store Image
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
To Get the Path for Image Storage
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
EDIT
From Your comments i have edited the onclick view in this the button1 and button2 functions will be executed separately.
public onClick(View v){
switch(v.getId()){
case R.id.button1:
//Your button 1 function
break;
case R.id. button2:
//Your button 2 function
break;
}
}
private static void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String fname = "Image-"+ o +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Modify onClick() as follows:
#Override
public void onClick(View v) {
if(v == btn) {
canvas=sv.getHolder().lockCanvas();
if(canvas!=null) {
canvas.drawBitmap(bitmap, 100, 100, null);
sv.getHolder().unlockCanvasAndPost(canvas);
}
} else if(v == btn1) {
saveBitmapToInternalStorage(bitmap);
}
}
There are several ways to enforce that btn must be pressed before btn1 so that the bitmap is painted before you attempt to save it.
I suggest that you initially disable btn1, and that you enable it when btn is clicked, like this:
if(v == btn) {
...
btn1.setEnabled(true);
}
To save file into directory
public static Uri saveImageToInternalStorage(Context mContext, Bitmap bitmap){
String mTimeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
String mImageName = "snap_"+mTimeStamp+".jpg";
ContextWrapper wrapper = new ContextWrapper(mContext);
File file = wrapper.getDir("Images",MODE_PRIVATE);
file = new File(file, "snap_"+ mImageName+".jpg");
try{
OutputStream stream = null;
stream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
stream.flush();
stream.close();
}catch (IOException e)
{
e.printStackTrace();
}
Uri mImageUri = Uri.parse(file.getAbsolutePath());
return mImageUri;
}
required permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You might be able to use the following for decoding, compressing and saving an image:
#Override
public void onClick(View view) {
onItemSelected1();
InputStream image_stream = null;
try {
image_stream = getContentResolver().openInputStream(myUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap image= BitmapFactory.decodeStream(image_stream );
// path to sd card
File path=Environment.getExternalStorageDirectory();
//create a file
File dir=new File(path+"/ComDec/");
dir.mkdirs();
Date date=new Date();
File file=new File(dir,date+".jpg");
OutputStream out=null;
try{
out=new FileOutputStream(file);
image.compress(format,size,out);
out.flush();
out.close();
MediaStore.Images.Media.insertImage(getContentResolver(), image," yourTitle "," yourDescription");
image=null;
}
catch (IOException e)
{
e.printStackTrace();
}
Toast.makeText(SecondActivity.this,"Image Save Successfully",Toast.LENGTH_LONG).show();
}
});
Here is my code, it says no such file or directory. Can anyone help me with this? I want to save image from URL into storage.
if (imageLoaded) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
if (imageBitmap == null) {
Toast.makeText(getActivity(), "Looks like images didn't load.", Toast.LENGTH_SHORT).show();
} else {
imageBitmap.compress(Bitmap.CompressFormat.JPEG,100,bytes);
File directory = null;
if (Environment.getExternalStorageDirectory().equals(Environment.MEDIA_MOUNTED)) {
directory = new File(Environment.getExternalStorageDirectory(),"COC");
if (!directory.isDirectory()) {
directory.mkdirs();
}
}
File f = new File(directory,ImageName+".jpg");
try {
f.createNewFile();
FileOutputStream fo = null;
fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
Toast.makeText(getActivity(),"saved",Toast.LENGTH_SHORT).show();
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
For this sort of situation choosing a network library like Retrofit would be good . Otherwise you have to create a HTTP url connection , download the image as bitmap and then save it to file . All work needs to be done off the main thread . So lots of thread pooling is needed . So lets solve the problem with retrofit
first add retrofit as dependency to your app level gradle file
compile 'com.squareup.retrofit:retrofit:2.0.0'
compile 'com.squareup.retrofit:converter-gson:2.0.0'
then create a demo layout file with a image view in it , in this image view we are going to show the downloaded image
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageViewId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="1420px"
android:maxHeight="700px"
android:scaleType="fitCenter" />
</RelativeLayout>
after that lets create a network API interface like this
public interface RetrofitImageAPI {
#GET("retrofit/images/uploads/android.jpg")
Call<ResponseBody> getImageDetails();
}
This is a good practice using retrofit as sigleton pattern (see this)
But for demonstration purpose I am showing everything in a single activity
public class MainActivity extends AppCompatActivity {
String url = "http://www.delaroystudios.com/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button ButtonArray= (Button) findViewById(R.id.RetrofitImage);
ButtonArray.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View VisibleImage = findViewById(R.id.RetrofitImage);
VisibleImage.setVisibility(View.GONE);
getRetrofitImage();
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
void getRetrofitImage() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitImageAPI service = retrofit.create(RetrofitImageAPI.class);
Call<ResponseBody> call = service.getImageDetails();
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
try {
Log.d("onResponse", "Response came from server");
boolean FileDownloaded = DownloadImage(response.body());
Log.d("onResponse", "Image is downloaded and saved ? " + FileDownloaded);
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
Log.d("onFailure", t.toString());
}
});
}
private boolean DownloadImage(ResponseBody body) {
try {
Log.d("DownloadImage", "Reading and writing file");
InputStream in = null;
FileOutputStream out = null;
try {
in = body.byteStream();
out = new FileOutputStream(getExternalFilesDir(null) + File.separator + "Android.jpg");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}
catch (IOException e) {
Log.d("DownloadImage",e.toString());
return false;
}
finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
int width, height;
ImageView image = (ImageView) findViewById(R.id.imageViewId);
Bitmap bMap = BitmapFactory.decodeFile(getExternalFilesDir(null) + File.separator + "Android.jpg");
width = 2*bMap.getWidth();
height = 3*bMap.getHeight();
Bitmap bMap2 = Bitmap.createScaledBitmap(bMap, width, height, false);
image.setImageBitmap(bMap2);
return true;
} catch (IOException e) {
Log.d("DownloadImage",e.toString());
return false;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item)
}
}
if it helps please don't forget to like and click the accept button . it means a lot to the person who answers .
have a good day
using Picasso:
Picasso.with(mContext)
.load(ImageUrl)
.into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
try {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/yourDirectory");
if (!myDir.exists()) {
myDir.mkdirs();
}
String name = new Date().toString() + ".jpg";
myDir = new File(myDir, name);
FileOutputStream out = new FileOutputStream(myDir);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch(Exception e){
// some action
}
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
);
Very simple code to save bitmap to file of your choice of directory:
final File myImageFile = new File(FILE_DIRECTORY, IMAGE_NAME); // Create image file
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myImageFile);
IMAGE_BITMAP.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.i("image", "image saved to >>>" + Uri.parse("file://" + myImageFile.toString()).toString());
If you want to use volley then you can do following:
ImageRequest ir = new ImageRequest(url,
new Response.Listener<Bitmap>() {
#Override
public void onResponse(Bitmap response) {
final File myImageFile = new File(fileDirectory, imageName); // Create image file
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myImageFile);
response.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.i("image", "image saved to >>>" + Uri.parse("file://" + myImageFile.toString()).toString()); downloadedFileUris.add(FileProvider.getUriForFile(ViewReportsActivity.this.getBaseContext(), BuildConfig.APPLICATION_ID + ".provider", myImageFile));
}
}, 0, 0, null, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
You complain that a file can not be created. But you try to write a file in a directory that does not exist. After mkdirs() you do not check if the directory is indeed created. Well it is not.
From Android 6 you should at runtime ask the user to confirm the permissions you requested in manifest.
Google for runtime permissions.
I am showing an image in webview and add onclick listener on download button. When user clicks on the download button it get the address of webview (which in this case is www.realearnpak.com/test/1.jpg). Image is shown in webview, but download image function does not work.
Please help me I am new thanks in advance. I tried alternative functions to download image from url but the do not appear to work.
public class MainActivity extends Activity {
public void DownloadImageFromPath(String path){
InputStream in =null;
Bitmap bmp=null;
int responseCode = -1;
try{
URL url = new URL(path);//"http://192.xx.xx.xx/mypath/img1.jpg
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setDoInput(true);
con.connect();
responseCode = con.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK)
{
//download
in = con.getInputStream();
bmp = BitmapFactory.decodeStream(in);
in.close();
}
}
catch(Exception ex){
Log.e("Exception",ex.toString());
}
}
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WebView mWebView= (WebView) findViewById(R.id.webView1);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// Handle the error
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
mWebView.loadUrl("http://www.realearnpak.com/test/1.jpg");
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Reset...");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int which) {
// here you can add functions
}
});
final Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
String webUrl = mWebView.getUrl();
//alertDialog.setMessage(webUrl);
// alertDialog.show();
DownloadImageFromPath(webUrl);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Here is one part of a code you can adapt for you need (but you would need to put it in a asynctask or the like) :
// Defines a handle for the byte download stream
InputStream inputStream = null;
FileOutputStream outputStream = null;
HttpEntity entity = null;
// Downloads the image and catches IO errors
try {
// Opens an HTTP connection to the image's URL
final String imageURL = URLEncoder.encode("http://my-path/to-my/beautiful-picture.jp", "UTF-8").replaceAll("\\+", "%20");
HttpGet httpRequest;
try {
httpRequest = new HttpGet(imageURL);
} catch (Exception e) {
Log.w(TAG, e);
throw new InterruptedException();
}
HttpResponse response = new DefaultHttpClient().execute(httpRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(TAG, "Error " + statusCode + " while retrieving bitmap from " + imageURL);
throw new InterruptedException();
}
// Gets the input stream containing the image
entity = response.getEntity();
inputStream = new BufferedHttpEntity(entity).getContent();
bitmap = BitmapFactory.decodeStream(new FlushedInputStream(inputStream));
if (bitmap == null) {
Log.w(TAG, "Error while decoding bitmap from " + imageURL);
throw new IllegalStateException();
}
outputStream = getContext().openFileOutput("Beautiful-picture.jpg", Context.MODE_PRIVATE);
boolean ok = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
if (!ok) {
Log.w(TAG, "Error while compressing bitmap from " + imageURL);
throw new IllegalStateException();
}
// If an IO error occurs, returns immediately
} catch (IOException e) {
e.printStackTrace();
return;
/*
* If the input stream is still open, close it
*/
} finally {
try {
if (null != inputStream) {
inputStream.close();
}
if (null != outputStream) {
outputStream.close();
}
if (entity != null) {
entity.consumeContent();
}
} catch (Exception e) {
e.printStackTrace();
}
}
For the FlushedInputStream, I let you look by yourself :p
There is a great library for this (actually there are a few). I would suggest you use one of them, as this is a common activity (downloading an image from the Web) and this is NOT something that makes sense to do yourself.
I use Picasso (it is a common favorite), Universal Image Downloader is another option.
I prefer volley depends oon what you need it for.
http://www.bignerdranch.com/blog/solving-the-android-image-loading-problem-volley-vs-picasso/
With a lot of help (on here) I've managed to nearly get my app up and running but I've got a problem. I'm basically a beginner in Java so this is a little deep for me, but I would still like some help. Basically the app displays a list of tones and lets you play them, if you touch and hold it inflates a context menu with an option to copy that selected tone to SD card.
The issue I know lies on the fourth-to-last line: boolean saved = saveas(sound.getSoundResourceId(),"filename"); because the variablesaved is not used.
I'm not too sure how to fix this,or what i should put in place of saved, just wondering if anyone on here has a clue?
Here's the full code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerForContextMenu(getListView());
this.getListView().setSelector(R.drawable.selector);
//create a simple list
mSounds = new ArrayList<Sound>();
Sound s = new Sound();
s.setDescription("Affirmative");
s.setSoundResourceId(R.raw.affirmative);
mSounds.add(s);
s = new Sound();
s.setDescription("Anjels");
s.setSoundResourceId(R.raw.anjels);
mSounds.add(s);
s = new Sound();
s.setDescription("Aggro");
s.setSoundResourceId(R.raw.aggro);
mSounds.add(s);
mSounds.add(s);
mAdapter = new SoundAdapter(this, R.layout.list_row, mSounds);
setListAdapter(mAdapter);
}
#Override
public void onListItemClick(ListView parent, View v, int position, long id){
Sound s = (Sound) mSounds.get(position);
MediaPlayer mp = MediaPlayer.create(this, s.getSoundResourceId());
mp.start();
}#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
public boolean saveas(int ressound, String fName){
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
int size=0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
String path="notifications/halon/";
String filename=fName+".ogg";
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String completePath = baseDir + File.separator + "music" + File.separator + "halon" + File.separator + filename;
boolean exists = (new File(completePath)).exists();
if (!exists){new File(completePath).mkdirs();}
FileOutputStream save;
try {
save = new FileOutputStream(completePath);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));
File k = new File(path, filename);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "exampletitle");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
values.put(MediaStore.Audio.Media.IS_RINGTONE, false);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
//Insert it into the database
this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);
return true;
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
Sound sound = (Sound) getListAdapter().getItem(info.position);
int length = mSounds.size(); // get the length of mSounds object
String[] names = new String[length]; // creates a fixed array with strings
for(int i = 0; i < length; i++) {
// add sound name to string array
names[i] = mSounds.get(i).getDescription(); // returns the string name
}
switch(item.getItemId()) {
case R.id.copytosd:
Toast.makeText(this, "Applying " + getResources().getString(R.string.copy) +
" for " + names[(int)info.id],
Toast.LENGTH_SHORT).show();
boolean saved = saveas(sound.getSoundResourceId(),"filename");
return true;
default:
return super.onContextItemSelected(item);
}
}}
If you are not going to use saved, delete the boolean saved = from that statement and just have saveas(sound.getSoundResourceId(),"filename");.
I've been playing around with this code and I'm obviously trying to make a soundboard that will save ringtones on longclicks and etc.
Though, this is the basic code for one button. I've been duplicating the same code on top of each other, trying to make arrays, just everything.. I can't get this code to work the way I want it to.
When they are multiple buttons and more codes.
I can get the sounds to all play for the buttons. I can get the menu to pop up for each button. Tho, the first button is always the one that gets saved, and the rest just fall off the map.
I assume that my data flow on the following code is not getting cut off and being picked up by the other sound buttons. Either way, it doesn't work. Please help me.
public class Soundboard extends Activity {
private SoundManager mSoundManager;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSoundManager = new SoundManager();
mSoundManager.initSounds(getBaseContext());
mSoundManager.addSound(1, R.raw.sound1);
Button SB = (Button)findViewById(R.id.sound1);
SB.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mSoundManager.playSound(1);
}
});
Button btn = (Button) findViewById(R.id.sound1);
registerForContextMenu(btn);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Save as...");
menu.add(0, v.getId(), 0, "Ringtone");
menu.add(0, v.getId(), 0, "Notification");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if(item.getTitle()=="Ringtone"){function1(item.getItemId());}
else if(item.getTitle()=="Notification"){function2(item.getItemId());}
else {return false;}
return true;
}
public void function1(int id){
if (savering(R.raw.sound1)) {
// Code if successful
Toast.makeText(this, "Saved as Ringtone", Toast.LENGTH_SHORT).show();
}
else
{
// Code if unsuccessful
Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show();
}
}
public void function2(int id){
if (savenot(R.raw.sound1)) {
// Code if successful
Toast.makeText(this, "Saved as Notification", Toast.LENGTH_SHORT).show();
}
else
{
// Code if unsuccessful
Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show();
}
}
//Save into Ring tone Folder
public boolean savering(int ressound){
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
int size=50;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
String path="/sdcard/media/audio/ringtones/";
String filename="ohhh"+".ogg";
boolean exists = (new File(path)).exists();
if (!exists){new File(path).mkdirs();}
FileOutputStream save;
try {
save = new FileOutputStream(path+filename);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)
));
File k = new File(path, filename);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "Ohhh Ringtone");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "weee");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
//Insert it into the database
this.getContentResolver().insert(
MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);
return true;
}
//Save in Notification Folder
public boolean savenot(int ressound){
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
int size=0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
String path="/sdcard/media/audio/notifications/";
String filename="ohhh"+".ogg";
boolean exists = (new File(path)).exists();
if (!exists){new File(path).mkdirs();}
FileOutputStream save;
try {
save = new FileOutputStream(path+filename);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)
));
File k = new File(path, filename);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "Ohhh Notification");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "weee");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
//Insert it into the database
this.getContentResolver().insert(
MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);
return true;
}
}
I'm just learning Android programming myself, but it seems like this is why you're always saving the first sound:
savering(R.raw.sound1)
and
savenot(R.raw.sound1)
Both of those are explicitly saving the first sound. Unless you've written a separate function1 and function2 for each button. But there's got to be a better way to manage saving than that.