How to get Audio path from listview - java

I am creating mp3 player unable to get audio path URI using media.uri.data is not working please help me how get path audio file path?
Here is my code. I am searching lot but did not found the answer media.uri.data is return null what should do?I am unable stuck only in this step help?
package com.monstertechno.musicplayerappui;
import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.renderscript.Sampler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;
import com.sothree.slidinguppanel.SlidingUpPanelLayout.PanelState;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;
private ArrayList<Song> songList;
private ListView songView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
runtimpermission();
songView = (ListView) findViewById(R.id.song_list);
songList = new ArrayList<Song>();
SongAdapter songAdt = new SongAdapter(this, songList);
songView.setAdapter(songAdt);
getSongList();
Collections.sort(songList, new Comparator<Song>() {
public int compare(Song a, Song b) {
return a.getTitle().compareTo(b.getTitle());
}
});
songView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(mediaPlayer!=null){
mediaPlayer.release();
}
}
});
}
public void runtimpermission(){
Dexter.withActivity(this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override public void onPermissionGranted(PermissionGrantedResponse response) {
Toast.makeText(MainActivity.this, "Permisson Access", Toast.LENGTH_SHORT).show();
}
#Override public void onPermissionDenied(PermissionDeniedResponse response) {
Toast.makeText(MainActivity.this, "Permisson Denied", Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
token.continuePermissionRequest();}
}).check();
}
public void getSongList() {
//retrieve song info
ContentResolver musicResolver = getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
if(musicCursor!=null && musicCursor.moveToFirst()){
//get columns
int titleColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ARTIST);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
songList.add(new Song(thisId, thisTitle, thisArtist));
}
while (musicCursor.moveToNext());
}
}
}

Okay you were'nt clear enough,I add a complete code in case any body needs it you only need one line of it though:
Cursor cur = cr.query(uri, null, selection, null, sortOrder);
int count = 0;
if (cur != null) {
count = cur.getCount();
if (count > 0) {
while (cur.moveToNext()) {
String album = (cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.ALBUM)));
String artist = (cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.ARTIST)));
String title =(cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.TITLE)));
String path = (cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.DATA)));
String alumbId =(cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)));
long duration = (cur.getLong(cur.getColumnIndex(MediaStore.Audio.Media.DURATION)));
Cursor cursorImage = getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, new String[] {MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM_ART}, MediaStore.Audio.Albums._ID+ "=?", new String[] {String.valueOf(alumbId)}, null);
assert cursorImage != null;
if (cursorImage.moveToFirst()) {
String imagePath = cursorImage.getString(cursorImage.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART));
}
}
}
}
cur.close();
It works I just tested it.Just check for null for imagePath.

Related

Android Studio Login with SQLite database

