So I am populating my Bitmap ArrayList (photos) by adding images through gallery and camera photos and then saves the array of names into database and images into the storage. In the ImageAdapter class if I remove an image from the array list then without saving the list it successfully removes the image from the storage but if I click the save button then it did not remove the image from my internal phone storage as my Bitmap ArrayList (photos) does not update. How can I update my Arraylist of Bitmap in the main class (fragment) before saving?
Save function
public void saveNotes() {
if (!Modify) {
if (titulo.getText().toString().length() > 0) {
if (!base.buscarNota(titulo.getText().toString())) {
String almostSameText = Html.toHtml(texto.getEditableText()).toString();
if (bp != null) {
Util.saveToInternalStorage(context, bp, ArrayImageName, photos);
Notas notas = new Notas(titulo.getText().toString().trim(), almostSameText, getFecha(), stringForArray);
base.insertarNota(notas);
} else {
Notas notas = new Notas(titulo.getText().toString().trim(), almostSameText, getFecha(), null);
base.insertarNota(notas);
}
getActivity().onBackPressed();
} else {
Alerta alerta = new Alerta(context, context.getResources().getString(R.string.title_existente));
}
} else {
Alerta alerta = new Alerta(context, context.getResources().getString(R.string.title_vacio));
}
} else {
String almostSameText = Html.toHtml(texto.getEditableText()).toString();
if (bp != null) {
Util.saveToInternalStorage(context, bp, ArrayImageName, photos);
base.modificarNota(titulo.getText().toString().trim(), almostSameText, stringForArray, id);
} else {
base.modificarNota(titulo.getText().toString().trim(), almostSameText, null, id);
}
getActivity().onBackPressed();
getActivity().overridePendingTransition(R.anim.enter_from_left, R.anim.exit_from_right);
}
}
my ImageAdapter Delete bitmap class
public void showDeletePictureDialog(){
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(Imagecontext);
} else {
builder = new AlertDialog.Builder(Imagecontext);
}
builder.setTitle("Delete photo")
.setMessage("Are you sure you want to delete this photo?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
ImageFileArrayAfterDelete = EditorFragment.loadImageStrings;
String folder_main = "MyImages";
File f = new File(Environment.getExternalStorageDirectory().toString(), folder_main);
z = new File(f.toString(), Uri.parse(String.valueOf(ImageFileArrayAfterDelete.get(currentPosition))) + ".jpg");
ImageName = z.getName();
Log.d("TAG_", "Position is: " + currentPosition + " File name is: " + ImageName);
bpAdapter.remove(currentPosition);
ImageFileArrayAfterDelete.remove(currentPosition);
toSingleString();
notifyItemRemoved(currentPosition);
notifyItemRangeChanged(currentPosition, bpAdapter.size());
z.delete();
}
})
You can achieve this just by doing this after deleting the item from your list
myList.removeAt(position)
myAdapter.notifyDataSetChanged()
Related
I need to access the specific folder depending on the name of the created project. In Main_Activity the name of this project is filled and new folder is created. Thus, Camera_Activity saves the photos taken in that folder. Next I access Gallery_Activity, but it never goes to the folder of the created project. How can I access to that folder?
An example: Name of the created folder: Proj_1, but user select the photos from another one that opens by default, the uri that comes out is:
content://com.android.externalstorage.documents/document/primary%3APictures%2FCaptures_Camera2%2FProj_aa%2Fpic_040621_110254.jpeg
Part of AndroidManifest.xml
...
<uses-feature android:name="android.hardware.camera2.full" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
...
MainActivity.java
...
createNewProject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Coge el nombre de EditText, crea nueva carpeta y empieza la captura de las imagenes
if(newName.getText().toString().isEmpty()){
Toast.makeText(getApplicationContext(), "Please, fill in the field.", Toast.LENGTH_LONG).show();
} else {
name = newName.getText().toString();
GlobalVariables.ProjectName = name;
Intent intent = new Intent(MainActivity.this, Camera_Activity.class);
startActivity(intent);
}
}
});
...
Camera_Activity.java takes the necessary photos, saves them and has a button to enter the gallery:
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
mTextureView = findViewById(R.id.camera_preview);
btn_take_pic = findViewById(R.id.button_take_photo);
acceptButton = findViewById(R.id.btn_ok);
cancelButton = findViewById(R.id.btn_cancel);
btn_gallery = findViewById(R.id.go_to_gallery);
imagePreview = findViewById(R.id.image_view_photo_preview);
...
// File name to save the picture
// First is getting the new project name from previous Activity:
String newProjName = GlobalVariables.ProjectName;
// Creating part of the name for image: timestamp. That will be: pic_tamestamp.jpeg
#SuppressLint("SimpleDateFormat") String timestamp = new SimpleDateFormat("ddMMyy_HHmmss").format(new Date());
directory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Captures_Camera2/Proj_" + newProjName);
GlobalVariables.MyDirectoryPath = directory.getPath();
if (!directory.exists() || !directory.isDirectory())
directory.mkdirs();
mFile = new File(directory, "pic_" + timestamp + ".jpeg");
pathToFile = mFile.getPath();
....
// ------------ GO TO GALLERY ---------
btn_gallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "You are going to Gallery...");
Intent GalleryIntent = new Intent(context, Gallery_Activity.class);
startActivity(GalleryIntent);
}
});
// ------------ SAVE PHOTO TO THE GALLERY ---------
acceptButton.setOnClickListener(new View.OnClickListener() {//26
#Override
public void onClick(View v) {
Toast.makeText(context, "Image saved to " + pathToFile, Toast.LENGTH_LONG).show();
// Recreating the activity with a new instance
recreate();
}
});
...
Gallery_Activity.java
public class Gallery_Activity extends AppCompatActivity implements View.OnClickListener, View.OnLongClickListener {
private static final String TAG = "GalleryActivity";
private final Context context = this;
private ImageView imageView1, imageView2;
private final int CODE_IMAGE_GALLERY_FIRST = 1;
private final int CODE_IMAGE_GALLERY_SECOND = 2;
private final int CODE_MULTIPLE_IMAGES_GALLERY = 3;
// Variables to check the name
private String directoryPath;
private String MyPath1 = null;
private String MyPath2 = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Keeping the screen on even when there is no touch interaction
final Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_gallery);
imageView1 = findViewById(R.id.imageView1);
// If you make a short click in the ImageView, you can choose only one image, if it is long click, you can choose two images
imageView1.setOnClickListener(this);
imageView1.setOnLongClickListener(this);
imageView2 = findViewById(R.id.imageView2);
imageView2.setOnClickListener(this);
imageView2.setOnLongClickListener(this);
directoryPath = GlobalVariables.MyDirectoryPath;
Log.d(TAG, " The path from Camera_Activity is: " + directoryPath); // /storage/emulated/0/Pictures/Captures_Camera2/Proj_*
chooseMultipleImages();
}
private void chooseMultipleImages() {
// TODO: here it does NOT enter the giving folder although using the path
startActivityForResult(Intent.createChooser(new Intent()
.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
.setAction(Intent.ACTION_GET_CONTENT)
.setType("image/*")
,"Selecting two images.."), CODE_MULTIPLE_IMAGES_GALLERY);
}
....
public void processImages(View view) {
//Toast.makeText(context, "Going to detect features...", Toast.LENGTH_SHORT).show();
Intent processIntent = new Intent(context, ImageProcessing.class);
startActivity(processIntent);
finish();
}
#Override
public boolean onLongClick(View v) {
recreate();
return false;
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.imageView1){
startActivityForResult(Intent.createChooser(new Intent()
.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)
.setAction(Intent.ACTION_GET_CONTENT)
.setType("image/*")
,"Selecting first image.."), CODE_IMAGE_GALLERY_FIRST);
}
else if(v.getId() == R.id.imageView2){
startActivityForResult(Intent.createChooser(new Intent()
.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)
.setAction(Intent.ACTION_GET_CONTENT)
.setType("image/*")
,"Selecting second image.."), CODE_IMAGE_GALLERY_SECOND);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ContentResolver resolver = this.getContentResolver();
// Get data from the folder
assert data != null;
Uri MyData = data.getData(); // for simple image
ClipData MultiImg = data.getClipData(); // for multiple images
GlobalVariables.countImg = MultiImg.getItemCount();
/* ******************************************
To pick multiples images from Gallery
******************************************
*/
if (requestCode == CODE_MULTIPLE_IMAGES_GALLERY && resultCode == RESULT_OK ){
/*
// TODO: For multiple images, more than 2 change this
int count = data.getClipData().getItemCount(); //evaluate the count before the for loop --- otherwise, the count is evaluated every loop.
for(int i = 0; i < count; i++)
Uri imageUri = data.getClipData().getItemAt(i).getUri();*/
// MultiImg != null was simplifyed since you cannot continue without any selection -> data never be null
if(GlobalVariables.countImg == 2){
// Getting name of the picture and print it
MyPath1 = MultiImg.getItemAt(0).getUri().toString();
MyPath2 = MultiImg.getItemAt(1).getUri().toString();
String Name1 = StringUtils.right(MyPath1,22);
String Name2 = StringUtils.right(MyPath2,22);
//String Proj_name = StringUtils.
GlobalVariables.PictureName1 = Name1;
GlobalVariables.PictureName2 = Name2;
Log.d(TAG, "--- First data name: " + StringUtils.right(MyPath1,22));
Log.d(TAG, "--- Second data name: " + StringUtils.right(MyPath2,22));
//Log.d(TAG, "Selected Items: " + clipData.getItemCount());
Log.d(TAG, "The full path is: " + MultiImg.getItemAt(0).getUri().toString());
// Showing images in the imageView
imageView1.setImageURI(MultiImg.getItemAt(0).getUri());
imageView2.setImageURI(MultiImg.getItemAt(1).getUri());
} else if (MyData != null ){
Log.d(TAG, "Only one image selected..");
Toast.makeText(context, "You should select 2 images and not only one", Toast.LENGTH_LONG).show();
recreate();
}
// MultiImg != null was simplifyed since you cannot continue without any selection -> data never be null
else if (GlobalVariables.countImg > 2){
//Log.d(TAG, "More than two selected images...");
Toast.makeText(context, "You should select 2 images and not ..." + GlobalVariables.countImg, Toast.LENGTH_LONG).show();
recreate();
}
}
/* ******************************************
To pick only one image fom Gallery for
each of ImageView and check that they
are different.
******************************************
*/
// pick image to the imageView1
else if(requestCode == CODE_IMAGE_GALLERY_FIRST && resultCode == RESULT_OK && MyData != null){
MyPath1 = MyData.getPath();
//Log.d(TAG, "\n ******** imageView1 has an image: \n" + StringUtils.right(MyPaths1,22) + "\n imageView2 has an image: \n" + StringUtils.right(MyPaths2,22));
assert StringUtils.right(MyPath1, 22) != null;
if(StringUtils.right(MyPath1,22).equals(StringUtils.right(MyPath2,22))){
Toast.makeText(context, "The images have to be different. Choose other image." , Toast.LENGTH_LONG).show();
}
else{
GlobalVariables.PictureName1 = StringUtils.right(MyPath1,22);
imageView1.setImageURI(MyData);
}
}
// pick image to the imageView2
else if(requestCode == CODE_IMAGE_GALLERY_SECOND && resultCode == RESULT_OK && MyData != null) {
MyPath2 = MyData.getPath();
//Log.d(TAG, "\n ******** imageView1 has an image: \n" + StringUtils.right(MyPaths1,22) + "\n imageView1 has an image: \n" + StringUtils.right(MyPaths2,22));
if(StringUtils.right(MyPath1,22).equals(StringUtils.right(MyPath2,22))){
Toast.makeText(context, "The images have to be different. Choose other image." , Toast.LENGTH_LONG).show();
}
else{
GlobalVariables.PictureName2 = StringUtils.right(MyPath2,22);
imageView2.setImageURI(MyData);
}
}
}
....
}
Can someone advise me on how I can solve this problem?
It is clear that I could leave things as they are and tell the user to check the folder where he selects the photos. But I would like it to be something more fluid and intuitive.
Thanks in advance.
private ArrayList<File> m_list = new ArrayList<File>();
String folderpath = Environment.getExternalStorageDirectory()
+ File.separator + "folder_name/";
File dir = new File(folderpath);
m_list.clear();
if (dir.isDirectory()) {
File[] files = dir.listFiles();
for (File file : files) {
if (!file.getPath().contains("Not_Found"))
m_list.add(file);
}
}
In my project I download all the data of my project from a json.I download title and description as text and also download my icon and the file of games.
I can download them and also save in database and show in listview easily.
My QUESTION is about how to save that my file for game is beinng download or not?
I have two buttons. first is download button when user click it , it starts to download file.when download finish, my download button disappear and my play button appears.
I want to save this, when user for second time run the application,i save for example my second position downloaded before. and I have just my play button.
my database:
public class DatabaseHandler extends SQLiteOpenHelper {
public SQLiteDatabase sqLiteDatabase;
int tedad;
public DatabaseHandler(Context context) {
super(context, "EmployeeDatabase.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String tableEmp = "create table emp(PersianTitle text,Description text,icon text,downloadlink text,dl integer)";
db.execSQL(tableEmp);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void insertData(ArrayList<String> id, ArrayList<String> name, ArrayList<String> salary, ArrayList<String> roms,String
dl) {
int size = id.size();
tedad = size;
sqLiteDatabase = this.getWritableDatabase();
try {
for (int i = 0; i < size; i++) {
ContentValues values = new ContentValues();
values.put("PersianTitle", id.get(i));
values.put("Description", name.get(i));
values.put("icon", salary.get(i));
values.put("downloadlink", roms.get(i));
values.put("dl", "0");
sqLiteDatabase.insert("emp", null, values);
}
} catch (Exception e) {
Log.e("Problem", e + " ");
}
}
public ArrayList<String> Game_Info (int row, int field) {
String fetchdata = "select * from emp";
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
ArrayList<String> stringArrayList = new ArrayList<String>();
Cursor cu = sqLiteDatabase.rawQuery(fetchdata, null);
for (int i = 0; i < row + 1; i++) {
cu.moveToPosition(i);
String s = cu.getString(field);
stringArrayList.add(s);
}
return stringArrayList;
}
}
and this is my main code:
public class MainActivity2 extends Activity {
Boolean done_game = false;
ProgressDialog progressDialog;
private boolean _init = false;
ListView listView;
DatabaseHandler database;
BaseAdapter adapter;
public String path_image;
JSONObject jsonObject;
Game_Counter_Store Game_Counter_Store;
int game_counter_store;
ArrayList<String> name_array = new ArrayList<String>();
ArrayList<String> des_array = new ArrayList<String>();
ArrayList<String> icon_array = new ArrayList<String>();
ArrayList<String> roms_array = new ArrayList<String>();
ArrayList<String> fav_array = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main2);
init();
System.gc();
File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "MyDirName");//make a direction
path_image = mediaStorageDir.getAbsolutePath(); // here is tha path
listView = (ListView) findViewById(R.id.listView);
database = new DatabaseHandler(MainActivity2.this);
database.getWritableDatabase();
Game_Counter_Store = new Game_Counter_Store("Games_Number", this); // number of game in first run is 0
game_counter_store = Game_Counter_Store.get_count();
if (game_counter_store == 0) {
Log.i("mhs", "game_counter_store is 0");
DownloadGames();
} else {
Log.i("mhs", "there are some games");
for (int i = 0; i < game_counter_store; i++) {
name_array = database.Game_Info(i, 0);
des_array = database.Game_Info(i, 1);
icon_array = database.Game_Info(i, 2);
roms_array = database.Game_Info(i, 3);
fav_array = database.Game_Info(i, 4);
}
adapter = new MyBaseAdapter(MainActivity2.this, name_array, des_array, icon_array, roms_array,fav_array);
listView.setAdapter(adapter);
}
}
public void DownloadGames() {
//here we download name, des, icon
MakeDocCallBack makeDocCallBack = new MakeDocCallBack() {
#Override
public void onResult(ArrayList<String> res) {
if (res.size() > 0) {
try {
Game_Counter_Store counter_store = new Game_Counter_Store("Games_Number", MainActivity2.this); // get numbrr of games
counter_store.set_count(res.size()); // store the games number
for (int i = 0; i < res.size(); i++) {
jsonObject = new JSONObject(res.get(i)); //get all the jsons
//get all the data to store in database
name_array.add(jsonObject.getString("PersianTitle"));
des_array.add(jsonObject.getString("Description"));
icon_array.add(jsonObject.getString("icon"));
roms_array.add(jsonObject.getString("downloadlink"));
GetFile fd = new GetFile(MainActivity2.this, path_image, getFileName(jsonObject.getString("icon")), jsonObject.getString("icon").toString(), null); // download the image
GetFileCallBack Image_callback = new GetFileCallBack() {
#Override
public void onStart() {
// Toast.makeText(getApplicationContext(),"start",Toast.LENGTH_LONG).show();
}
#Override
public void onProgress(long l, long l1) {
// Toast.makeText(getApplicationContext(),"onProgress",Toast.LENGTH_LONG).show();
}
#Override
public void onSuccess() {
// Toast.makeText(getApplicationContext(),"YES",Toast.LENGTH_LONG).show();
}
#Override
public void onFailure() {
// Toast.makeText(getApplicationContext(),"NO",Toast.LENGTH_LONG).show();
}
};
if (!fd.DoesFileExist()) {
fd.Start(Image_callback); // get the data
}
//set data in adapter to show in listview
adapter = new MyBaseAdapter(MainActivity2.this, name_array, des_array, icon_array, roms_array,fav_array);
listView.setAdapter(adapter);
}
//store dada in database (name , des , icon , bin file(roms) , state)
database.insertData(name_array, des_array, icon_array, roms_array,"0");
} catch (Exception ex) {
}
}
}
};
DocMaker doc = new DocMaker();
doc.set(this, makeDocCallBack);
}
public static String getFileName(String url) {
String temp = url.substring(url.lastIndexOf('/') + 1, url.length());
if (temp.contains("?"))
temp = temp.substring(0, temp.indexOf("?"));
return temp;
}
public class MyBaseAdapter extends BaseAdapter {
private Activity activity;
private ArrayList title, desc, icon, roms,fav;
private LayoutInflater inflater = null;
public MyBaseAdapter(Activity a, ArrayList b, ArrayList c, ArrayList d, ArrayList e, ArrayList f) {
activity = a;
this.title = b;
this.desc = c;
this.icon = d;
this.roms = e;
this.fav=f;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return title.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.list_item, null);
TextView title2 = (TextView) vi.findViewById(R.id.game_name); // title
String song = title.get(position).toString();
title2.setText(song);
TextView title22 = (TextView) vi.findViewById(R.id.game_des); // desc
String song2 = desc.get(position).toString();
title22.setText(song2);
File imageFile = new File("/storage/emulated/0/MyDirName/" + getFileName(icon_array.get(position)));
ImageView imageView = (ImageView) vi.findViewById(R.id.icon); // icon
imageView.setImageBitmap(BitmapFactory.decodeFile(imageFile.getAbsolutePath()));
TextView title222 = (TextView) vi.findViewById(R.id.game_roms); // desc
String song22 = roms.get(position).toString();
title222.setText(song22);
final Button dl_btn = (Button) vi.findViewById(R.id.dl_btn); // desc
final Button run_btn = (Button) vi.findViewById(R.id.play_btn); // desc
run_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Preferences.DEFAULT_GAME_FILENAME = getFileName(roms_array.get(position));
Intent myIntent = new Intent(MainActivity2.this, FileChooser.class);
myIntent.putExtra(FileChooser.EXTRA_START_DIR, Preferences.getRomDir(MainActivity2.this));
Log.i("mhsnnn", Preferences.getTempDir(MainActivity2.this));
final int result = Preferences.MENU_ROM_SELECT;
startActivityForResult(myIntent, result);
}
});
dl_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MakeDocCallBack makeDocCallBack = new MakeDocCallBack() {
#Override
public void onResult(ArrayList<String> res) {
if (res.size() > 0) {
try {
jsonObject = new JSONObject(res.get(position));
roms_array.add(jsonObject.getString("downloadlink"));
GetFile fd1 = new GetFile(MainActivity2.this, path_image, getFileName(jsonObject.getString("downloadlink")), jsonObject.getString("downloadlink").toString(),null); //download the bin file
GetFileCallBack roms_callback = new GetFileCallBack() {
#Override
public void onStart() {
}
#Override
public void onProgress(long l, long l1) {
Log.i("nsr", "onProgress");
}
#Override
public void onSuccess() {
Log.i("nsr", "onSuccess");
dl_btn.setVisibility(View.GONE);
run_btn.setVisibility(View.VISIBLE);
}
#Override
public void onFailure() {
Log.i("nsr", "onFailure");
}
};
if (!fd1.DoesFileExist()) {
fd1.Start(roms_callback);
}
} catch (Exception ex) {
}
}
}
};
DocMaker doc = new DocMaker();
doc.set(MainActivity2.this, makeDocCallBack);
}
});
return vi;
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
private boolean verifyExternalStorage() {
// check for sd card first
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// rw access
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// r access
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// no access
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
// if we do not have storage warn user with dialog
if (!mExternalStorageAvailable || !mExternalStorageWriteable) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this)
.setTitle(getString(R.string.app_name) + " Error")
.setMessage("External Storage not mounted, are you in disk mode?")
.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
init();
}
})
.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
dialog.show();
return false;
}
return true;
}
private void init() {
if (verifyExternalStorage() && !_init) {
// always try and make application dirs
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
Log.i("nsrrr1", extStorageDirectory);
// /storage/emulated/0
File myNewFolder = new File(extStorageDirectory + Preferences.DEFAULT_DIR);
Log.i("nsrrr2", extStorageDirectory + Preferences.DEFAULT_DIR);///storage/emulated/0/sega
if (!myNewFolder.exists()) {
myNewFolder.mkdir();
}
myNewFolder = new File(extStorageDirectory + Preferences.DEFAULT_DIR_ROMS);
Log.i("nsrrr3", extStorageDirectory + Preferences.DEFAULT_DIR);///storage/emulated/0/sega
if (!myNewFolder.exists()) {
myNewFolder.mkdir();
}
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list(Preferences.DEFAULT_DIR_GAME);
Log.i("nsrrr3", files + "");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(Preferences.DEFAULT_DIR_GAME + "/" + filename);
File outFile = new File(myNewFolder, filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch (IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
// do first run welcome screen
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean firstRun = preferences.getBoolean(Preferences.PREF_FIRST_RUN, true);
if (firstRun) {
// remove first run flag
Editor edit = preferences.edit();
edit.putBoolean(Preferences.PREF_FIRST_RUN, false);
// default input
edit.putBoolean(Preferences.PREF_USE_DEFAULT_INPUT, true);
edit.commit();
}
// generate APK path for the native side
ApplicationInfo appInfo = null;
PackageManager packMgmr = this.getPackageManager();
try {
appInfo = packMgmr.getApplicationInfo(getString(R.string.package_name), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("Unable to locate assets, aborting...");
}
String _apkPath = appInfo.sourceDir;
// init the emulator
Emulator.init(_apkPath);
Log.i("rrrr", _apkPath);
// set the paths
Emulator.setPaths(extStorageDirectory + Preferences.DEFAULT_DIR,
extStorageDirectory + Preferences.DEFAULT_DIR_ROMS,
"",
"",
"");
// load up prefs now, never again unless they change
//PreferenceFacade.loadPrefs(this, getApplicationContext());
// load gui
// Log.d(LOG_TAG, "Done init()");
setContentView(R.layout.activity_main2);
// set title
super.setTitle(getString(R.string.app_name));
_init = true;
// Log.d(LOG_TAG, "Done onCreate()");
}
}
private void copyFile(InputStream in, OutputStream out) {
byte[] buffer = new byte[1024];
int read;
try {
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
how to make method in my database to do this?
If I understood you properly, you can add a table, user_games for example with User ID, Game ID and Status, then you can update status whenever an action is completed.
For example Status 1 for downloading, status 2 for Downloaded or Finished and you can even add statuses like download failed, to add a re-download button...
you can do something like
public void update_status(UserID,GameID) {
String update = "UPDATE games set status = 1 where id="+Game_ID+" and UserID = " + UserID);
db.rawQuery(update, null);
}
how can I solve this problem.
In the file explorer, when I hit a video file. something else appears in alertdialog. It theoretically should occur, the file pressed.
How can I solve?
Thank you.
I added 2 photos to better understand the error.
public class file_explorer_fragment extends ListFragment {
private List<String> item = null;
private List<String> path = null;
private String root;
private TextView myPath;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_file_explorer_fragment, container, false);
myPath = (TextView)v.findViewById(R.id.path);
root = Environment.getExternalStorageDirectory().getPath();
getDir(root);
return v;
}
private void getDir(String dirPath)
{
myPath.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if(!dirPath.equals(root))
{
item.add(root);
path.add(root);
item.add("../");
path.add(f.getParent());
}
for(int i=0; i < files.length; i++)
{
File file = files[i];
if(!file.isHidden() && file.canRead()) {
path.add(file.getPath());
if(file.isDirectory()){
item.add(file.getName() + "/");
}else{
if(isVideo(file)){
item.add(file.getName());
}
}
}
}
ArrayAdapter<String> fileList =
new ArrayAdapter<String>(getActivity(), R.layout.row_file_explorer, item);
setListAdapter(fileList);
}
public static boolean isVideo(File file){
//merge perfect codul asta
/*{
if (file.getName().toLowerCase().endsWith(".avi")) return true;
if (file.getName().toLowerCase().endsWith(".m3u8")) return true;
if (file.getName().toLowerCase().endsWith(".3gp")) return true;
if (file.getName().toLowerCase().endsWith(".mpg")) return true;
if (file.getName().toLowerCase().endsWith(".mp4")) return true;
return false;
}*/
String extension = "";
String filename = file.getName().toLowerCase();
int i = filename.lastIndexOf('.');
if (i >= 0) {
extension = filename.substring(i);
}
/* String ext = null;
String s = file.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1) {
ext = s.substring(i).toLowerCase();
}*/
switch (extension) {
case ".3gp":
case ".mpg":
case ".mpeg":
case ".mpe":
case ".mp4":
case ".avi":
case ".m3u8":
return true;
default:
return false;
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
File file = new File(path.get(position));
Context context = getActivity().getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, path.get(position), duration);
toast.show();
if (file.isDirectory())
{
if(file.canRead()){
getDir(path.get(position));
}else{
new android.app.AlertDialog.Builder(getActivity())
.setIcon(R.drawable.ic_folder_open_black_24dp)
.setTitle("[" + file.getName() + "] folder can't be read!")
.setPositiveButton("OK", null).show();
}
}else {
new android.app.AlertDialog.Builder(getActivity())
.setIcon(R.drawable.ic_folder_open_black_24dp)
.setTitle(file.getName())
.setPositiveButton("OK", null).show();
//Intent intent = new Intent(getActivity(), MainActivity.class);
//intent.putExtra("url", root+"/"+file.getName());
//startActivity(intent);
}
}
}
Photo from show 2 videos.
Photo 2 show alertdialog, and inside is wrong file.
I'm working on a school assignment which is to create a Bookmarking app with 2 activites, a ListActivity called BookNote and an activity called ManageActivity.
All typing must be done in ManageActivity and passed back to BookNote for list changes, reading, and writing data.
My problem is when I call the function "addBookmark" in BookNote activity. What I want to happen is for a new list item to be added at the end of the list with the bookmark objects info in it.
What is happening is that whatever item is at the end of the list is simply overwritten instead of a new item being created.
My code is below with comments stating my intentions of each function.
BookNote activity
public class BookNote extends ListActivity{
private ArrayAdapter<Bookmark> adapter;
private final String FILENAME = "bookmarks.txt";
public String title = "EMPTY", url = "EMPTY", note = "EMPTY";
public String bookmarkClicked ="";
public int listViewID = 0;
public boolean intentListener = false;
public int intentReturnCounter = 0;
public boolean addBookmarkClicked = false;
public ArrayList<Bookmark> bookmarkList;
/*When activity is called, list is populated by readData(), addBookmarkClicked is reset to false, intentLister is changed to true if returning from ManageActivity,
if intentListener is true, addBookmarkClicked will be changed to true if AddBookmark is clicked from the BookNote menubar, a bookmark object will be created with information
passed back from ManageActivity, and if addBookmarkClicked is true, the bookmark object will be added to the end of the list, otherwise it will be inserted in the same
list element from which was chosen to edit.*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bookmarkList = readData();
adapter = new ArrayAdapter<Bookmark>(this, android.R.layout.simple_list_item_1, bookmarkList);
setListAdapter(adapter);
addBookmarkClicked = false;
intentListener = false;
intentListener = getIntent().getBooleanExtra("listen", false);
if (intentListener == true) {
addBookmarkClicked = getIntent().getExtras().getBoolean("addBookmarkClicked", false);
title = getIntent().getExtras().getString("title");
url = getIntent().getExtras().getString("url");
note = getIntent().getExtras().getString("note");
listViewID = getIntent().getExtras().getInt("listViewID");
Bookmark bookmark = new Bookmark(title, url, note);
Toast.makeText(getApplicationContext(), "Intent return: True", Toast.LENGTH_SHORT).show();
intentListener = false;
if (addBookmarkClicked == true) {
addBookmark(bookmark);
Toast.makeText(getApplicationContext(), "Bookmark Added", Toast.LENGTH_SHORT).show();
addBookmarkClicked = false;
} else {
insertBookmark(bookmark, listViewID);
Toast.makeText(getApplicationContext(), "Bookmark Edited", Toast.LENGTH_SHORT).show();
}
//writeData();
}
}
//reads data when app runs and fills arrayadapter and list with items saved to bookmarks.txt
private ArrayList<Bookmark> readData(){
ArrayList<Bookmark> bookmarks = new ArrayList<>();
try {
FileInputStream fis = openFileInput(FILENAME);
Scanner scanner = new Scanner(fis);
if (scanner.hasNext()){
String titleScan = scanner.nextLine();
String urlScan = scanner.nextLine();
String noteScan = scanner.nextLine();
Bookmark bookmark = new Bookmark(titleScan, urlScan, noteScan);
bookmarks.add(bookmark);
}else{
Bookmark bookmark = new Bookmark("Example Title", "Example URL", "Example Note");
bookmarks.add(bookmark);
}
scanner.close();
} catch (FileNotFoundException e) {
}
return bookmarks;
}
private void writeData(){
try {
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fos);
BufferedWriter bw = new BufferedWriter(osw);
PrintWriter pw = new PrintWriter(bw);
for(int i = 0; i < adapter.getCount(); i++){
Bookmark bookmark = adapter.getItem(i);
pw.println(bookmark.getTitle() + "\n" + bookmark.getUrl() + "\n" + bookmark.getNote());
}
pw.close();
} catch (FileNotFoundException e) {
Log.e("Write ERR", "Cannot save: " + e.getMessage());
e.printStackTrace();
Toast.makeText(BookNote.this, "Error saving", Toast.LENGTH_SHORT).show();
}
}
//If addBookmark menu item is clicked, this will be called to add a bookmark to the end of the ArrayAdapter.
private void addBookmark(Bookmark bookmark){
adapter.add(bookmark);
writeData();
}
//Calls ManageActivity and reports information about app.
public void gotoManageActivity(boolean addBookmarkClicked){
Intent manageIntent = new Intent(this, ManageActivity.class);
Bundle extras = new Bundle();
extras.putString("bookmark", bookmarkClicked);
extras.putBoolean("addBookmarkClicked", addBookmarkClicked);
extras.putInt("listViewID", listViewID);
manageIntent.putExtras(extras);
startActivity(manageIntent);
}
#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_add) {
addBookmarkClicked = true;
gotoManageActivity(addBookmarkClicked);
return true;
}
return super.onOptionsItemSelected(item);
}
}
ManageActivity
public class ManageActivity extends AppCompatActivity {
private String title = "EMPTY", url = "EMPTY", note = "EMPTY";
private boolean listener = true;
private boolean addBookmarkClicked = false;
/* When activity starts, check for addBookmarkClicked status, create book */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.manage_layout);
addBookmarkClicked = getIntent().getExtras().getBoolean("addBookmarkClicked", false);
String bookmarkString = "";
bookmarkString = getIntent().getExtras().getString("bookmark");
if(bookmarkString != null && bookmarkString.length() > 0) {
if (bookmarkString.length() != 0) {
String[] stringArray = bookmarkString.split("\\n");
title = stringArray[0];
url = stringArray[1];
note = stringArray[2];
updateTextViews();
}
}
else { updateTextViews();
}
}
#Override
public void onBackPressed(){
Intent bookNoteIntent = new Intent(this, BookNote.class);
Bundle extras = new Bundle();
if(title.length() == 0 || title == null){title= "Empty";}
if(url.length() == 0 || url == null){ url = "Empty";}
if(note.length() == 0 || url == null) { note = "Empty";}
extras.putString("title", title);
extras.putString("url", url);
extras.putString("note", note);
extras.putBoolean("listen", listener);
extras.putBoolean("addBookmarkClicked", addBookmarkClicked);
bookNoteIntent.putExtras(extras);
startActivity(bookNoteIntent);
}
Great question! I had to deal with this issue myself as well, a couple of weeks ago.
The main thing is that you will need to re-instantiate your ArrayAdapter, or adapter in your case.
Now you do the first step correctly:
bookmarkList = readData();
adapter = new ArrayAdapter<Bookmark>(this, android.R.layout.simple_list_item_1, bookmarkList);
setListAdapter(adapter);
But you will do this again when trying to update the list: I believe you added the new bookmark correctly, but you'll need to re-create the ArrayAdapter for the listview.
EDIT:
I believe I found the peril.
Right here you will need to re-instantiate the ArrayAdapter, as I mentioned earlier.
private void addBookmark(Bookmark bookmark){
adapter.add(bookmark);
writeData();
}
Basically, whenever you update the data to be shown in your list, you need to do this step...
I am trying to to attach files which places on some folder in Sdcard. I am able to fetch files from gallery and other media type but no luck so far to browse sdcard so i could choose text files (Doc, docx, pdf etc). The requirement is very close to Email-attach menu option in Email-Application of Android device which allows user view Sdcard folders by Intent.
If anybody have such an experience to browse Sdcard and its Contents please share code or guide me. many Thanks in advance.
Recently i am using following code to open But it is not showing Sdcard option`:-
Uri startDir = Uri.fromFile(new File(Environment.getExternalStorageDirectory()
.getAbsolutePath()));
Intent intent = new Intent();
intent.setData(startDir);
intent.setType("*/*");
intent.setAction(Intent.ACTION_VIEW);
startActivity(intent);
try this ...
public OnClickListener buttonOnClickBrowse = new OnClickListener() {
#Override
public void onClick(View v)
{
loadFileList();
showDialog(DIALOG_LOAD_FILE);
}
};
// *************************************
ArrayList<String> str = new ArrayList<String>();
// Check if the first level of the directory structure is the one showing
private Boolean firstLvl = true;
private Item [] fileList;
private File path = new File(Environment.getExternalStorageDirectory() + "");
private String chosenFile;
private static final int DIALOG_LOAD_FILE = 1000;
ArrayAdapter adapter1;
private void loadFileList()
{
try
{
path.mkdirs();
} catch (SecurityException e)
{
Log.e(TAG , "unable to write on the sd card ");
}
// Checks whether path exists
if (path.exists())
{
FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File dir , String filename)
{
File sel = new File(dir , filename);
// Filters based on whether the file is hidden
// or not
return (sel.isFile() || sel.isDirectory()) && !sel.isHidden();
}
};
String [] fList = path.list(filter);
fileList = new Item[fList.length];
for (int i = 0; i < fList.length; i++)
{
fileList [i] = new Item(fList [i] , R.drawable.file_icon);
// Convert into file path
File sel = new File(path , fList [i]);
// Set drawables
if (sel.isDirectory())
{
fileList [i].icon = R.drawable.directory_icon;
Log.d("DIRECTORY" , fileList [i].file);
} else
{
Log.d("FILE" , fileList [i].file);
}
}
if (!firstLvl)
{
Item temp[] = new Item[fileList.length + 1];
for (int i = 0; i < fileList.length; i++)
{
temp [i + 1] = fileList [i];
}
temp [0] = new Item("Up" , R.drawable.directory_up);
fileList = temp;
}
} else
{
Log.e(TAG , "path does not exist");
}
adapter1 = new ArrayAdapter<Item>(ImageReader.this , android.R.layout.select_dialog_item , android.R.id.text1 , fileList) {
#Override
public View getView(int position , View convertView , ViewGroup parent)
{
View view = super.getView(position , convertView , parent);
TextView textView = (TextView) view.findViewById(android.R.id.text1);
// put the image on the text view
textView.setCompoundDrawablesWithIntrinsicBounds(fileList [position].icon , 0 , 0 , 0);
// add margin between image and text (support various
// screen
// densities)
int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
textView.setCompoundDrawablePadding(dp5);
return view;
}
};
}
private class Item {
public String file;
public int icon;
public Item(String file , Integer icon) {
this.file = file;
this.icon = icon;
}
#Override
public String toString()
{
return file;
}
}
File setetedFileName;
#Override
protected Dialog onCreateDialog(int id)
{
Dialog dialog = null;
AlertDialog.Builder builder = new Builder(this);
if (fileList == null)
{
Log.e(TAG , "No files loaded");
dialog = builder.create();
return dialog;
}
switch (id) {
case DIALOG_LOAD_FILE:
builder.setTitle("choose ur file");
builder.setAdapter(adapter1 , new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog , int which)
{
chosenFile = fileList [which].file;
File sel = new File(path + "/" + chosenFile);
setetedFileName = sel;
if (sel.isDirectory())
{
firstLvl = false;
// Adds chosen directory to list
str.add(chosenFile);
fileList = null;
path = new File(sel + "");
loadFileList();
removeDialog(DIALOG_LOAD_FILE);
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG , path.getAbsolutePath());
}
// Checks if 'up' was clicked
else if (chosenFile.equalsIgnoreCase("up") && !sel.exists())
{
// present directory removed from list
String s = str.remove(str.size() - 1);
// path modified to exclude present
// directory
path = new File(path.toString().substring(0 , path.toString().lastIndexOf(s)));
fileList = null;
// if there are no more directories in
// the list, then
// its the first level
if (str.isEmpty())
{
firstLvl = true;
}
loadFileList();
removeDialog(DIALOG_LOAD_FILE);
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG , path.getAbsolutePath());
}
// File picked
else
{
// Perform action with file picked
Toast.makeText(getApplicationContext() , "" + setetedFileName.getAbsolutePath() , Toast.LENGTH_SHORT).show();
}
}
});
break;
}
dialog = builder.show();
return dialog;
}
// *******************************************************************
One way is that, pragmatically show required files and folders in your app and let user select the files to be attached.
As far as showing particular folder through intent is concerned, seems there is no built in app to do that.
Have a look at this link.