Thursday 31 May 2018

Load Image from gallery

@Overridepublic void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    Bitmap bitmap = null;
    String selectedImagePath = null;
 
   if (resultCode == RESULT_OK && requestCode == GALLERY_PICTURE) {
      if (data != null) {
        Uri selectedImage = data.getData();
        selectedImagePath = getPath(selectedImage);
        String[] filePath = {MediaStore.Images.Media.DATA};
        Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
        c.moveToFirst();
        int columnIndex = c.getColumnIndex(filePath[0]);
        selectedImagePath = c.getString(columnIndex);
        c.close();
        if (selectedImagePath != null) {
            Bitmap bm = BitmapFactory.decodeFile(selectedImagePath);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object            byte[] byteArrayImage = baos.toByteArray();
            String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
            byte[] decodeResponse = Base64.decode(encodedImage, Base64.DEFAULT | Base64.NO_WRAP);
            bitmap = BitmapFactory.decodeByteArray(decodeResponse, 0, decodeResponse.length); // load            bitmap = Bitmap.createScaledBitmap(bitmap, 400, 400, false);
            iv_profile.setImageBitmap(bitmap);
            imageUpload(selectedImagePath);
        }
    } 
}

Wednesday 23 May 2018

Toolbar search view implementation in fragment

menu_action_search.xml-

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.activities.MyActivity">
    <item
        android:id="@+id/action_search"
        android:icon="@drawable/search"
        android:orderInCategory="100"
        android:title="@string/action_search"
        app:actionViewClass="android.widget.SearchView"
        app:showAsAction="always" />

</menu>



  Class- MyFragment.java

  private MyFilterAdpater mAdapter;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        mAdapter = new MyFilterAdpater(getContext(), mArrayList);
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onPrepareOptionsMenu(menu);
        inflater.inflate(R.menu.menu_action_search, menu);
        MenuItem item = menu.findItem(R.id.action_search);
        searchView = (SearchView) MenuItemCompat.getActionView(item);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                searchView.clearFocus();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                final List<MyModel> filteredList = filter(mArrayList, s.toLowerCase());
                mAdapter.setFilter(filteredList);
                return true;
            }
        });

    }

      private List<MyModel.Data> filter(List<MyModel.Data> models, String query) {
        query = query.toLowerCase();
        final List<MyModel.Data> filteredList = new ArrayList<>();
        for (MyModel model : models) {
            final String text = (model.getCustmorName()).toLowerCase();
            if (text.contains(query)) {
                filteredList.add(model);
            }
        }
        return filteredList;
    }

Class- MyFilterAdpater

   private ArrayList<MyModel>  mResultList;

   public void setFilter(List<MyModel.Data> model) {
        mResultList = new ArrayList<>();
        mResultList.addAll(model);
        notifyDataSetChanged();
    }

Thursday 17 May 2018

Download attached file from url in sdcard or device internal memory in android


Utils class-

  public File createFileDirectory(Context context) {
        if (Utils.isSdCardAvailable() && Utils.isExternalStorageWritable()) {
            directory = new File(Utils.getDirectory());
        } else {
            ContextWrapper cw = new ContextWrapper(context);
            directory = cw.getDir(cw.getString(R.string.folder_name), Context.MODE_PRIVATE);
        }
        return directory;
    }

    public static String getDirectory() {
        String dirPath = null;
        try {
            dirPath = Environment.getExternalStorageDirectory() + subRootFolder;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dirPath;
    }

    /* Checks if external storage is available for read and write */
    public static boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }

    /* Checks if external storage is available for read and write */
    public static boolean isSdCardAvailable() {
        return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    }


 MyActivity implements DownloadingAsync.IDownloadAttachment-

    File directory = null;
    String savingPath = null;


    boolean isFileAlreadyDownloaded(String mFile) {
        if (mFile != null) {
            Utils utils = new Utils();
            directory = utils.createFileDirectory(this);
            savingPath = directory + File.separator + mFile;
            File file = new File(savingPath);
            if (file.exists()) {
                return true;
            }
        }
        return false;
    }


    String fileUrl = UrlFactory.IMG_BASEURL +mFilteredList.get(position).getDownload_path();
    String file_name = mFilteredList.get(position).getFile_name();

     if (isFileAlreadyDownloaded(file_name)) {
                        Toast.makeText(getApplicationContext(),  MyActivity.this.getString(R.string.file_already_downloaded), Toast.LENGTH_LONG).show();
                    } else {
                        if (Build.VERSION.SDK_INT >= 23) {
                            if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                    == PackageManager.PERMISSION_GRANTED) {
                                new DownloadingAsync(MyActivity.this, file_name, fileUrl, directory).execute();
                            } else {
                                ActivityCompat.requestPermissions(MyActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                            }
                        } else {
                            new DownloadingAsync(MyActivity.this, file_name, fileUrl, directory).execute();
                        }
      }


    @Override
    public void isAttachmentDownloaded(String message) {
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
        myDealsListAdapter.notifyDataSetChanged();
    }