Currently I am developing a personal software that is able to use the database to store the registered accounts and when logging in will retrieve the data from the database to compare with the characters been entered by the user.
But for some reason, even though I entered it correctly, I can't log in successfully
This is SQLite java file
package anhtuan.example.sample.SQLite;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class SQLite extends SQLiteOpenHelper {
public SQLite(#Nullable Context context) {
super(context, "System", null, 1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String account = "create table accounts " +
"(" +
"_id integer primary key autoincrement, " +
"user text," +
"password text" +
")";
sqLiteDatabase.execSQL(account);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("drop table if exists accounts");
onCreate(sqLiteDatabase);
}
}
Here are DAO java file
package anhtuan.example.sample.DAO;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;
import java.util.ArrayList;
import anhtuan.example.sample.Log.SignUp;
import anhtuan.example.sample.Model.AccountModel;
import anhtuan.example.sample.SQLite.SQLite;
public class DAO {
SQLite sqLite;
ArrayList<AccountModel> ds = new ArrayList<>();
public DAO(Context context) {
sqLite = new SQLite(context);
}
public void addUser(String acc, String pass) {
SQLiteDatabase sqLiteDatabase = sqLite.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("user",acc);
values.put("password",pass);
sqLiteDatabase.insert("accounts", null, values);
}
public ArrayList<AccountModel> getDSAccount(){
SQLiteDatabase sqLiteDatabase = sqLite.getReadableDatabase();
Cursor c = sqLiteDatabase.rawQuery("select * from accounts", null);
if(c.getCount()>0){
c.moveToFirst();
do {
ds.add(new AccountModel(c.getString(1),c.getString(2)));
}while (c.moveToNext());
}
return ds;
}
public boolean checkLogin(Context context,String users,String passwords){
ds = getDSAccount();
for(int i = 0; i < ds.size();i++){
if(ds.get(i).getUser().equals(users)){
if(passwords.equals(ds.get(i).getPassword())){
return true;
}
}
};
return false;
}
public boolean changePass(String user,String password){
return true;
}
}
And lastly the signin java file
package anhtuan.example.sample.Log;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.textfield.TextInputEditText;
import java.util.ArrayList;
import anhtuan.example.sample.DAO.DAO;
import anhtuan.example.sample.Home;
import anhtuan.example.sample.Model.AccountModel;
import anhtuan.example.sample.R;
public class SignIn extends AppCompatActivity {
TextInputEditText user,pass;
TextView signup;
Button Login;
DAO dao;
ArrayList<AccountModel> ds;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
setTitle("Sign In");
user = findViewById(R.id.SIuser);
pass = findViewById(R.id.SIpass);
Login = findViewById(R.id.SIbtn);
signup = findViewById(R.id.SItv);
dao = new DAO(this);
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(SignIn.this,ForgotPass.class);
startActivity(i);
}
});
String Loginuser = user.getText().toString();
String Loginpasse = pass.getText().toString();
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(user.getText().length() == 0 || pass.getText().length() == 0){
AlertDialog.Builder builder = new AlertDialog.Builder(SignIn.this);
builder.setTitle("You haven't insert all the blank");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.show();
}else{
if(dao.checkLogin(SignIn.this,Loginuser,Loginpasse)){
Intent i = new Intent(SignIn.this,Home.class);
startActivity(i);
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(SignIn.this);
builder.setTitle("Check again !");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.show();
}
}
}
});
}
}
I had try to use contain and indexOf with arrayList to find the data without using for loop but it always come out false so i decide to use for loop again.

How to get the selected item's ID from dropdown and send to sqlite android?

