Cannot resolve the custom path directory to save the captured Images - java

I have below code to choose the Directory which opens an Dialog box with options to choose custom directory path
DirectoryChooserDialog directoryChooserDialog =
new DirectoryChooserDialog(MainActivity.this,
new DirectoryChooserDialog.ChosenDirectoryListener()
{
#Override
public void onChosenDir(String chosenDir)
{
m_chosenDir = chosenDir;
Toast.makeText(
MainActivity.this, "Chosen directory: " +
chosenDir, Toast.LENGTH_LONG).show();
}
});
// Toggle new folder button enabling
directoryChooserDialog.setNewFolderEnabled(m_newFolderEnabled);
// Load directory chooser dialog for initial 'm_chosenDir' directory.
// The registered callback will be called upon final directory selection.
directoryChooserDialog.chooseDirectory(m_chosenDir);
m_newFolderEnabled = ! m_newFolderEnabled;
and below is the code to save the file in external storage
public void takePicture(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = Uri.fromFile(getOutputMediaFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, file);
startActivityForResult(intent, 100);
}
private static File getOutputMediaFile() {
File mediaStorageDir = new File(m_chosenDir);
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("CameraDemo", "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
return new File(mediaStorageDir.getPath() + File.separator +
"IMG_" + timeStamp + ".jpg");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
imageView.setImageURI(file);
}
}
But it highlights error in
File mediaStorageDir = new File(m_chosenDir);
and below is image file,
Error Image
How can I solve this? In which step I'm doing wrong...Please kindly suggest.
Thanks in advance.

Try the following code:
1) MainActivity.class:----------------
public class MainActivity extends AppCompatActivity {
private Button b;
private ImageView iv;
private final int PICTURE_ACTIVITY_CODE = 1;
private File captured_image_file;
private boolean flag = false;
private boolean flag_1 = false;
private String file_name = "myphoto";
private String file_extension = "png";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.iv);
b = (Button) findViewById(R.id.b);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createDirectoryChooserDialog();
}
});
}
private void createDirectoryChooserDialog() {
File mPath = new File(Environment.getExternalStorageDirectory() + "//DIR//");
FileDialog fileDialog = new FileDialog(this, mPath, "." + "png");
fileDialog.addDirectoryListener(new FileDialog.DirectorySelectedListener() {
public void directorySelected(File directory) {
Log.e(getClass().getName(), "*********selected dir " + directory.toString());
if (!directory.toString().isEmpty()) {
if (directory.exists()) {
captured_image_file = new File(directory.getAbsolutePath() + "/" + file_name + "." + file_extension);
flag = true;
} else {
flag = false; // directory doesn't exits.
}
}
if (flag) {
if (!captured_image_file.exists()) { // file doesn't exist
Log.e("File doesn't exists", "Creating File");
try {
flag_1 = captured_image_file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
flag_1 = false;
}
} else {
flag_1 = true; // file will be over-written
}
if (flag_1) {
Log.e("Creation", "Succeeded");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri outputFileUri = Uri.fromFile(captured_image_file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, PICTURE_ACTIVITY_CODE);
}
}
}
});
fileDialog.setSelectDirectoryOption(true);
fileDialog.showDialog();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICTURE_ACTIVITY_CODE) {
if (resultCode == RESULT_OK) {
Uri inputFileUri = Uri.fromFile(captured_image_file);
Bitmap image = BitmapFactory.decodeFile(inputFileUri.getPath());
iv.setImageBitmap(image);
} else {
// handle partially created file
}
}
}
}
2) FileDialog.class:------------
public class FileDialog {
private static final String PARENT_DIR = "..";
private final String TAG = getClass().getName();
private String[] fileList;
private File currentPath;
public interface FileSelectedListener {
void fileSelected(File file);
}
public interface DirectorySelectedListener {
void directorySelected(File directory);
}
private ListenerList<FileSelectedListener> fileListenerList = new ListenerList<FileSelectedListener>();
private ListenerList<DirectorySelectedListener> dirListenerList = new ListenerList<DirectorySelectedListener>();
private final Activity activity;
private boolean selectDirectoryOption;
private String fileEndsWith;
/**
* #param activity
* #param initialPath
*/
public FileDialog(Activity activity, File initialPath) {
this(activity, initialPath, null);
}
public FileDialog(Activity activity, File initialPath, String fileEndsWith) {
this.activity = activity;
setFileEndsWith(fileEndsWith);
if (!initialPath.exists()) initialPath = Environment.getExternalStorageDirectory();
loadFileList(initialPath);
}
/**
* #return file dialog
*/
public Dialog createFileDialog() {
Dialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(activity , android.R.style.Theme_Translucent_NoTitleBar);
//dialog.setContentView(R.layout.loading_screen);
builder.setTitle(currentPath.getPath());
if (selectDirectoryOption) {
builder.setPositiveButton("Select directory", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.e("pathname", currentPath.getPath());
fireDirectorySelectedEvent(currentPath);
}
});
}
builder.setItems(fileList, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String fileChosen = fileList[which];
File chosenFile = getChosenFile(fileChosen);
if (chosenFile.isDirectory()) {
loadFileList(chosenFile);
dialog.cancel();
dialog.dismiss();
showDialog();
} else fireFileSelectedEvent(chosenFile);
}
});
dialog = builder.show();
return dialog;
}
public void addFileListener(FileSelectedListener listener) {
fileListenerList.add(listener);
}
public void removeFileListener(FileSelectedListener listener) {
fileListenerList.remove(listener);
}
public void setSelectDirectoryOption(boolean selectDirectoryOption) {
this.selectDirectoryOption = selectDirectoryOption;
}
public void addDirectoryListener(DirectorySelectedListener listener) {
dirListenerList.add(listener);
}
public void removeDirectoryListener(DirectorySelectedListener listener) {
dirListenerList.remove(listener);
}
/**
* Show file dialog
*/
public void showDialog() {
createFileDialog().show();
}
private void fireFileSelectedEvent(final File file) {
fileListenerList.fireEvent(new ListenerList.FireHandler<FileSelectedListener>() {
public void fireEvent(FileSelectedListener listener) {
listener.fileSelected(file);
}
});
}
private void fireDirectorySelectedEvent(final File directory) {
dirListenerList.fireEvent(new ListenerList.FireHandler<DirectorySelectedListener>() {
public void fireEvent(DirectorySelectedListener listener) {
listener.directorySelected(directory);
}
});
}
private void loadFileList(File path) {
this.currentPath = path;
List<String> r = new ArrayList<String>();
if (path.exists()) {
if (path.getParentFile() != null) r.add(PARENT_DIR);
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
if (!sel.canRead()) return false;
if (selectDirectoryOption) return sel.isDirectory();
else {
boolean endsWith = fileEndsWith != null ? filename.toLowerCase().endsWith(fileEndsWith) : true;
return endsWith || sel.isDirectory();
}
}
};
String[] fileList1 = path.list(filter);
if (fileList1 == null) {
} else {
for (String file : fileList1) {
r.add(file);
}
}
}
fileList = (String[]) r.toArray(new String[]{});
}
private File getChosenFile(String fileChosen) {
if (fileChosen.equals(PARENT_DIR)) return currentPath.getParentFile();
else return new File(currentPath, fileChosen);
}
private void setFileEndsWith(String fileEndsWith) {
this.fileEndsWith = fileEndsWith != null ? fileEndsWith.toLowerCase() : fileEndsWith;
}
}
3) ListenerList interface:------------
class ListenerList<L> {
private List<L> listenerList = new ArrayList<L>();
public interface FireHandler<L> {
void fireEvent(L listener);
}
public void add(L listener) {
listenerList.add(listener);
}
public void fireEvent(FireHandler<L> fireHandler) {
List<L> copy = new ArrayList<L>(listenerList);
for (L l : copy) {
fireHandler.fireEvent(l);
}
}
public void remove(L listener) {
listenerList.remove(listener);
}
public List<L> getListenerList() {
return listenerList;
}
}
4) activity_main.xml:----------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:gravity="center">
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
tools:ignore="contentDescription"
android:id="#+id/iv"/>
<Button
android:layout_width="200dp"
android:layout_height="50dp"
android:text="Take Pic"
android:id="#+id/b"/>
</LinearLayout>
5) Note: FileDialog class and ListenerList interface are from : Choose File Dialog

