using ContentResolver and openInputStream() (Android) - java

New in Android and
Working on an app like This
At the end got the problem java.io.FileNotFoundException: /document/86: open failed: ENOENT (No such file or directory)
Now I'm working on the solution that
"That how to use ContentResolver and openInputStream()"
Anyone help me how to do this, please

if you trying to make an app that read a file from Phone
Try This
Try this may help
private InputStream getResources(String s) {
return null;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("text/plain");
startActivityForResult(intent, 7);
Log.v("###", "parent " + getParent());
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri PathHolder = data.getData();
Log.v("###", "yo " + PathHolder);
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 7:
if (resultCode == RESULT_OK) {
setContentView(R.layout.activity_main);
try {
InputStream inputStream = getContentResolver().openInputStream(PathHolder);
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
String mLine;
while ((mLine = r.readLine()) != null) {
text.append(mLine);
text.append('\n');
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Related

How to pass a file from a file picker to a function?

I have an app that opens up a file picker and it outputs the path of that file in a Toast Message.
But I would like to change it such that the file that I pick is passed as a parameter to a function.
My activity looks like this:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.btn_picker);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, 7);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch (requestCode) {
case 7:
if (resultCode == RESULT_OK) {
String PathHolder = data.getData().getPath();
Toast.makeText(MainActivity.this, "The Files path is: "+ PathHolder, Toast.LENGTH_LONG).show();
}
break;
}
}
}
And it does what it is supposed to do but instead of outputting the file path, I would like to call the function
importToFile()
From the manage class.
I would like to do something like this:
manage.importToFile(File1)
Where File1 is the file I selected from the file picker.
How can I do that.
Thanks in advance.
You can use File class in android to work with files. Create an instance of File using the path of the selected file and pass it to that method of yours. Something like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch (requestCode) {
case 7:
if (resultCode == RESULT_OK) {
// as #Taseer Ahmad said its not a good way to get path of the file.
//String PathHolder = data.getData().getPath();
String PathHolder = getPath(this, data.getData());
if (!TextUtils.isEmpty(PathHolder)) {
File file = new File(PathHolder);
manager.importToFile(file);
Toast.makeText(MainActivity.this, "The Files path is: "+ PathHolder, Toast.LENGTH_LONG).show();
}
}
break;
}
}
EDIT
As #Taseer Ahmad said, data.getData().getPath() is not a safe way to get path of the selected file. This code is copied from here.
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = { "_data" };
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}

Choosing a file from the sdcard and sending it by HTTP Post

I want to make an application that allows me to choose a file from SDcard (.apk file), then send it by HTTP Post to a web service.
The problem is that even if I can choose the file, I can't convert it in a byte array because my application is looking for it in its private folders, not in SDcard.
I used Intent to access to FileManager and choose a file from storage. Then, a toast notification shows me its path.
public class MainActivity extends AppCompatActivity {
Button button1;
Intent intent;
String PathHolder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
PathHolder = data.getData().getPath();
File file = new File(PathHolder);
String FileName = file.getName();
Toast.makeText(MainActivity.this, PathHolder, Toast.LENGTH_LONG).show();
try {
byte[] bArray = new byte[(int) file.length()];
FileInputStream inputStream = new FileInputStream(file);
inputStream.read(bArray);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
}
}
After
FileInputStream inputStream = new FileInputStream(f);
My application throws an Exception and the response is :
File Not Found
The variable f, on which you are constructing the FileInputStream of is never assigned or am I wrong? I think you should change f to file.

Cannot take picture or choose image from gallery