I have an Autocomplete textview list where I am populating data from SQLite. When I am selecting one name from the list I want to get the ID/primary key of that particular name and then insert it to the database when a button is clicked. How do I do that?
This is my code by which I am populating data in the Autocomplete text view.
package com.example.user.paperflyv0;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class NewOrder extends AppCompatActivity {
String[] executive_num_list;
public static final String MERCHANT_NAME = "Merchant Name";
private String EXECUTIVE_URL = "http://paperflybd.com/executiveList.php";
private String INSERT_URL = "http://192.168.0.117/new/insertassign.php";
//private String MERCHANT_URL= "http://192.168.0.117/new/merchantlistt.php";
private String MERCHANT_URL = "http://paperflybd.com/merchantAPI.php";
private AssignExecutiveAdapter assignExecutiveAdapter;
List<AssignManager_ExecutiveList> executiveLists;
List<AssignManager_Model> assignManager_modelList;
Database database;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_order);
database = new Database(getApplicationContext());
database.getWritableDatabase();
executiveLists = new ArrayList<>();
assignManager_modelList = new ArrayList<>();
//Fetching email from shared preferences
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
String username = sharedPreferences.getString(Config.EMAIL_SHARED_PREF, "Not Available");
String user = username.toString();
getallmerchant();
getallexecutives();
final AutoCompleteTextView actv_m_name = findViewById(R.id.auto_m_name);
final AutoCompleteTextView actv_exe_name = findViewById(R.id.auto_exe_name);
final EditText count = findViewById(R.id.editText);
button = findViewById(R.id.btn_assign);
List<String> merchantnames = new ArrayList<String>();
List<String> executivenames = new ArrayList<String>();
for (int z = 0; z < assignManager_modelList.size(); z++) {
merchantnames.add(assignManager_modelList.get(z).getM_names());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(NewOrder.this,
android.R.layout.simple_list_item_1, merchantnames);
/* adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);*/
actv_m_name.setAdapter(adapter);
for (int k = 0; k < executiveLists.size(); k++) {
executivenames.add(executiveLists.get(k).getExecutive_name());
}
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(NewOrder.this,
android.R.layout.simple_list_item_1, executivenames);
/* adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);*/
actv_exe_name.setAdapter(adapter1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
database.insertneworder(actv_m_name.getText().toString(),actv_exe_name.getText().toString(),count.getText().toString());
}
});
}
private void getallmerchant() {
try {
SQLiteDatabase sqLiteDatabase = database.getReadableDatabase();
Cursor c = database.get_merchantlist(sqLiteDatabase);
while (c.moveToNext()) {
String merchantName = c.getString(0);
String merchantCode = c.getString(1);
String assigned = c.getString(2);
AssignManager_Model todaySummary = new AssignManager_Model(merchantName, merchantCode, assigned);
assignManager_modelList.add(todaySummary);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void getallexecutives() {
try {
SQLiteDatabase sqLiteDatabase = database.getReadableDatabase();
Cursor c = database.get_executivelist(sqLiteDatabase);
while (c.moveToNext()) {
String empName = c.getString(0);
String empCode = c.getString(1);
AssignManager_ExecutiveList assignManager_executiveList = new AssignManager_ExecutiveList(empName, empCode);
executiveLists.add(assignManager_executiveList);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
override the onItemClick method and check as follows
#Override
public void onItemClick(AdapterView<?> av, View view, int pos,long arg3) {
String selectedText = (String) av.getItemAtPosition(pos);
//or av.getAdapter().getItem(pos);
}
When working with SQLiteDatabase, it is best to use SQLiteOpenHelper class.
package com.homemedia.home.stackanswers;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "homemedia.db";
public DBHelper(Context context){
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
//create your tables here
}
public void addValues(String values){
//now get writable db here
SQLiteDatabase db = this.getWritableDatabase();
//Use content values to enable you enter the values to db
ContentValues cvalues = new ContentValues();
cvalues.put("name", values);
db.insert("tablenamehere", null, cvalues);
//
}
public ArrayList<String> getValues(String queryCriteria){
//now get readable db here
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> itemValues = new ArrayList<>();
//use cursor to query db
Cursor cursor = db.rawQuery("Select * from tablename", null);
cursor .moveToFirst(); //moves to 1st positon
//goes through all items
while (!cursor.isAfterLast()){
// get particular values here and add to arraylist
itemValues.add(cursor.getString(cursor.getColumnIndex("columnin table")));
cursor.moveToNext();
}
cursor.close();
return itemValues; //if you need int values, put int ArrayList<int>
}
public ArrayList<Integer> empIDs(String criteria){
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<Integer> itemValues = new ArrayList<>();
//use cursor to query db
Cursor cursor = db.rawQuery("Select * from tablename WHERE columnValue = criteria ", null);
cursor .moveToFirst(); //moves to 1st positon
//goes through all items
while (!cursor.isAfterLast()){
// get particular values here and add to arraylist
itemValues.add(cursor.getInt(cursor.getColumnIndex("primarykey col")));
//if getting integer is difficult, get as string and convert to int
cursor.moveToNext();
}
cursor.close();
return itemValues;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Then in main Activity
public class MainActivity extends AppCompatActivity {
DBHelper mydb;
ArrayList<String> mylist;
ArrayList<Integer> myIDs;
Spinner myspinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb = new DBHelper(this);
myIDs = mydb.empIDs("search criteria");
mylist = mydb.getValues("search Criteria");
// to add info
mydb.addValues("value to be added");
myspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String stringId = String.valueOf(myIDs.get(position));
mydb.addValues(stringId);
}
I hope this works for you!

Uploading image from Android to Firebase always gives exception

I'm developing an app that accesses all the images in your device and automatically upload the images on Firebase Storage.
This is like whenever the activity starts, it automatically fetch image and upload without user's selection.
Main_Activity:
import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.FirebaseApp;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private Cursor cursor;
private int columnIndex;
GridView AllImages;
public int REQUEST_PERMISSIONS = 123;
Uri myUri;
ImageView img;
FirebaseApp firebaseApp;
FirebaseDatabase firebaseDatabase;
FirebaseStorage firebaseStorage;
StorageReference storageReference;
DatabaseReference databaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if ((ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) && (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
} else {
Log.e("Else", "Else");
}
img = (ImageView) findViewById(R.id.images);
ArrayList<String> arrayList = getImagesPath(this);
String a = arrayList.get(6);
Toast.makeText(getApplicationContext(), "" + a.toString(), Toast.LENGTH_LONG).show();
img.setImageURI(Uri.parse(new File(a).toString()));
myUri = Uri.parse(new File(c).toString());
firebaseApp = FirebaseApp.getInstance();
firebaseStorage = FirebaseStorage.getInstance(firebaseApp);
storageReference = firebaseStorage.getReference("Pictures");
StorageReference sRef = storageReference.child(Constants.STORAGE_PATH_UPLOADS + System.currentTimeMillis() + "." + getFileExtension(myUri));
sRef.putFile(myUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
Toast.makeText(getApplicationContext(), "Can't Upload ", Toast.LENGTH_LONG).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
// Setting progressDialog Title.
Toast.makeText(getApplicationContext(), "Uploading ", Toast.LENGTH_LONG).show();
}
});
String[] projection = {MediaStore.Images.Thumbnails._ID};
cursor = managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection, null, null, MediaStore.Images.Thumbnails._ID + "");
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
AllImages = (GridView) findViewById(R.id.GV_Images);
AllImageAdapter adapter = new AllImageAdapter(MainActivity.this, cursor, columnIndex);
AllImages.setAdapter(adapter);
}
public String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
public static ArrayList<String> getImagesPath(Activity activity) {
Uri uri;
ArrayList<String> listOfAllImages = new ArrayList<String>();
Cursor cursor;
int column_index_data, column_index_folder_name;
String PathOfImage = null;
uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = { MediaStore.MediaColumns.DATA,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME };
cursor = activity.getContentResolver().query(uri, projection, null,
null, null);
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
while (cursor.moveToNext()) {
PathOfImage = cursor.getString(column_index_data);
listOfAllImages.add(PathOfImage);
}
return listOfAllImages;
}
}
Adapter Class:
public class AllImageAdapter extends BaseAdapter {
Context c;
Cursor cur;
ImageView imageView;
int columnIndex;
public AllImageAdapter(Context c, Cursor cur, int columnIndex)
{
this.c = c;
this.cur = cur;
this.columnIndex = columnIndex;
}
#Override
public int getCount() {
return cur.getCount();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Set The Image in Image View.
imageView = new ImageView(c);
cur.moveToPosition(position);
int imageID = cur.getInt(columnIndex);
imageView.setImageURI(Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID));
imageView.setLayoutParams(new GridView.LayoutParams(330, 330));
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setPadding(4, 4, 4, 4);
//convertView.setTag(imageView);
return imageView;
}
}
In (Main Activity), for a time being, I'm just picking one picture by myself that is on index 6, to check if it works or not.
And here's
my another class:
public class Constants {
public static final String STORAGE_PATH_UPLOADS = "uploads/";
//public static final String DATABASE_PATH_UPLOADS = "uploads";
}
I'm not using Database yet.
The problem that I'm facing is, whenever the program runs, it shows exception:
StorageException has occurred.
An unknown error occurred, please check the HTTP result code and inner exception for server response.
Code: -13000 HttpResult: 0
09-08 12:06:44.694 11024-11263/com.example.umairasher.picturestofirebase
E/StorageException: No content provider: received_1035650876484715.jpeg
java.io.FileNotFoundException: No content provider: received_1035650876484715.jpeg
at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1092)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:944)
at android.content.ContentResolver.openInputStream(ContentResolver.java:664)
at com.google.firebase.storage.UploadTask.<init>(Unknown Source)
at com.google.firebase.storage.StorageReference.putFile(Unknown Source)
at com.example.umairasher.picturestofirebase.MainActivity.onCreate(MainActivity.java:113)
at android.app.Activity.performCreate(Activity.java:6439)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2498)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2605)
at android.app.ActivityThread.access$1100(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:179)
at android.app.ActivityThread.main(ActivityThread.java:5730)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:681)
E/StorageException: No content provider: received_1035650876484715.jpeg
java.io.FileNotFoundException: No content provider: received_1035650876484715.jpeg
at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1092)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:944)
at android.content.ContentResolver.openInputStream(ContentResolver.java:664)
at com.google.firebase.storage.UploadTask.<init>(Unknown Source)
at com.google.firebase.storage.StorageReference.putFile(Unknown Source)
at com.example.umairasher.picturestofirebase.MainActivity.onCreate(MainActivity.java:113)
at android.app.Activity.performCreate(Activity.java:6439)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2498)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2605)
at android.app.ActivityThread.access$1100(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:179)
at android.app.ActivityThread.main(ActivityThread.java:5730)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:681)
Can anybody please help, I know I'm doing a mistake somewhere but just can't help it. Thanks in advance.