Related

How to handle loading large amounts of data in android

I have an activity with a button upon clicking which opens a new activity with 3 fragments with tab layout, The first fragment loads files from the internal storage in recyclerview, 2nd one loads installed apps in recyclerview and the 3rd loads contacts in a recyclerview, But the problem I'm facing is that when I click the button to launch the activity it takes 2-3 seconds to launch the activity & I tested it on a device which contained a lot of apps and contacts it crashed the app and didn't opened the activity, I think this is because it is taking time to load all the data at once, How can I solve this problem?
This is the code from the fragments
FileListFragment.java
public class FileListFragment extends Fragment implements FilesStateManager {
private static final String TAG = "FileListFragment";
RecyclerView fileListRecyclerView,currentPathRecyclerView;
TextView currentPathTextView;
ArrayList<FileObject> fileObjects = new ArrayList<>();
ArrayList<FileObject> currentFolders = new ArrayList<>();
static ArrayList<FileObject> selectedFiles = new ArrayList<>();
String currentPath = "";
String initialPath = "";
String pathToShow = "/";
RelativeLayout grantPermissionContainer;
Button grantPermissionButton;
FileManager fileManager;
static DataSelectedManager dataSelectedManager;
public FileListFragment(DataSelectedManager dataSelectedManager) {
this.dataSelectedManager = dataSelectedManager;
}
private final int PERMISSION_CODE = 100;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_file_list,container,false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
currentPathRecyclerView = view.findViewById(R.id.current_folder_recyclerview);
fileListRecyclerView = view.findViewById(R.id.folder_list_recyclerview);
grantPermissionContainer = view.findViewById(R.id.grant_permission_container);
grantPermissionButton = view.findViewById(R.id.grant_permission_button);
init();
}
private void init(){
fileManager = new FileManager(getContext());
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
grantPermissionContainer.setVisibility(View.VISIBLE);
fileListRecyclerView.setVisibility(View.GONE);
}
grantPermissionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT < 16) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},PERMISSION_CODE);
} else {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},PERMISSION_CODE);
}
}
});
try{
String path = getActivity().getExternalFilesDir(null).getPath();
currentPath = path.split("Android")[0];
initialPath = currentPath;
FileObject fileObject = new FileObject("/",initialPath,null,true,"none","0",false);
currentFolders.add(fileObject);
setupCurrentPathRecyclerView();
readFiles();
Log.d(TAG, "init: " + path);
}
catch (Exception e){
e.printStackTrace();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Log.d(TAG, "onRequestPermissionsResult: Called");
if (requestCode == PERMISSION_CODE){
Log.d(TAG, "onRequestPermissionsResult: Codes matched");
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Log.d(TAG, "onRequestPermissionsResult: Permission Granted");
grantPermissionContainer.setVisibility(View.GONE);
fileListRecyclerView.setVisibility(View.VISIBLE);
FileObject fileObject = new FileObject("/",initialPath,null,true,"none","0",false);
currentFolders.add(fileObject);
setupCurrentPathRecyclerView();
readFiles();
}
}
}
private void readFiles(){
fileObjects = fileManager.readFiles(currentPath,selectedFiles);
setupRecyclerView();
}
private void setupRecyclerView(){
FileListAdapter fileListAdapter = new FileListAdapter(fileObjects,selectedFiles,getContext(),this);
fileListRecyclerView.setAdapter(fileListAdapter);
fileListRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
}
private void setupCurrentPathRecyclerView(){
FolderPathAdapter folderPathAdapter = new FolderPathAdapter(currentFolders,getContext(),this);
currentPathRecyclerView.setAdapter(folderPathAdapter);
currentPathRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL,false));
currentPathRecyclerView.smoothScrollToPosition(currentFolders.size());
}
#Override
public void folderClicked(FileObject fileObject) {
currentPath = fileObject.getPath();
currentFolders.add(fileObject);
currentPathRecyclerView.getAdapter().notifyItemInserted(currentFolders.size() - 1);
currentPathRecyclerView.smoothScrollToPosition(currentFolders.size());
readFiles();
}
#Override
public void pathFolderClicked(FileObject fileObject) {
Log.d(TAG, "pathFolderClicked: Called");
if (!fileObject.getPath().equals(currentFolders.get(currentFolders.size() - 1).getPath())){
for (FileObject folder : currentFolders){
if (folder.getPath().equals(fileObject.getPath())){
int index = currentFolders.indexOf(folder) + 1;
int size = currentFolders.size();
currentFolders = new ArrayList<>(currentFolders.subList(0,index));
Log.d(TAG, "pathFolderClicked: Number of item " + (size - index) + " Index: " + index);
// currentPathRecyclerView.getAdapter().notifyItemRangeRemoved(index,size - index);
setupCurrentPathRecyclerView();
currentPath = currentFolders.get(currentFolders.size() - 1).getPath();
readFiles();
Log.d(TAG, "pathFolderClicked: Notified");
}
}
Log.d(TAG, "pathFolderClicked: " + Arrays.toString(currentFolders.toArray()));
}
}
#Override
public void fileSelected(FileObject fileObject) {
selectedFiles.add(fileObject);
dataSelectedManager.dataSelected();
}
#Override
public void fileDeselected(FileObject fileObject) {
ArrayList<FileObject> filesToRemove = new ArrayList<>();
for (FileObject fileObject1 : selectedFiles){
if (fileObject.getPath().equals(fileObject1.getPath())){
filesToRemove.add(fileObject1);
}
}
dataSelectedManager.dataDeSelected();
selectedFiles.removeAll(filesToRemove);
}
public static void triggerDataTransfer(){
dataSelectedManager.sendSelectedFiles(selectedFiles);
}
}
AppListFragment.java
public class AppListFragment extends Fragment implements AppsStateManager {
RecyclerView appListRecyclerView;
TextView selectAllTextView;
CheckBox selectAllCheckBox;
static ArrayList<App> apps = new ArrayList<>();
AppsManager appsManager;
static DataSelectedManager dataSelectedManager;
public AppListFragment(DataSelectedManager dataSelectedManager) {
this.dataSelectedManager = dataSelectedManager;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_app_list,container,false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
appListRecyclerView = view.findViewById(R.id.app_recycler_view);
selectAllTextView = view.findViewById(R.id.select_all_text_view);
selectAllCheckBox = view.findViewById(R.id.select_all_checkbox);
appsManager = new AppsManager(getActivity().getPackageManager(),getActivity().getApplicationContext().getPackageName());
getInstalledApps();
setupRecyclerView();
selectAllCheckBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!selectAllCheckBox.isChecked()){
for (App app : apps){
if (app.isSelected()){
app.setSelected(false);
dataSelectedManager.dataDeSelected();
}
}
}
else {
for (App app : apps){
if (!app.isSelected()){
app.setSelected(true);
dataSelectedManager.dataSelected();
}
}
}
appListRecyclerView.getAdapter().notifyDataSetChanged();
}
});
}
private void getInstalledApps(){
apps = appsManager.getInstalledApps();
selectAllTextView.setText("Select All (" + apps.size() + ")");
}
private void setupRecyclerView(){
AppListAdapter appListAdapter = new AppListAdapter(apps,getContext(),this);
appListRecyclerView.setAdapter(appListAdapter);
appListRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
}
#Override
public void deSelected() {
selectAllCheckBox.setChecked(false);
dataSelectedManager.dataDeSelected();
}
#Override
public void selected() {
dataSelectedManager.dataSelected();
}
public static void triggerDataTransfer(){
ArrayList<App> selectedApps = new ArrayList<>();
for (App app : apps){
if (app.isSelected()){
selectedApps.add(app);
}
}
dataSelectedManager.sendSelectedApps(selectedApps);
}
}
ContactListFragment.java
public class ContactListFragment extends Fragment implements ContactsStateManager {
private static final String TAG = "ContactListFragment";
static ArrayList<Contact> contacts = new ArrayList<>();
TextView selectAllTextView;
CheckBox selectAllRadioButton;
Button grantPermissionButton;
RelativeLayout grantPermissionLayout;
RecyclerView contactsRecyclerView;
ContactsManager contactsManager;
static DataSelectedManager dataSelectedManager;
public ContactListFragment(DataSelectedManager dataSelectedManager) {
this.dataSelectedManager = dataSelectedManager;
}
private final int PERMISSION_CODE = 101;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_contact_list,container,false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
contactsRecyclerView = view.findViewById(R.id.contacts_recycler_view);
selectAllTextView = view.findViewById(R.id.select_all_text_view);
selectAllRadioButton = view.findViewById(R.id.select_all_checkbox);
grantPermissionLayout = view.findViewById(R.id.grant_permission_container);
grantPermissionButton = view.findViewById(R.id.grant_permission_button);
contactsManager = new ContactsManager(getActivity().getContentResolver());
selectAllRadioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!selectAllRadioButton.isChecked()){
for (Contact contact: contacts){
if (contact.isSelected()){
contact.setSelected(false);
dataSelectedManager.dataDeSelected();
}
}
}
else{
for (Contact contact: contacts){
if (!contact.isSelected()){
contact.setSelected(true);
dataSelectedManager.dataSelected();
}
}
}
contactsRecyclerView.getAdapter().notifyDataSetChanged();
}
});
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED){
grantPermissionLayout.setVisibility(View.VISIBLE);
contactsRecyclerView.setVisibility(View.GONE);
}
else{
readContacts();
setupRecyclerView();
}
grantPermissionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS},PERMISSION_CODE);
}
});
}
private void readContacts(){
contacts = contactsManager.getContacts();
selectAllTextView.setText("Select All (" + contacts.size() + ")");
}
private void setupRecyclerView(){
ContactListAdapter contactListAdapter = new ContactListAdapter(contacts,getContext(),this);
contactsRecyclerView.setAdapter(contactListAdapter);
contactsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Log.d(TAG, "onRequestPermissionsResult: Called");
if (requestCode == PERMISSION_CODE){
Log.d(TAG, "onRequestPermissionsResult: Codes matched");
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Log.d(TAG, "onRequestPermissionsResult: Permission Granted");
grantPermissionLayout.setVisibility(View.GONE);
readContacts();
contactsRecyclerView.setVisibility(View.VISIBLE);
setupRecyclerView();
}
}
}
#Override
public void deSelected() {
selectAllRadioButton.setChecked(false);
dataSelectedManager.dataDeSelected();
}
#Override
public void selected() {
dataSelectedManager.dataSelected();
}
public static void triggerDataTransfer(){
ArrayList<Contact> selectedContacts = new ArrayList<>();
for(Contact contact : contacts){
if (contact.isSelected()){
selectedContacts.add(contact);
}
}
dataSelectedManager.sendSelectedContacts(selectedContacts);
}
}
AppsManager.java
public class AppsManager {
PackageManager packageManager;
private String PACKAGE_NAME;
public AppsManager(PackageManager packageManager,String PACKAGE_NAME) {
this.packageManager = packageManager;
this.PACKAGE_NAME = PACKAGE_NAME;
}
public ArrayList<App> getInstalledApps(){
PackageManager packageManager = this.packageManager;
ArrayList<App> apps = new ArrayList<>();
List<PackageInfo> packs = packageManager.getInstalledPackages(0);
for (int i = 0; i < packs.size(); i++){
PackageInfo packageInfo = packs.get(i);
if ((!isSystemApp(packageInfo)) && !packageInfo.packageName.equals(PACKAGE_NAME)){
String appName = packageInfo.applicationInfo.loadLabel(packageManager).toString();
Drawable icon = packageInfo.applicationInfo.loadIcon(packageManager);
String packages = packageInfo.applicationInfo.packageName;
apps.add(new App(appName,icon,packages,false));
}
}
return apps;
}
private boolean isSystemApp(PackageInfo packageInfo){
return (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
}
}
ContactsManager.java
public class ContactsManager{
ContentResolver contentResolver;
public ContactsManager(ContentResolver contentResolver) {
this.contentResolver = contentResolver;
}
public ArrayList<Contact> getContacts(){
ContentResolver cr = contentResolver;
ArrayList<Contact> contacts = new ArrayList<>();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,ContactsContract.Contacts.DISPLAY_NAME + " ASC");
if (cursor.getCount() > 0){
while (cursor.moveToNext()){
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String phone = "";
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0){
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
pCur.close();
}
Contact contact = new Contact(name,id,phone,false);
contacts.add(contact);
}
}
return contacts;
}
}
FileManager.java
public class FileManager {
private static final String TAG = "FileManager";
Context context;
public FileManager(Context context) {
this.context = context;
}
public ArrayList<FileObject> readFiles(String path, ArrayList<FileObject> selectedFiles){
ArrayList<FileObject> filesList = new ArrayList<>();
File file = new File(path);
File[] files = file.listFiles();
for (File file1 : files){
String name = file1.getName();
String filePath = file1.getAbsolutePath();
boolean isDirectory = file1.isDirectory();
String fileSize = "";
if (isDirectory){
int count = file1.listFiles().length;
if (count > 0){
fileSize = count + "";
}
}
else{
long fileSizeInBytes = file1.length();
long fileSizeInKB = fileSizeInBytes / 1024;
long fileSizeInMB = fileSizeInKB / 1024;
if (fileSizeInMB >= 1){
fileSize = fileSizeInMB + " MB";
}
else{
fileSize = fileSizeInKB + " KB";
}
}
boolean selected = isSelected(filePath,selectedFiles);
String extension = "";
if (isDirectory){
extension = "none";
}
else{
Log.d(TAG, "readFiles: " + filePath);
String[] splitArray = filePath.split("\\.");
Log.d(TAG, "readFiles: " + splitArray.length);
extension = splitArray[splitArray.length - 1];
}
Drawable icon;
if (isDirectory){
icon = context.getResources().getDrawable(R.drawable.ic_folder_skin_24dp);
}
else{
switch (extension){
case "pdf":
icon = context.getResources().getDrawable(R.drawable.ic_picture_as_pdf_red_24dp);
break;
default:
icon = context.getResources().getDrawable(R.drawable.ic_insert_drive_file_skin_24dp);
break;
}
}
FileObject fileObject = new FileObject(name,filePath,icon,isDirectory,extension,fileSize,selected);
filesList.add(fileObject);
}
return filesList;
}
boolean isSelected(String path, ArrayList<FileObject> selectedFiles){
boolean isSelected = false;
for (FileObject fileObject : selectedFiles){
if (fileObject.getPath().equals(path)){
isSelected = true;
}
}
return isSelected;
}
}
When you are performing heavy operations consider using Threads.

