Sunday, 6 May 2018

How to add Progress bar until image not Showing in Android

 - In Java file add following code
     //To set value in components
          if (image != null && !image.isEmpty()) {
          Picasso.with(ProfileActivity.this).load(AppConstant.TAG_Image_Base_Path + image)
          .into(image_student, new ImageLoadedCallback(progressBar) {
            @Override
            public void onSuccess() {
             if (progressBar != null) {
                 progressBar.setVisibility(View.GONE);
                  }
                }
               });
             } else {
                image_student.setImageResource(R.mipmap.ic_launcher);
             }

  public class ImageLoadedCallback implements com.squareup.picasso.Callback {
        ProgressBar progressBar;
        public ImageLoadedCallback(ProgressBar progBar) {
            progressBar = progBar;
        }

        @Override
        public void onSuccess() {
        }

        @Override
        public void onError() {
        }
    }

- In main.xml Add Following Code
 
    <RelativeLayout
     android:layout_width="65dp"
     android:gravity="center"
     android:layout_gravity="bottom"
     android:layout_height="65dp">

     <ImageView
      android:id="@+id/image_student"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent" />

     <ProgressBar
      android:id="@+id/progressBar"
      style="?android:attr/progressBarStyleSmall"
      android:layout_width="30dp"
      android:layout_centerHorizontal="true"
      android:layout_centerVertical="true"
      android:layout_height="30dp"
      android:visibility="gone" />

     </RelativeLayout>

How to Upload Image using Retrofit in Android

- First To add in ApiInterface class
- APIInterface.java
  public interface APIInterface {
    //For Edit Profile
    @Multipart
    @POST("editprofile")
    Call<GetSetData> getUpdateProfile(@Part("rollno") RequestBody rollno, @Part("address") RequestBody address,@Part("fullname") RequestBody fullname, @Part MultipartBody.Part image);
  }

- ApiClient.java
   public class ApiClient {
   public static final String BASE_URL = "http://test.com/api/";
    private static Retrofit retrofit = null;

    public static Retrofit getClient() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        if (retrofit==null) {
            retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create()).build();
        }
        return retrofit;
      }
   }

- Give Permission in AndroidManifest.xml
 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

- Add Following code in build.gradle
   compile 'com.squareup.retrofit2:retrofit:2.0.2'
   compile 'com.squareup.retrofit2:converter-gson:2.0.2'
   compile 'com.squareup.okhttp3:okhttp:3.4.1'
   compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'