Event not saved in Calendar

I want to save an event in the calendar directly, without openning the calendar app. I have found that in some devices the event is not saved in calendar, but I am not getting any error in the logcat. This is the code that I am using,
ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues()
values.put(CalendarContract.Events.DTSTART, DateBuilder.getStartDayCalendar());
values.put(CalendarContract.Events.DTEND, DateBuilder.getEndDayCalendar());
values.put(CalendarContract.Events.TITLE, "Title");
values.put(CalendarContract.Events.DESCRIPTION, "description");
values.put(CalendarContract.Events.CALENDAR_ID, 1);
values.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
Does anyone know what is happening?
Thanks!
UPDATE
In same devices you need to set up the status,Events.STATUS, Events.STATUS_CONFIRMED, that was the problem
Find the solution :
Follow the steps it will create event directly :
Manifest.xml
Add permissions in Manifest
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
<uses-permission android:name="android.permission.READ_CALENDAR" />
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="testpreference.com.testcalendar.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Calendars" />
<Spinner
android:id="#+id/calendarid_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/newevent_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Event"
android:layout_gravity="center_horizontal"
/>
</LinearLayout>
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Spinner calendarIdSpinner;
private Hashtable<String,String> calendarIdTable;
private Button newEventButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
calendarIdSpinner = (Spinner) findViewById(R.id.calendarid_spinner);
newEventButton = (Button) findViewById(R.id.newevent_button);
newEventButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (CalendarHelper.haveCalendarReadWritePermissions(MainActivity.this))
{
addNewEvent();
}
else
{
CalendarHelper.requestCalendarReadWritePermission(MainActivity.this);
}
}
});
calendarIdSpinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
if (CalendarHelper.haveCalendarReadWritePermissions(this))
{
//Load calendars
calendarIdTable = CalendarHelper.listCalendarId(this);
updateCalendarIdSpinner();
}
}
private void updateCalendarIdSpinner()
{
if (calendarIdTable==null)
{
return;
}
List<String> list = new ArrayList<String>();
Enumeration e = calendarIdTable.keys();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
list.add(key);
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
calendarIdSpinner.setAdapter(dataAdapter);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode==CalendarHelper.CALENDARHELPER_PERMISSION_REQUEST_CODE)
{
if (CalendarHelper.haveCalendarReadWritePermissions(this))
{
Toast.makeText(this, (String)"Have Calendar Read/Write Permission.",
Toast.LENGTH_LONG).show();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
private void addNewEvent()
{
if (calendarIdTable==null)
{
Toast.makeText(this, (String)"No calendars found. Please ensure at least one google account has been added.",
Toast.LENGTH_LONG).show();
//Load calendars
calendarIdTable = CalendarHelper.listCalendarId(this);
updateCalendarIdSpinner();
return;
}
final long oneHour = 1000 * 60 * 60;
final long tenMinutes = 1000 * 60 * 10;
long oneHourFromNow = (new Date()).getTime() + oneHour;
long tenMinutesFromNow = (new Date()).getTime() + tenMinutes;
String calendarString = calendarIdSpinner.getSelectedItem().toString();
int calendar_id = Integer.parseInt(calendarIdTable.get(calendarString));
CalendarHelper.MakeNewCalendarEntry(this, "Test", "Add event", "Somewhere",tenMinutesFromNow,tenMinutesFromNow+oneHour,false,true,calendar_id,3);
}
}
Create class for calendar selection
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
private static final String TAG = "OnItemSelectedListener";
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
Log.v(TAG,"onNohingSelected() called.");
}
}
CalendarHelper.java
import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CalendarContract.Events;
import android.provider.CalendarContract.Reminders;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.TimeZone;
public class CalendarHelper {
//Remember to initialize this activityObj first, by calling initActivityObj(this) from
//your activity
private static final String TAG = "CalendarHelper";
public static final int CALENDARHELPER_PERMISSION_REQUEST_CODE = 99;
public static void MakeNewCalendarEntry(Activity caller,String title,String description,String location,long startTime,long endTime, boolean allDay,boolean hasAlarm, int calendarId,int selectedReminderValue) {
ContentResolver cr = caller.getContentResolver();
ContentValues values = new ContentValues();
values.put(Events.DTSTART, startTime);
values.put(Events.DTEND, endTime);
values.put(Events.TITLE, title);
values.put(Events.DESCRIPTION, description);
values.put(Events.CALENDAR_ID, calendarId);
values.put(Events.STATUS, Events.STATUS_CONFIRMED);
if (allDay)
{
values.put(Events.ALL_DAY, true);
}
if (hasAlarm)
{
values.put(Events.HAS_ALARM, true);
}
//Get current timezone
values.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
Log.i(TAG, "Timezone retrieved=>"+TimeZone.getDefault().getID());
Uri uri = cr.insert(Events.CONTENT_URI, values);
Log.i(TAG, "Uri returned=>"+uri.toString());
// get the event ID that is the last element in the Uri
long eventID = Long.parseLong(uri.getLastPathSegment());
if (hasAlarm)
{
ContentValues reminders = new ContentValues();
reminders.put(Reminders.EVENT_ID, eventID);
reminders.put(Reminders.METHOD, Reminders.METHOD_ALERT);
reminders.put(Reminders.MINUTES, selectedReminderValue);
Uri uri2 = cr.insert(Reminders.CONTENT_URI, reminders);
}
}
public static void requestCalendarReadWritePermission(Activity caller)
{
List<String> permissionList = new ArrayList<String>();
if (ContextCompat.checkSelfPermission(caller,Manifest.permission.WRITE_CALENDAR)!=PackageManager.PERMISSION_GRANTED)
{
permissionList.add(Manifest.permission.WRITE_CALENDAR);
}
if (ContextCompat.checkSelfPermission(caller,Manifest.permission.READ_CALENDAR)!=PackageManager.PERMISSION_GRANTED)
{
permissionList.add(Manifest.permission.READ_CALENDAR);
}
if (permissionList.size()>0)
{
String [] permissionArray = new String[permissionList.size()];
for (int i=0;i<permissionList.size();i++)
{
permissionArray[i] = permissionList.get(i);
}
ActivityCompat.requestPermissions(caller,
permissionArray,
CALENDARHELPER_PERMISSION_REQUEST_CODE);
}
}
public static Hashtable listCalendarId(Context c) {
if (haveCalendarReadWritePermissions((Activity)c)) {
String projection[] = {"_id", "calendar_displayName"};
Uri calendars;
calendars = Uri.parse("content://com.android.calendar/calendars");
ContentResolver contentResolver = c.getContentResolver();
Cursor managedCursor = contentResolver.query(calendars, projection, null, null, null);
if (managedCursor.moveToFirst())
{
String calName;
String calID;
int cont = 0;
int nameCol = managedCursor.getColumnIndex(projection[1]);
int idCol = managedCursor.getColumnIndex(projection[0]);
Hashtable<String,String> calendarIdTable = new Hashtable<>();
do
{
calName = managedCursor.getString(nameCol);
calID = managedCursor.getString(idCol);
Log.v(TAG, "CalendarName:" + calName + " ,id:" + calID);
calendarIdTable.put(calName,calID);
cont++;
} while (managedCursor.moveToNext());
managedCursor.close();
return calendarIdTable;
}
}
return null;
}
public static boolean haveCalendarReadWritePermissions(Activity caller)
{
int permissionCheck = ContextCompat.checkSelfPermission(caller,
Manifest.permission.READ_CALENDAR);
if (permissionCheck== PackageManager.PERMISSION_GRANTED)
{
permissionCheck = ContextCompat.checkSelfPermission(caller,
Manifest.permission.WRITE_CALENDAR);
if (permissionCheck== PackageManager.PERMISSION_GRANTED)
{
return true;
}
}
return false;
}
}