save state of my game in database

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);
}

Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent to activity

I m getting this error in my code.
Please help me.
My code is as follows. I don't know how to solve this. When I click on the add button I want to add all data to the model class and that class should be filled with the list array in main activity.
public class MainActivity extends Activity implements DataTransferInterfase{
private Button btnSelect,btnShow;
public int REQUEST_CAMERA=1;
public int SELECT_IMAGE=0;
private GridView gridview;
private CustomAdapter gridAdaptor;
public TextView tvcounter;
public ImageItemBin imageItemBin;
private Uri mCapturedImageUri;
public static ArrayList<ImageItemBin> publicSelectedImage=new ArrayList<ImageItemBin>();
public ArrayList<ImageItemBin> showImagelist=new ArrayList<ImageItemBin>();
public Uri ImageUri;
private int count=publicSelectedImage.size();
private int coloumn=3;
private int row=count/coloumn;
public String imgPath="";
private Uri fileUri; // file url to store image
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSelect=(Button)findViewById(R.id.btnselect);
btnShow=(Button)findViewById(R.id.btnShow);
tvcounter=(TextView)findViewById(R.id.tvcounter);
publicSelectedImage=new ArrayList<ImageItemBin>();
//showImagelist=new ArrayList<ImageItemBin>();
showImagelist=new ArrayList<ImageItemBin>();
gridview=(GridView) findViewById(R.id.gridLayout_main);
// gridAdaptor=new CustomAdapter(MainActivity.this,publicSelectedImage);
// gridview.setAdapter(gridAdaptor);
//gridAdaptor(R.layout.custom_grid_item_layout,getView());
//gridLayout.addView(gridAdaptor.getView());
//gridLayout.addView(inflater.inflate(R.layout.custom_grid_item_layout,null));
//gridLayout.addView(img);
//tvcounter.setText(CountRecord(imageItemBin));
//tvcounter.setText(CustomAdapter.result+"");
showImagelist.add(CustomAdapter.showBin);
tvcounter.setText(showImagelist.size());
//showImagelist.add(CustomAdapter.result);
//tvcounter.setText(counter);
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//custom dialogBox
final Dialog dialog=new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_dialog_layout);
dialog.setTitle("Select from..");
//set the custom dialog components
TextView txtmsg=(TextView)dialog.findViewById(R.id.txtmsg);
Button btnGallaery=(Button)dialog.findViewById(R.id.btngallery);
Button btnCamara=(Button)dialog.findViewById(R.id.btncamara);
btnGallaery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent image=new Intent();
image.setType("image/*");
image.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(image,"select file"),SELECT_IMAGE);
dialog.dismiss();
}
});
btnCamara.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cam=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
/*if(cam.resolveActivity(getPackageManager())!=null){
String filename="temp.jpg";
ContentValues values=new ContentValues();
values.put(MediaStore.Images.Media.TITLE,filename);
mCapturedImageUri=getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);*/
//cam.putExtra(MediaStore.EXTRA_OUTPUT,setImageUri());
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
cam.putExtra("Image", fileUri);
startActivityForResult(cam,REQUEST_CAMERA);
dialog.dismiss();
// }
}
});
dialog.show();
}
});
btnShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==SELECT_IMAGE){
if(resultCode==RESULT_OK && null!=data){
for (int i=0,c=0,r=0;i<count;i++,c++){
if(c==coloumn){
c=0;
r++;
}
}
ImageUri=data.getData();
imageItemBin=new ImageItemBin();
imageItemBin.setImage(ImageUri.toString());
publicSelectedImage.add(imageItemBin);
gridAdaptor=new CustomAdapter(MainActivity.this,publicSelectedImage,this);
gridview.setAdapter(gridAdaptor);
}
}
if(requestCode==REQUEST_CAMERA)
{
if(resultCode==RESULT_OK && data!=null){
/*String[] projection={MediaStore.Images.Media.DATA};
Cursor cursor=managedQuery(mCapturedImageUri,projection,null,null,null);
int coloumn_index_data=cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String picturePath=cursor.getString(coloumn_index_data);
Uri selectedImage=data.getData();
imageItemBin=new ImageItemBin();
imageItemBin.setImage(selectedImage.toString());
publicSelectedImage.add(imageItemBin);*/
// gridAdaptor=new CustomAdapter(MainActivity.this,publicSelectedImage);
// gridview.setAdapter(gridAdaptor);
Bitmap mphoto = (Bitmap) data.getExtras().get("data");
String stringImage=BitMapToString(mphoto);
// String getimage=getImagePath();
imageItemBin=new ImageItemBin();
imageItemBin.setImage(stringImage);
//imageItemBin.setImage(picturePth.toString());
publicSelectedImage.add(imageItemBin);
gridAdaptor=new CustomAdapter(MainActivity.this,publicSelectedImage,this);
gridview.setAdapter(gridAdaptor);
//gridAdaptor.notifyDataSetChanged();
// tvcounter.setText(counter);
//publicSelectedImage=selectedImage;
}
}
}
public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
/*private List<ImageItemBin> DisplayImage(){
ImageItemBin itembin=new ImageItemBin();
itembin.getImage();
}*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/*
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
/*File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
*/
//File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".jpg");
// Create the storage directory if it does not exist
/*if (!file.exists()) {
if (!file.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}*/
// Create a media file name
//String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
// Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".jpg");
} /*else if (type == MEDIA_TYPE_VIDEO) {
//mediaFile = new File(file.getPath() + File.separator
// + "VID_" + timeStamp + ".mp4");
}*/ else {
return null;
}
return mediaFile;
//return file;
}
private Bitmap previewCapturedImage(Uri file)
{
Bitmap bitmap=null;
try {
// hide video preview
//videoPreview.setVisibility(View.GONE);
//imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
bitmap = BitmapFactory.decodeFile(file.getPath(),
options);
return bitmap;
//imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
return bitmap;
}
public String BitMapToString(Bitmap bitmap){
ByteArrayOutputStream baos=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
byte [] b=baos.toByteArray();
String temp= Base64.encodeToString(b, Base64.DEFAULT);
return temp;
}
public Bitmap StringToBitMap(String encodedString){
try{
byte [] encodeByte=Base64.decode(encodedString,Base64.DEFAULT);
Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
}catch(Exception e){
e.getMessage();
return null;
}
}
public static int totalAmt=0;
#Override
public int CountRecord(ImageItemBin bin) {
//for (int i=0;i<count;i++){
totalAmt=totalAmt+1;
// }
return totalAmt;
}
}
I just got it.
here is the way for getting the perfect result.in adapter just add the data.get(position)to countRecord method.
public int CountRecord(ImageItemBin bin)
{
showImagelist.add(showBin);
int size=showImagelist.size();
tvcounter.setText(Integer.toString(size));
btnShow.setText(Integer.toString(size));
return 0;
}
CustomAdaptor.java
public class CustomAdapter extends BaseAdapter {
public static String counter="";
public static int result=0;
Context context;
private int layoutResourceId;
private ArrayList<ImageItemBin> data=new ArrayList<ImageItemBin>();
public static ImageItemBin showBin=new ImageItemBin();
DataTransferInterfase dataTransferInterfase;
String qty,title;
public MainActivity mainActivity;
ImageLoader imageLoader;
DisplayImageOptions options;
private static LayoutInflater inflater=null;
public CustomAdapter(MainActivity mainActivity,ArrayList<ImageItemBin> data,DataTransferInterfase dataTransferInterfase){
this.data=data;
this.context=mainActivity;
this.dataTransferInterfase=dataTransferInterfase;
this.mainActivity=mainActivity;
inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, final View convertView, ViewGroup parent) {
Holder holder=null;
View rootview=convertView;
if(rootview==null) {
rootview = inflater.inflate(R.layout.custom_grid_item_layout, null);
holder = new Holder();
holder.edttitle = (EditText) rootview.findViewById(R.id.edtTitle);
holder.edtqty = (EditText) rootview.findViewById(R.id.edtQty);
holder.image = (ImageView) rootview.findViewById(R.id.MyimageView);
holder.tvcounter=(TextView)rootview.findViewById(R.id.tvcounter);
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(context));
rootview.setTag(holder);
qty=holder.edtqty.getText().toString();
title=holder.edttitle.getText().toString();
data.get(position).setTitle(title);
data.get(position).setQty(qty);
}
else
{
holder=(Holder)convertView.getTag();
holder.image.setTag(position);
holder.edttitle.setTag(position);
holder.edtqty.setTag(position);
qty=holder.edtqty.getText().toString();
title=holder.edttitle.getText().toString();
data.get(position).setTitle(title);
data.get(position).setQty(qty);
}
String img=data.get(position).getImage();
final String title=data.get(position).getTitle();
final String qty=data.get(position).getQty();
options = getDisplayImageOptions(context, R.mipmap.ic_launcher);
imageLoader.displayImage(img, holder.image, options);
holder.btnadd=(Button)rootview.findViewById(R.id.btnAdd);
final Holder finalHolder = holder;
//public static final ImageItemBin showBin=new ImageItemBin();
holder.btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
data.get(position).setQty(qty);
data.get(position).setTitle(title);
showBin.setImage(data.get(position).getImage());
showBin.setTitle(title);
showBin.setQty(qty);
mainActivity.CountRecord(data.get(position));
}
});
return rootview;
}
static class Holder{
ImageView image;
EditText edtqty;
EditText edttitle;
Button btnadd;
TextView tvcounter;
}
public static DisplayImageOptions getDisplayImageOptions(Context context, int defaultImg) {
DisplayImageOptions options = new DisplayImageOptions.Builder().showImageOnLoading(defaultImg)
.resetViewBeforeLoading(true).showImageForEmptyUri(defaultImg).showImageOnFail(defaultImg)
.cacheInMemory(true).cacheOnDisk(true).considerExifParams(true).bitmapConfig(Bitmap.Config.RGB_565)
.considerExifParams(true).build();
return options;
}
}