- To Call Following Method on Click of Select image Button
   private void selectImage() {
        final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};
        AlertDialog.Builder builder = new AlertDialog.Builder(ProfileActivity.this);
        builder.setTitle("Add Photo!");
        builder.setCancelable(false);
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (items[item].equals("Take Photo")) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(intent, 100);
                } else if (items[item].equals("Choose from Library")) {
                    Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(
                            Intent.createChooser(intent, "Select File"), 200);
                } else if (items[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 100) {
                Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
                File destination = new File(Environment.getExternalStorageDirectory(),
                        System.currentTimeMillis() + ".jpg");
                selectedImagePath = destination.getAbsolutePath();
                FileOutputStream fo;
                try {
                    destination.createNewFile();
                    fo = new FileOutputStream(destination);
                    fo.write(bytes.toByteArray());
                    fo.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                image_profile.setImageBitmap(thumbnail);

            } else if (requestCode == 200) {
                Uri selectedImageUri = data.getData();
                String[] projection = {MediaStore.MediaColumns.DATA};
                CursorLoader cursorLoader = new CursorLoader(TestActivity.this, selectedImageUri, projection, null, null, null);
                Cursor cursor = cursorLoader.loadInBackground();
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
                cursor.moveToFirst();
                selectedImagePath = cursor.getString(column_index);

                Bitmap bm;
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(selectedImagePath, options);
                final int REQUIRED_SIZE = 200;
                int scale = 1;
                while (options.outWidth / scale / 2 >= REQUIRED_SIZE
                        && options.outHeight / scale / 2 >= REQUIRED_SIZE)
                    scale *= 2;
                options.inSampleSize = scale;
                options.inJustDecodeBounds = false;
                bm = BitmapFactory.decodeFile(selectedImagePath, options);

                try {
                    ExifInterface ei = new ExifInterface(selectedImagePath);
                    int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
                    switch (orientation) {
                        case ExifInterface.ORIENTATION_ROTATE_90:
                            bm = rotateImage(bm, 90);
                            break;
                        case ExifInterface.ORIENTATION_ROTATE_180:
                            bm = rotateImage(bm, 180);
                            break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                image_profile.setImageBitmap(bm);
            }
        }
    }

    public static Bitmap rotateImage(Bitmap source, float angle) {
        Bitmap retVal;

        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        retVal = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
        return retVal;
    }

- To Add following code in Java class
     private void updateProfileData(String full_name, String address) {
        // Showing progress dialog
        pDialog = new ProgressDialog(ProfileActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

        //creating a file
        File file = new File(selectedImagePath);

        //creating request body for file
        RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
        MultipartBody.Part imagenPerfil = MultipartBody.Part.createFormData("image1", file.getName(), requestFile);

        // add another part within the multipart request
        RequestBody req_roll_no = RequestBody.create(MediaType.parse("text/plain"), roll_no);
        RequestBody req_address = RequestBody.create(MediaType.parse("text/plain"), address);
        RequestBody req_full_name = RequestBody.create(MediaType.parse("text/plain"), full_name);

        APIInterface apiService = ApiClient.getClient().create(APIInterface.class);
        Call<GetSetData> call = apiService.getUpdateProfile(req_roll_no, req_address, req_full_name, imagenPerfil);
        call.enqueue(new Callback<GetSetData>() {
            @Override
            public void onResponse(Call<GetSetData> call, Response<GetSetData> response) {
                String str_success = response.body().getSuccess();
                if (pDialog.isShowing()) {
                    pDialog.dismiss();
                }
                if (str_success.equals("1")) {
                    Toast.makeText(TestActivity.this, "Profile Update Successfully", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<GetSetData> call, Throwable t) {
                // Log error here since request failed
                if (pDialog.isShowing()) {
                    pDialog.dismiss();
                }
                Toast.makeText(getApplicationContext(), "Some problem occure", Toast.LENGTH_SHORT).show();
            }
        });
    }

How to add Recyclerview in android

- Add following line in build.gradle

 compile 'com.android.support:recyclerview-v7:26.+'

- Add following line in main.xml
 <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.RecyclerView
       android:id="@+id/recycle_home_work"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content">
    </android.support.v7.widget.RecyclerView>
 </LinearLayout>

- Add following code in MainActivity.class

  RecyclerView recycle_test = (RecyclerView) findViewById(R.id.recycle_test);
  //For Linear Layout Manager for only Listview(Item in List)
  TestAdapter testAdapter = new TestAdapter(TestActivity.this, list_array);
  LinearLayoutManager llm = new LinearLayoutManager(TestActivity.this);
  llm.setOrientation(LinearLayoutManager.VERTICAL);
  recycle_test.setLayoutManager(llm);
  recycle_test.setAdapter(testAdapter);
  testAdapter.notifyDataSetChanged();

  //For Layout Manager for only Gridview(Item in Grid)
  TestAdapter testAdapter = new TestAdapter(TestActivity.this, list_array);
  RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager (TestActivity.this, 2);
  recycle_test.setLayoutManager(mLayoutManager);
  recycle_test.setAdapter(testAdapter);
  testAdapter.notifyDataSetChanged();


//Adapter
public class TestAdapter extends RecyclerView.Adapter<TestAdapter.MyViewHolder> {
        public Context context;
        List<PhotoResponseData> array_list;

        public TestAdapter(Context context, List<PhotoResponseData> array_list) {
            this.context = context;
            this.array_list = array_list;
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.text_photo, parent, false);

            final MyViewHolder holder = new MyViewHolder(itemView);
            return new MyViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(final MyViewHolder holder, final int position) {
            String image = array_list.get(position).getImagename();
            if (image != null && !image.isEmpty()) {
                Picasso.with(context).load(AppConstant.TAG_Image_Photo + image).placeholder(R.mipmap.ic_launcher).into(holder.image_photo);
            } else {
                holder.image_photo.setImageResource(R.mipmap.ic_launcher);
            }
        }

        @Override
        public int getItemCount() {
            return array_list.size();
        }

        @Override
        public int getItemViewType(int position) {
            return position;
        }

        public class MyViewHolder extends RecyclerView.ViewHolder {
            ImageView image_photo;
            public MyViewHolder(View convertView) {
                super(convertView);
                image_photo = (ImageView) convertView.findViewById(R.id.image_photo);
            }

        }
    }

How to Download pdf from web in Android

- on Click of download button to add following code

   String pdf_url = array_list.get(position).getpdf();
   if (pdf_url != null && !pdf_url.isEmpty()) {
         new FileDownloading().execute();
   } else {
        Toast.makeText(context, "PDF url is not found",Toast.LENGTH_LONG).show();
   }

//To Add Following Code outside of onCreate() Method.

 class FileDownloading extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            mProgressDialog = new ProgressDialog(TestActivity.this);
            mProgressDialog.setMessage("Downloading file..");
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
          String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
            File folder = new File(extStorageDirectory, "Test/Testwork");
            folder.mkdirs();
            File file = new File(folder, pdf_url);
            try {
                file.createNewFile();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            Downloader.DownloadFile("http://test.domainname.com/test/assets/testpdf/" + pdf_url, file);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
           if (mProgressDialog.isShowing()) {
                mProgressDialog.dismiss();
           }

           Toast.makeText(TestActivity.this, "Download Completed Successfully", Toast.LENGTH_LONG).show();
            showPdf();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mProgressDialog != null)
            mProgressDialog.dismiss();
    }

//To Show Downloaded PDF

 public void showPdf() {
        File file = new File(Environment.getExternalStorageDirectory() + "/Test/Testwork/" + pdf_url);
        PackageManager packageManager = getPackageManager();
        Intent testIntent = new Intent(Intent.ACTION_VIEW);
        testIntent.setType("application/pdf");
        List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(file);
        intent.setDataAndType(uri, "application/pdf");
        startActivity(intent);
    }

Saturday, 5 May 2018

How to give permission programatically in android


- To call isStoragePermissionGranted method in OnCreate()

public boolean isStoragePermissionGranted() {

if (Build.VERSION.SDK_INT >= 23) {            
 if(checkSelfPermission(android.Manifest.permission.
WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED{   
    Log.v("PDF", "Permission is granted");      
    return true;            
} else {           
    Log.v("PDF", "Permission is revoked");            
    ActivityCompat.requestPermissions(this, new String[]  {Manifest.permission.WRITE_EXTERNAL_STORAGE},1); 
    return false;            
  }       
} else {
    //permission is automatically granted on sdk<23 upon installation            
    Log.v("PDF", "Permission is granted");     
    return true;      
  }   
}


Friday, 23 February 2018

How to Use Custom Navigation Drawer in Android

First of all, to add DrawerLayout in main.xml file and inside drawer layout to add lable or listview.

//main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 
 xmlns:android="http://schemas.android.com/apk/res/android" 
 xmlns:tools="http://schemas.android.com/tools" 
 android:id="@+id/drawerLayout"     
 android:layout_width="match_parent"     
 android:layout_height="match_parent"     
android:orientation="vertical">
 
<LinearLayout     
   android:id="@+id/container" 
   android:layout_width="match_parent"     
   android:layout_height="fill_parent" 
   android:orientation="vertical" 
   android:weightSum="1">

    <include layout="@layout/layout_toolbar" />

    <FrameLayout         
     android:id="@+id/content_frame" 
     android:layout_width="match_parent" 
     android:layout_height="fill_parent">

 
    //Include layout of main screen 
       <include
           android:id="@+id/home" 
           layout="@layout/fragment_home"             
           android:layout_width="fill_parent"             
           android:layout_height="fill_parent" />
    </FrameLayout>
</LinearLayout>
 
<LinearLayout     
  android:layout_width="120dp"     
  android:layout_height="match_parent" 
  android:layout_gravity="left|start"
  android:orientation="vertical">
 
 //Add here lable or listview you want 

 
<LinearLayout 
  android:id="@+id/linear_dashboard"     
  android:layout_width="fill_parent"   
  android:layout_height="wrap_content" 
  android:layout_marginBottom="15dp" 
  android:layout_marginTop="20dp" 
  android:orientation="vertical">

    <ImageView 
      android:layout_width="fill_parent" 
      android:layout_height="30dp"         
      android:layout_gravity="center" 
      android:src="@drawable/ic_launcher" />

    <TextView 
      android:id="@+id/text_dashboard" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_marginTop="5dp" 
      android:gravity="center" 
      android:text="Dashboard" 
      android:textColor="@color/white" 
      android:textSize="14dp" />
    </LinearLayout>
 </LinearLayout>

</android.support.v4.widget.DrawerLayout>
 
//layout_toolbar.xml 
 
<?xml version="1.0" encoding="utf-8"?> 
<android.support.v7.widget.Toolbar  
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/toolbar" 
   android:layout_width="match_parent" 
   android:layout_height="40dp"
   android:background="@color/action_back">

    <LinearLayout 
      android:layout_width="fill_parent"
      android:layout_height="wrap_content">
 
       <TextView         
          android:layout_width="fill_parent"
          android:gravity="center" 
          android:text="App Name"
          android:textColor="@color/white"  
          android:layout_height="wrap_content">
       </TextView>
   </LinearLayout>
</android.support.v7.widget.Toolbar> 

//fragment_home.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" 
   android:background="@color/white">

    <LinearLayout
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent" 
        android:weightSum="1">
 
         <TextView 
            android:layout_width="fill_parent"
            android:gravity="center"            
            android:text="App Name"   
            android:textColor="@color/white"
            android:layout_height="wrap_content">
        </TextView> 
    </LinearLayout> 
</LinearLayout>
 
Now, In java add following code for Navigation Drawer
 
public class MainActivity extends AppCompatActivity { 

  //First to make variable of Components 
  Toolbar toolbar;
  public static DrawerLayout drawerLayout;
  private ActionBarDrawerToggle drawerToggle;
 
 @Overrideprotected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
 
    //First to take Reference of Components
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    spinner_menu = (Spinner) findViewById(R.id.spinner_menu);
    drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout); 

    // To add Following method in your class
    setSupportActionBar(toolbar);
    initDrawerLayout();
 }
 
 private void initDrawerLayout() {
    drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
            R.string.drawer_open, R.string.drawer_close) {

        @Override 
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
        }

        @Override 
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);

        }
    };
    drawerToggle.setDrawerIndicatorEnabled(false);
    Drawable drawable = ResourcesCompat.getDrawable(getResources(), 
     R.drawable.ic_drawer,getTheme());
    drawerToggle.setHomeAsUpIndicator(drawable);
    drawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
        @Override        public void onClick(View v) {
            if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
                drawerLayout.closeDrawer(GravityCompat.START);
            } else {
                drawerLayout.openDrawer(GravityCompat.START);
            }
        }
    });
    drawerLayout.setDrawerListener(drawerToggle);
}