Sorry guys, I'm very new to android and now need to create a simple camera in my android studio.
When I choose an image from gallery or take a picture, it will crashed.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View claims = inflater.inflate(R.layout.camera_main, container, false);
b=(Button)claims.findViewById(R.id.btnSelectPhoto);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
return claims;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(Claims.this.getActivity());
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity. RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
viewImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getActivity().getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image ", picturePath + "");
viewImage.setImageBitmap(thumbnail);
}
}
}
}
LogCat Error
java.lang.RuntimeException: Failure delivering result ResultInfo{who=android:fragment:0, request=2, result=-1, data=Intent { dat=content://com.sec.android.gallery3d.provider/picasa/item/5843197728949359042 (has extras) }} to activity {com.example.project.project/com.example.project.project.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3752)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3795)
Can someone explain to me why would this happen and how to fix it?
Thanks a lot :)
you can using this method
public class MainActivity extends AppCompatActivity {
private static final int IMAGE_REQUEST_CODE = 1;
private static final int CAMERA_REQUEST_CODE = 2;
private static final String IMG_FILE_NAME = "tempImg";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// From Gallery
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), IMAGE_REQUEST_CODE);
// Take a Picture
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = Uri.fromFile(GetOutputMediaFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
public static File GetOutputMediaFile() {
// External sdcard location
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory() + "/" + HConstants.IMG_FILE_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
// Create a media file name
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ IMG_FILE_NAME + ".jpg");
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
if(requestCode == IMAGE_REQUEST_CODE){
fileUri = data.getData();
Log.i(getClass().getName(), "fileUri" + fileUri);
}else{
Log.i(getClass().getName(), fileUri);
}
}
}
}
Getting Image from Gallery.
Try the following code.Hopefully it will work
public class ImageGalleryDemoActivity extends Activity {
private static int RESULT_LOAD_IMAGE = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
Taking Picture
public class CameraDemoActivity extends Activity {
int TAKE_PHOTO_CODE = 0;
public static int count=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//here,we are making a folder named picFolder to store pics taken by the camera using this application
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
File newdir = new File(dir);
newdir.mkdirs();
Button capture = (Button) findViewById(R.id.btnCapture);
capture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// here,counter will be incremented each time,and the picture taken by camera will be stored as 1.jpg,2.jpg and likewise.
count++;
String file = dir+count+".jpg";
File newfile = new File(file);
try {
newfile.createNewFile();
} catch (IOException e) {}
Uri outputFileUri = Uri.fromFile(newfile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
Log.d("CameraDemo", "Pic saved");
}
}
}
Also add the permissions in Manifest File:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

java.net.MalformedURLException trying to retrieve a photo saved on my Android device

I am trying to add in my App a function to use the camera to store photos in my device.
At the beginning i use the camera like this:
mButtonCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count++;
String file = dir+prova+".jpg";
File newFile = new File(file);
try {
newFile.createNewFile();
}catch (IOException e){}
Uri outputFileUri = Uri.fromFile(newFile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,outputFileUri);
Log.v("CameraDemo", "Pic savedNO");
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
}
});
And then for the OnActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
Log.v("CameraDemo", "Pic saved");
Log.v("Salva Foto", dir+prova+".jpg");
myDBHandler.addPhoto(prova,dir+prova+".jpg");
}
}
Until here evrything is ok but when I try to retrieve the photo using this:
InputStream URLcontent = null;
try {
URLcontent = (InputStream) new URL(fotoSI).getContent();
} catch (IOException e) {
e.printStackTrace();
}
Drawable image = Drawable.createFromStream(URLcontent, fotoSI);
mImageCamera.setImageDrawable(image);
It doesn´t return any photo that is what the Log says me:
java.net.MalformedURLException: Protocol not found: /storage/emulated/0/Pictures/
I am trying everything but without results.

startActivityForResult vs OnRestart (bundle or read from file)

Main Java Activity:
TList tl = new TList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
}
public void AddmyCostumObj_buttonclik(View view) {
Intent intent = new Intent(this, AddActivity.class);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
Bundle T = data.getExtras();
String new_myCostumObj_s = myCostumObj.myCostumObj_getString("ret");
myCostumObj new1 = new myCostumObj();
new1.string_to_myCostumObj(new_myCostumObj_s);
tl.add_myCostumObj(new1);
}
}
#Override
protected void onStart() {
super.onStart();
FileInputStream fis;
try {
fis = openFileInput("data_tasks");
ObjectInputStream ois = new ObjectInputStream(fis);
tl = (TList) ois.readObject();
if (tl == null) tl = new TList(); // it sometimes gave nullPointer
ois.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
FileOutputStream fos;
try {
fos = openFileOutput("data_tasks", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(tl);
oos.flush();
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
}
Add Java Activity:
// creates a new myCostumObj
public void add_buttonclick(View view){
Intent intent = new Intent();
Bundle T = new Bundle();
T.putString("ret", myCostumObj.myCostumObj_toString());
intent.putExtras(T);
setResult(RESULT_OK, intent);
finish();
}
What does the main activity do first on restart? Does it do the expected thing and read form the file the tl and than add the myCostumObj from the bundle? If so, than what am I doing wrong, because the tl is always appearing empty.

Categories

Resources