stranges with android mediaservice - Java for Android App Development

I've got nexus 4 and have some issue with media servicem cause my MS could not find music on my internal SD card; So I make an app;
Code:
public class SingleMediaScanner implements MediaScannerConnectionClient {
private MediaScannerConnection mMs;
private File mFile;
public SingleMediaScanner(Context context, File f) {
mFile = f;
mMs = new MediaScannerConnection(context, this);
mMs.connect();
}
[user=439709]@override[/user]
public void onMediaScannerConnected() {
Log.v("MS", "connected");
mMs.scanFile(mFile.getAbsolutePath(), "audio/*");
Log.v("MS-file", mFile.getAbsolutePath());
}
[user=439709]@override[/user]
public void onScanCompleted(String path, Uri uri) {
mMs.disconnect();
}
}
Code:
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath()+"/Music/");
for (int i=0;i<dir.listFiles().length;i++)
{
if (dir.listFiles()[i].isFile()==true&&dir.listFiles()[i].getName().endsWith(".mp3"))
{
new SingleMediaScanner(this, dir.listFiles()[i].getAbsoluteFile());
}
Log says that MS was connected and tried to scan media file, but file doesnt appear in Media library , what's the problem? by the way I have CM ROM

Related

database connect doesn't work properly

i've need to connect my app to an external database so i put my sqlite database on assets folder and i've follow this tutorial to make DBHelper.
now i want to show some record of database in my app but when i launch it, it give me an error like a table "linee" doesn't exists on my database but it exists!!!! this link cans proof it http://img689.imageshack.us/img689/926/ytvo.png
why???? it's a week that i can to fix this problem but i can't solve it
this is MyOpenHelper
Code:
public class MyOpenHelper extends SQLiteOpenHelper{
//The Android's default system path of your application database.
private static String DB_PATH ;
private SQLiteDatabase db;
private static String DB_NAME = "orari";
private final Context myContext;
public MyOpenHelper(Context context) {
super(context, DB_NAME, null, 1);// 1? its Database Version
if(android.os.Build.VERSION.SDK_INT >= 4.2){
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
} else {
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
}
this.myContext = context;
}
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist){
}else{
this.getReadableDatabase();
try{
copyDataBase();
}catch (IOException e){
throw new Error("Errore nel copiare il database");
}
}
}
private boolean checkDataBase(){
File dbFile=new File(DB_PATH+DB_NAME);
return dbFile.exists();
}
private void copyDataBase() throws IOException{
InputStream myInput=myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH+DB_NAME;
OutputStream myOutput=new FileOutputStream(outFileName);
byte[] buffer = new byte [1024];
int length;
while ((length=myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException{
String myPath=DB_PATH+DB_NAME;
db=SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
[user=439709]@override[/user]
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
[user=439709]@override[/user]
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}

Dynamically loading an external library at runtime

I am using and android 2.2 phone for testing and getting an error which is driving me crazy
07-27 01:24:55.692: W/System.err(14319): java.lang.ClassNotFoundException: com.shoaib.AndroidCCL.MyClass in loader [email protected]
Can someone help me what to do now..i have tried various suggested solutions on different posts
First I wrote the following class:
Code:
package org.shoaib.androidccl;
import android.util.Log;
public class MyClass {
public MyClass() {
Log.d(MyClass.class.getName(), "MyClass: constructor called.");
}
public void doSomething() {
Log.d(MyClass.class.getName(), "MyClass: doSomething() called.");
}
}
And I packaged it in a DEX file that I saved on my device's SD card as `/sdcard/testdex.jar`.
Then I wrote the program below, after having removed `MyClass` from my Eclipse project and cleaned it:
Code:
public class Main extends Activity {
[user=1299008]@supp[/user]ressWarnings("unchecked")
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
final String libPath = Environment.getExternalStorageDirectory() + "/testdex.jar";
final File tmpDir = getDir("dex", 0);
final DexClassLoader classloader = new DexClassLoader(libPath, tmpDir.getAbsolutePath(), null, this.getClass().getClassLoader());
final Class<Object> classToLoad = (Class<Object>) classloader.loadClass("org.shoaib.androidccl.MyClass");
final Object myInstance = classToLoad.newInstance();
final Method doSomething = classToLoad.getMethod("doSomething");
doSomething.invoke(myInstance);
} catch (Exception e) {
e.printStackTrace();
}
}
}
As far as I know you can't load external dex classes (and certainly not a jar file), the only ones that can be loaded are the ones packaged in the classes.dex file inside the APK and protected by its signature and certificate.
This would be quite a security flaw if your app could be "clean" at install but then download malicious classes and execute them.

[Q] Copy Image from Gallery Share (Send To) menu

Moderators... It says I am breaking the rules by asking a question and to ask in the Q&A... But the title of this is "Coding Discussion, Q&A, and Educational Resources" I am not breaking the rules intentionally, I just don't know where else to put this. This is a Coding Question, not a General Question that I would think would get buried and or lost in the General Q&A forum. Please move if you feel I am incorrect.
Hello All, I was hoping someone could help me.
I am trying to create an app that will hide pictures. I want to be able to Pick my App from the Share (Send To) menu from the Users Gallery and have it copy the file to a Directory I have created on my SDCard and then ultimately delete the file from the current location.
Here is what I have so far, but when I pick my app from the Share menu, it crashes the Gallery app. So... I can't even see any errors in my LogCat to even try and troubleshoot my issue.
Can someone point me to a working example of how to do this (I have searched the internet until I am blue in the face) or... I hate to say it... Fix my Code?
Any Help would be appreciated... Thanks!!
Code:
package com.company.privitegallery;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
public class SendToDo extends Activity {
File sdCardLoc = Environment.getExternalStorageDirectory();
File intImagesDir = new File(sdCardLoc,"/DCIM/privgal/.nomedia");
private static final int CAMERA_REQUEST = 1888;
private String selectedImagePath;
String fileName = "capturedImage.jpg";
private static Uri mCapturedImageURI;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
// Get intent, action and MIME type
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("text/plain".equals(type)) {
handleSendText(intent); // Handle text being sent
} else if (type.startsWith("image/")) {
handleSendImage(intent); // Handle single image being sent
try {
GetPhotoPath();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
if (type.startsWith("image/")) {
handleSendMultipleImages(intent); // Handle multiple images being sent
}
} else {
// Handle other intents, such as being started from the home screen
}
//...
}
void handleSendText(Intent intent) {
String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
if (sharedText != null) {
// Update UI to reflect text being shared
}
}
void handleSendImage(Intent intent) {
Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (imageUri != null) {
// Update UI to reflect image being shared
}
}
void handleSendMultipleImages(Intent intent) {
ArrayList<Uri> imageUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
if (imageUris != null) {
// Update UI to reflect multiple images being shared
}
}
public void GetPhotoPath() throws IOException {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
copy(fileName, intImagesDir);
}
[user=439709]@override[/user]
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_REQUEST) {
selectedImagePath = getPath(mCapturedImageURI);
Log.v("selectedImagePath: ", ""+selectedImagePath);
//Save the path to pass between activities
try {
copy(selectedImagePath, intImagesDir);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public void copy(String scr, File dst) throws IOException {
InputStream in = new FileInputStream(scr);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
private void deleteLatest() {
// TODO Auto-generated method stub
File f = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera" );
//Log.i("Log", "file name in delete folder : "+f.toString());
File [] files = f.listFiles();
//Log.i("Log", "List of files is: " +files.toString());
Arrays.sort( files, new Comparator<Object>()
{
public int compare(Object o1, Object o2) {
if (((File)o1).lastModified() > ((File)o2).lastModified()) {
// Log.i("Log", "Going -1");
return -1;
} else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
// Log.i("Log", "Going +1");
return 1;
} else {
// Log.i("Log", "Going 0");
return 0;
}
}
});
//Log.i("Log", "Count of the FILES AFTER DELETING ::"+files[0].length());
files[0].delete();
}
}
What's the gallery log output?
Btw, you're not breaking the rules. This is the right forum for Java Q&A.
nikwen said:
What's the gallery log output?
Click to expand...
Click to collapse
How would I get the Logs for the Gallery? I am using and HTC ONE and it's the standard Gallery. Nothing shows up in LogCat so I'm stuck
nikwen said:
Btw, you're not breaking the rules. This is the right forum for Java Q&A.
Click to expand...
Click to collapse
Great, Thanks!!
StEVO_M said:
How would I get the Logs for the Gallery? I am using and HTC ONE and it's the standard Gallery. Nothing shows up in LogCat so I'm stuck
Great, Thanks!!
Click to expand...
Click to collapse
Do you view the logs on your computer?
There should be an error message in the logs.
nikwen said:
Do you view the logs on your computer?
There should be an error message in the logs.
Click to expand...
Click to collapse
Which Logs?? As I said before. LogCat does not give any errors.

File Save code is not saving file in internal storage

i want to save a layout (relative layout), when i run the app everything is working fine, but i am unable to find saved file/s in the internal storage of the phone. Any help would be appreciated as i am new and unable to sort out what is going wrong . here is my code
Code:
public void saveMe(View v) {
// get prompts.xml view
LayoutInflater li = LayoutInflater.from(this);
View promptsView = li.inflate(R.layout.prompt, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set prompt.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialog);
// set dialog message
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
final String fileName = userInput.getText().toString();
final View view1=findViewById(R.id.relativeLayout); // The view that you want to save as an image
Bitmap bitmap = Bitmap.createBitmap(view1.getWidth(), view1.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
view1.draw(c);
if(fileName.length() == 0)
Toast.makeText(EidCardFinal.this,"Please Enter File Name",Toast.LENGTH_SHORT).show();
else{
File file = new File(context.getFilesDir(), fileName);
if (file.exists())
Toast.makeText(EidCardFinal.this,"File Already Exists",Toast.LENGTH_SHORT).show();
else{
try{
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, out);
Toast.makeText(EidCardFinal.this,"File Saved",Toast.LENGTH_SHORT).show();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
Try adding a line:
out.flush();
just before calling close() on the FileOutputStream. I think this will get the save code to work, and it's worth trying.
ExoComet said:
Try adding a line:
out.flush();
just before calling close() on the FileOutputStream. I think this will get the save code to work, and it's worth trying.
Click to expand...
Click to collapse
thanks for the suggestion, but i have opted for the external storage and its working fine

[Q]Problem using RootTools library

i am trying to list files of root folders using roottools libary .here is the code
Code:
public ArrayList<File> listFiles(final Context c,final String path) {
final ArrayList<File> a=new ArrayList<File>();
Command command = new Command(0, "ls "+path)
{
@Override
public void commandOutput(int i, String s) {
File f=new File(path+"/"+s);
a.add(f);}
@Override
public void commandTerminated(int i, String s) {
}
@Override
public void commandCompleted(int i, int i2) {
//want to arraylist return from here
}
};
try {
RootTools.getShell(true).add(command);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
now problem is that if i return arraylist<file> from the end of method,its size is zero,to solve it i must return the arraylist from commandCompleted
method.but i am not able to accomplish that.So please solve my problem
Maybee arraylist as static outside your function? So on top of source file? Not sure but maybee

Categories

Resources