public class DownloadingAsync extends AsyncTask<Void, Void, Void> {
    private static final String TAG = "Download Task";
    private Context context;
    private String file_name;
    private String downloadUrl;
    private File outputFile = null;
    private long total = 0;
    private int contentLength = 0;
    private File mFileDirectory;
    private IDownloadAttachment iDownloadAttachment;
    private String deliverMessage = null;
    private ProgressDialog dialog;

    public DownloadingAsync(Context context, String file_name, String downloadUrl, File directory) {
        this.context = context;
        this.file_name = file_name;
        this.downloadUrl = downloadUrl;
        this.mFileDirectory = directory;
        iDownloadAttachment = (IDownloadAttachment) context;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = new ProgressDialog(context);
        dialog.setMessage("Downloading started, please wait.");
        dialog.show();
    }

    @Override
    protected void onPostExecute(Void result) {

        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        if (outputFile != null) {
            iDownloadAttachment.isAttachmentDownloaded(deliverMessage);
      /*    MimeTypeMap map = MimeTypeMap.getSingleton();
            String ext = MimeTypeMap.getFileExtensionFromUrl(file_name);
            String type = map.getMimeTypeFromExtension(ext);

            if (type == null)
              //  type = ";

            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri data = Uri.fromFile(outputFile);

            intent.setDataAndType(data, type);

            context.startActivity(intent); */
        }
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        try {
            String savingPath = null;
            URL url = new URL(downloadUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            //connect
            urlConnection.connect();
            switch (urlConnection.getResponseCode()) {
                case HttpURLConnection.HTTP_OK: {
                    contentLength = urlConnection.getContentLength();

                    //If File is not present create directory
                    if (!mFileDirectory.exists()) {
                        mFileDirectory.mkdir();
                    }
                   /* File parent = directory.getParentFile();
                    if (parent != null)
                        parent.mkdirs();*/

                    savingPath = mFileDirectory + File.separator + file_name;
                    outputFile = new File(mFileDirectory, file_name);

                    /**
                     * CHECK INCOMPLETE DOWNLOADED FILE
                     * IF TRUE THE DELETE THE INCOMPLETE FILE AND START DOWNLOAD SAME FILE AGAIN
                     */
                    //**********************************************
                    File file = new File(savingPath);
                    if (file.exists()) {
                        if (file.length() != contentLength) {
                            if (outputFile.exists()) {
                                outputFile.delete();
                                System.out.println(context.getString(R.string.incomplete_download_file_deleted));
                            }
                        } else {
                            contentLength = 0;
                            deliverMessage = context.getString(R.string.file_already_downloaded);
                            return null;
                        }
                    }
                    //**********************************************
                    try {
                        outputFile.createNewFile();
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    try {
                        InputStream inputStream = urlConnection.getInputStream();
                        FileOutputStream outputStream = new FileOutputStream(outputFile);
                        int bytesRead = -1;
                        byte[] buffer = new byte[4096];
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            total += bytesRead;
                            outputStream.write(buffer, 0, bytesRead);
                        }
                        outputStream.flush();
                        outputStream.close();
                        inputStream.close();

                    } catch (OutOfMemoryError e) {
                        // TODO: handle exception
                    }

                    if (total == contentLength) {
                        deliverMessage = context.getString(R.string.file_download_completed);
                    }
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            Log.d(TAG, "Error : IOException " + e);
            e.printStackTrace();
        } catch (Exception e) {
            Log.d(TAG, "Error: Exception " + e);
        }

        return null;
    }

    public interface IDownloadAttachment {
        void isAttachmentDownloaded(String message);
    }
}

Add .gitignore file in android studio project

When we compile android project then few auto generated file automatically generated.
These auto generated files are not required during code commit. We can ignore auto
generated file from android project using below .gitignore file.

Follow below steps to add .gitignore file in your git project directory.

1. Open notepad and copy paste below text.
2. Save it using file name like abc.gitignore.
3. Put .gitignore file at root directory of project. After that clean your project.


#built application files
*.apk
*.ap_

# files for the dex VM
*.dex

# Java class files
*.class

# built native files (uncomment if you build your own)
# *.o
# *.so

# generated files
bin/
gen/

# Ignore gradle files
.gradle/
build/

# Local configuration file (sdk path, etc)
local.properties

# Windows thumbnail db
Thumbs.db

# OSX files
.DS_Store

# Eclipse project files
.classpath
.project

# Android Studio
*.iml
.idea
#.idea/workspace.xml - remove # and delete .idea if it better suit your needs.
.gradle
build/

#NDK
obj/