[HELP]FATAL EXCEPTION: main java.lang.NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
ProductDatabase.ProductDatabaseHelper controller = new ProductDatabase.ProductDatabaseHelper(this);
EditText mBarcodeEdit;
EditText mFormatEdit;
EditText mTitleEdit;
EditText mPriceEdit;
private static final int ZBAR_SCANNER_REQUEST = 0;
private static final int ZBAR_QR_SCANNER_REQUEST = 1;
private static final ProductData mProductData = new ProductData();
Button mScanButton;
Button mAddButton;
Button mSelectButton;
Button mExportButton;
Button btnimport;
ProductDatabase mProductDb;
ListView ls;
TextView infotext;
File file = null;
// DatabaseHelper dbhelper = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ls = (ListView) findViewById(R.id.placeslist);
mBarcodeEdit = (EditText) findViewById(R.id.barcodeEdit);
mFormatEdit = (EditText) findViewById(R.id.codeFormatEdit);
mTitleEdit = (EditText) findViewById(R.id.titleEdit);
mPriceEdit = (EditText) findViewById(R.id.priceEdit);
mScanButton = (Button) findViewById(R.id.scan_btn);
mAddButton = (Button) findViewById(R.id.addButton);
mSelectButton = (Button) findViewById(R.id.selelctButton);
mProductDb = new ProductDatabase(this); // not yet shown
infotext = (TextView) findViewById(R.id.txtresulttext);
mExportButton = (Button) findViewById(R.id.exportbtn);
mSelectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, product_list.class);
startActivity(i);
}
});
mAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String barcode = mBarcodeEdit.getText().toString();
String format = mFormatEdit.getText().toString();
String title = mTitleEdit.getText().toString();
String price = mPriceEdit.getText().toString();
String errors = validateFields(barcode, format, title, price);
if (errors.length() > 0) {
showInfoDialog(MainActivity.this, "Please fix errors", errors);
} else {
mProductData.barcode = barcode;
mProductData.format = format;
mProductData.title = title;
mProductData.price = new BigDecimal(price);
mProductDb.insert(mProductData);
showInfoDialog(MainActivity.this, "Success", "Product saved successfully");
resetForm();
}
}
});
mExportButton.setOnClickListener(new View.OnClickListener() {
SQLiteDatabase sqldb = controller.getReadableDatabase(); //My Database class
Cursor c =null;
#Override
public void onClick(View view) { //main code begins here
try {
c = sqldb.rawQuery("select * from spot_pay.db", null);
int rowcount = 0;
int colcount = 0;
File sdCardDir = Environment.getExternalStorageDirectory();
String filename = "MyBackUp.csv";
// the name of the file to export with
File saveFile = new File(sdCardDir, filename);
FileWriter fw = new FileWriter(saveFile);
BufferedWriter bw = new BufferedWriter(fw);
rowcount = c.getCount();
colcount = c.getColumnCount();
if (rowcount > 0) {
c.moveToFirst();
for (int i = 0; i < colcount; i++) {
if (i != colcount - 1) {
bw.write(c.getColumnName(i) + ",");
} else {
bw.write(c.getColumnName(i));
}
}
bw.newLine();
for (int i = 0; i < rowcount; i++) {
c.moveToPosition(i);
for (int j = 0; j < colcount; j++) {
if (j != colcount - 1)
bw.write(c.getString(j) + ",");
else
bw.write(c.getString(j));
}
bw.newLine();
}
bw.flush();
infotext.setText("Exported Successfully.");
}
} catch (Exception ex) {
if (sqldb.isOpen()) {
sqldb.close();
infotext.setText(ex.getMessage().toString());
}
} finally {
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
private void showInfoDialog(Context context, String title, String information) {
new AlertDialog.Builder(context)
.setMessage(information)
.setTitle(title)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
private void resetForm() {
// TODO Auto-generated method stub
mBarcodeEdit.getText().clear();
mFormatEdit.getText().clear();
mTitleEdit.getText().clear();
mPriceEdit.getText().clear();
}
public void launchScanner(View v) {
if (isCameraAvailable()) {
Intent intent = new Intent(this, ZBarScannerActivity.class);
startActivityForResult(intent, ZBAR_SCANNER_REQUEST);
} else {
Toast.makeText(this, "Rear Facing Camera Unavailable", Toast.LENGTH_SHORT).show();
}
}
public void launchQRScanner(View v) {
if (isCameraAvailable()) {
Intent intent = new Intent(this, ZBarScannerActivity.class);
intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{Symbol.QRCODE});
startActivityForResult(intent, ZBAR_SCANNER_REQUEST);
} else {
Toast.makeText(this, "Rear Facing Camera Unavailable", Toast.LENGTH_SHORT).show();
}
}
public boolean isCameraAvailable() {
PackageManager pm = getPackageManager();
return pm.hasSystemFeature(PackageManager.FEATURE_CAMERA);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ZBAR_SCANNER_REQUEST:
case ZBAR_QR_SCANNER_REQUEST:
if (resultCode == RESULT_OK) {
mBarcodeEdit.setText(data.getStringExtra(ZBarConstants.SCAN_RESULT));
// Toast.makeText(this, "Scan Result = " + data.getStringExtra(ZBarConstants.SCAN_RESULT), Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED && data != null) {
String error = data.getStringExtra(ZBarConstants.ERROR_INFO);
if (!TextUtils.isEmpty(error)) {
Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
}
}
break;
}
}
private static String validateFields(String barcode, String format,
String title, String price) {
StringBuilder errors = new StringBuilder();
if (barcode.matches("^\\s*$")) {
errors.append("Barcode required\n");
}
if (format.matches("^\\s*$")) {
errors.append("Format required\n");
}
if (title.matches("^\\s*$")) {
errors.append("Title required\n");
}
if (!price.matches("^-?\\d+(.\\d+)?$")) {
errors.append("Need numeric price\n");
}
return errors.toString();
}
}
I think string may be null somewhere. Please type something in textfield or check for null string.

Carrying intent from PreferenceActivity to LWP Service/Movie class

I am having trouble carrying over a user selected image/gif to the main LWP service. I start off by prompting the user to select a gif through this PreferenceActivity (some of this was borrowed from members here and tutorials on Vogella)
public class GifPreference extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener{
#SuppressWarnings("deprecation")
//SharedPreferences SHARED_PREF;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getPreferenceManager().setSharedPreferencesName("custom_gif");
addPreferencesFromResource(R.xml.prefsettings);
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(
this);
getPreferenceManager().findPreference("custom_gif").setOnPreferenceClickListener(new OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
Toast.makeText(getBaseContext(), "Select a GIF - " + (width) + " x " + height , Toast.LENGTH_LONG).show();
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
return true;
}
});
}
public String getRealPathFromURI(Uri contentUri) {
String [] proj={MediaColumns.DATA};
Cursor cursor = managedQuery( contentUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
String RealPath;
SharedPreferences customSharedPreference = getSharedPreferences("custom_gif", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = customSharedPreference.edit ();
RealPath = getRealPathFromURI (selectedImage);
editor.putString("custom_gif", RealPath);
editor.commit();
ComponentName component = new ComponentName(getPackageName(), getPackageName() + ".LWPEngine");
Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, component);
startActivity(intent);
}}
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onDestroy() {
getPreferenceManager().getSharedPreferences().
unregisterOnSharedPreferenceChangeListener(this);
super.onDestroy();
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
}
}
And this is the main LWPService:
public class LWPEngine extends WallpaperService {
private static int RESULT_LOAD_IMAGE1 = 1;
static final Handler mGIFHandler = new Handler();
//public String gifBG;
public Engine onCreateEngine() {
try {
LWPEngine.GIFEngine var1 = new LWPEngine.GIFEngine();
return var1;
} catch (IOException var3) {
return null;
}
}
class GIFEngine extends Engine {
private LWPEngineHelper lWPEngineHelper = new LWPEngineHelper(LWPEngine.this.getApplicationContext(), LWPEngine.this.getResources());
private final Movie mGIF;
private final int mGIFDuration;
private final int mGIFHeight;
private final Runnable mGIFRunnable;
private final int mGIFWidth;
private String mImageScale = "Stretch to screen";
private long mStart;
private int mWhen;
#SuppressWarnings("unused")
public GIFEngine() throws IOException {
//decodes and plays the gif - if no gif is found, throw an error.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(LWPEngine.this);
String gifBG = prefs.getString("custom_gif", "This file does not work");
InputStream var2 = new FileInputStream(gifBG);
//InputStream var2 = LWPEngine.this.getResources().openRawResource(R.drawable.dogegif);
if(var2 != null) {
try {
this.mGIF = Movie.decodeStream(var2);
this.mGIFDuration = this.mGIF.duration();
} finally {
var2.close();
}
this.mGIFWidth = this.mGIF.width();
this.mGIFHeight = this.mGIF.height();
this.mWhen = -1;
this.mGIFRunnable = new Runnable() {
public void run() {
GIFEngine.this.animGIF();
}
};
} else {
throw new IOException("Can't open GIF");
}
}
void animGIF()
{
tick();
SurfaceHolder localSurfaceHolder = getSurfaceHolder();
Canvas localCanvas = null;
/* try
{*/
localCanvas = localSurfaceHolder.lockCanvas();
if (localCanvas != null)
animGIFDraw(localCanvas);
if (localCanvas != null)
localSurfaceHolder.unlockCanvasAndPost(localCanvas);
LWPEngine.mGIFHandler.removeCallbacks(this.mGIFRunnable);
if (isVisible())
LWPEngine.mGIFHandler.postDelayed(this.mGIFRunnable, 40L);
return;
/* }
finally
{
if (localCanvas != null)
localSurfaceHolder.unlockCanvasAndPost(localCanvas);
}*/
}
void animGIFDraw(Canvas var1) {
this.lWPEngineHelper.setBackground(var1);
var1.save();
PointF var3 = this.lWPEngineHelper.getCanvasScale(this.mImageScale, this.mGIFWidth, this.mGIFHeight);
var1.scale(var3.x, var3.y);
this.mGIF.setTime(this.mWhen);
Point var5 = this.lWPEngineHelper.getImagePos(var3, this.mGIFWidth, this.mGIFHeight);
this.mGIF.draw(var1, (float)var5.x, (float)var5.y);
var1.restore();
}
public void onDestroy() {
super.onDestroy();
LWPEngine.mGIFHandler.removeCallbacks(this.mGIFRunnable);
}
public void onOffsetsChanged(float var1, float var2, float var3, float var4, int var5, int var6) {
super.onOffsetsChanged(var1, var2, var3, var4, var5, var6);
this.animGIF();
}
public void onSurfaceChanged(SurfaceHolder var1, int var2, int var3, int var4) {
super.onSurfaceChanged(var1, var2, var3, var4);
this.animGIF();
}
public void onVisibilityChanged(boolean var1) {
super.onVisibilityChanged(var1);
if(var1) {
this.animGIF();
} else {
LWPEngine.mGIFHandler.removeCallbacks(this.mGIFRunnable);
}
}
public void onSharedPreferenceChanged(SharedPreferences prefs,
String key) {
String gifBG = prefs.getString("custom_gif", "This file does not work");
//gifBG = prefs.getString("custom_gif", "Bad Image");
}
void tick() {
if((long)this.mWhen == -1L) {
this.mWhen = 0;
this.mStart = SystemClock.uptimeMillis();
} else {
if(this.mGIFDuration!=0) {
this.mWhen = (int)((SystemClock.uptimeMillis() - this.mStart) % (long)this.mGIFDuration);
}
}
}
}
}
I keep getting a null pointer exception - I'm guess because there's nothing there - so I'm obviously not setting the shared preferences right - or it's the inputstream...
Any help in getting a user selected image to the inputstream of the main LWPservice would be very helpful!
**Edit I should mention everything works up until I start the LWPService after selecting the GIF. It's when loading the lwp I get the error. using a static GIF in the drawable does work.
Thanks in advanced,
Marc
I figured out the answer in case anyone is curious.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(LWPEngine.this);
String gifBG = prefs.getString("custom_gif", "This file does not work");
needs to be:
SharedPreferences prefs = getApplicationContext().getSharedPreferences("custom_gif",MODE_PRIVATE);
String gifBG = prefs.getString("custom_gif", "This file does not work");
Also needed to change this in my SharedPreference class as well.
getSharedPreference needs context, and the way I had it before for was limiting the scope of the "global" capabilities of the SharedPreference method.
I hope that helps people!

Categories