@Overrideprotected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    drawerToggle.syncState();
}

@Overridepublic void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    drawerToggle.onConfigurationChanged(newConfig);
}

 
} 
 
 
 
 

Tuesday, 14 November 2017

How to use Retrofit Api in Android

1) First of all to add this dependencies in your app/build.gradle file 
 
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2' 
compile 'com.squareup.okhttp3:okhttp:3.4.1' 
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
 
2) then make one java class name Apiclient to declare api base link for getting data 
and this link is demo link so paste your link here 

public class ApiClient {
    public static final String BASE_URL = "http://domainname.com/folder";

    private static Retrofit retrofit = null;


    public static Retrofit getClient() {

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor)
                                                    .build();

        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

3) To make one interface to declare the api name and param list and to use this link 
jsonschema2pojo.org for making pojo class of your response  
 
 
public interface APIInterface {

    //For Login    @GET("login")
    Call<GetSetMethod> getLoginResponse(@Query("username") String username,  
@Query("password") String password);

} 

4) Use all method and class in your main class where you want to get response for 
display.here is demo class for your reference 
 private void loginProcessWithRetrofit(final String username, String password) {
    // Showing progress dialog    pDialog = new ProgressDialog(LoginActivity.this);
    pDialog.setMessage("Please wait...");
    pDialog.setCancelable(false);
    pDialog.show();

    APIInterface apiService =
            ApiClient.getClient().create(APIInterface.class);

    Call<GetSetMethod> call = apiService.getLoginResponse(username, password);
    call.enqueue(new Callback<GetSetMethod>() {
        @Override        public void onResponse(Call<GetSetMethod> call, 
            Response<GetSetMethod> response) {
            Log.e("List size", ""+response.raw().request().url());
            String str_success = response.body().getSuccess();
            if (pDialog.isShowing()) {
                pDialog.dismiss();
            }
            if (str_success.equals("1")) {
                //Get Login Response 
                ResponseData responseData = response.body().getResponseData();
                String user_id = responseData.getId();
                String auth_key = responseData.getAuthkey();
                String app_type = responseData.getApp();
                        

                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.open_next,R.anim.close_next);
                finish();
            } else {
                Toast.makeText(getApplicationContext(), 
              "Username or Password does not Matched", Toast.LENGTH_SHORT).show();
            }
        }

        @Override 
            public void onFailure(Call<GetSetMethod> call, Throwable t) {
            // Log error here since request failed 
               if (pDialog.isShowing()) {
                pDialog.dismiss();
            }
            Toast.makeText(getApplicationContext(), "Login Failed", 
          Toast.LENGTH_SHORT).show();
        }
    });
}