logcat file showing errors

package com.example.ishan.complainbox;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.AppCompatImageButton;
import android.view.View;
import android.widget.EditText;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import android.support.v7.widget.AppCompatImageView;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.graphics.drawable.BitmapDrawable;
public class Crime extends MainActivity implements
View.OnClickListener,LocationListener {
GoogleMap googleMap;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private Button btnSelect;
private ImageView imgView,ivImage;
private String userChosenTask;
EditText street, city, pincode, detail;
Button btnsave;
crimeDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!isGooglePlayServicesAvailable()) {
finish();
setContentView(R.layout.activity_crime);
// Get References of Views
street = (EditText) findViewById(R.id.str);
city = (EditText) findViewById(R.id.city);
pincode = (EditText) findViewById(R.id.pin);
detail = (EditText) findViewById(R.id.detail);
imgView = (ImageView)findViewById(R.id.imgView);
btnsave = (Button) findViewById(R.id.save);
btnSelect = (Button) findViewById(R.id.uploadpic);
dbHandler = new crimeDBHandler(this, null, null, 1);
btnSelect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String strt = street.getText().toString();
String cty = city.getText().toString();
String pin = pincode.getText().toString();
String det = detail.getText().toString();
Bitmap bitmap =
((BitmapDrawable)imageView.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageInByte = baos.toByteArray();
btnsave = (Button) findViewById(R.id.save);
selectImage();
dbHandler.insertEntry(strt, cty, pin, det,imageInByte);
Toast.makeText(getApplicationContext(), "Complaint
Successfully Filed ", Toast.LENGTH_LONG).show();
}
});
ivImage = (ImageView) findViewById(R.id.img);
}
}
#Override
public void onRequestPermissionsResult ( int requestCode, String[]
permissions,
int[] grantResults){
switch (requestCode) {
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
if (userChosenTask.equals("Take Photo"))
cameraIntent();
else if (userChosenTask.equals("Choose from Library"))
galleryIntent();
} else
break;
}
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
private void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(Crime.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=userChosenTask.checkPermission(Crime.this);
if (items[item].equals("Take Photo"))
{
userChosenTask ="Take Photo";
if(result)
cameraIntent();
}
else if (items[item].equals("Choose from Library"))
{
userChosenTask ="Choose from Library";
if(result)
galleryIntent();
}
else if (items[item].equals("Cancel"))
{
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select
File"),SELECT_FILE);
}
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent
data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new
File(Environment.getExternalStorageDirectory(),System.currentTimeMillis()
+ ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
ivImage.setImageBitmap(thumbnail);
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm =
MediaStore.Images.Media.getBitmap
(getApplicationContext().getContentResolver(), data.getData());
}
catch (IOException e) {
e.printStackTrace();
}
}
ivImage.setImageBitmap(bm);
}
#Override
public void onLocationChanged(Location location) {
TextView locationTv = (TextView) findViewById(R.id.latlongLocation);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLng));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
This is one activity class of my android project and this activity depends on another utility class....which is mentioned below:
The statement Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap(); shows an error in "imageView" and the statement boolean result=userChosenTask.checkPermission(Crime.this); shows an error on "checkPermission"...but I don't understand why...because checkPermission is already defined in the utility class....
package com.example.ishan.complainbox;
/**
* Created by ishan on 11/04/2017.
*/
import android.os.Build;
import android.content.Context;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.Manifest;
import android.content.pm.PackageManager;
import android.content.DialogInterface;
public class Utility {
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkPermission(final Context context)
{
int currentAPIVersion = Build.VERSION.SDK_INT;
if(currentAPIVersion>=android.os.Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED)
{
if
(ActivityCompat.shouldShowRequestPermissionRationale((MainActivity) context,
Manifest.permission.READ_EXTERNAL_STORAGE))
{
AlertDialog.Builder alertBuilder = new
AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("External storage permission is
necessary");
alertBuilder.setPositiveButton(android.R.string.yes, new
DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((MainActivity)
context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else
{
ActivityCompat.requestPermissions((MainActivity) context,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
return false;
} else {
return true;
}
} else
{
return true;
}
}
}
In your manifests.xml, you need to include permission:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Categories

Resources