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

Tuesday, 14 June 2016

Facebook Login using custom Button 


In this tutorial first of all if you are using eclipse then to download Facebook SDK from this website 
https://developers.facebook.com/docs/android/ and if you are using Android Studio then import dependencies in build.gradle file compile 'com.facebook.android:facebook-android-sdk:4.5.0'

To make the project in the https://developers.facebook.com/ and get the facebook id and add in to the string.xml file.

In XML file to add this code

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="50dp"
android:orientation="horizontal">
<Button
android:id="@+id/btn_facebook"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/fb_btn"
android:text="Facebook"
android:textAllCaps="false"
android:textColor="@android:color/white" />
</LinearLayout> 

In java file add this code

public class LoginActivity extends Activity implements View.OnClickListener {
Intent intent;
Button btn_facebook;
private CallbackManager mCallbackManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.login);
// Reference of Component
btn_facebook = (Button) findViewById(R.id.btn_facebook);
//Click Listener of Components
btn_facebook.setOnClickListener(this);
//Facebook login
List<String> permissions = new ArrayList<String>();
permissions.add("email");
FacebookSdk.sdkInitialize(this.getApplicationContext());
AppEventsLogger.activateApp(this);
mCallbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(mCallbackManager,
new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.d("Success", "Login");
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response
Log.v("LoginActivity", response.toString());
try {
String id = object.getString("id");
String name = object.getString("name");
//String email = object.getString("email");
// Toast.makeText(getApplicationContext(), "email ="+email, Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),Registration.class);
intent.putExtra("Fbname",name);
intent.putExtra("Fbid",id);
startActivity(intent);
overridePendingTransition(R.anim.open_next,R.anim.close_next);
finish();
} catch(Exception e){
e.printStackTrace();
}
}
});
//Toast.makeText(getApplicationContext(),""+response_code,Toast.LENGTH_LONG).show();
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday");
request.setParameters(parameters);
request.executeAsync();
}
@Override
public void onCancel() {
Toast.makeText(LoginActivity.this, "Login Cancel", Toast.LENGTH_LONG).show();
}
@Override
public void onError(FacebookException exception) {
Toast.makeText(LoginActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_facebook:
loginFacebook();
break;
}
}
public void loginFacebook(){
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile","email","user_birthday","user_friends"));
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(mCallbackManager.onActivityResult(requestCode, resultCode, data)) {
return;
}
}
}
In Android Manifest file you have to add the following meta tag
<activity    android:name="com.facebook.FacebookActivity"    android:label="@string/app_name"/>

<meta-data    android:name="com.facebook.sdk.ApplicationId"    android:value="@string/app_id" />
<meta-data    android:name="com.facebook.sdk.ApplicationName"    android:value="@string/app_name" />
<meta-data    android:name="com.facebook.sdk.WebDialogTheme"    android:resource="@android:style/Theme.Translucent.NoTitleBar" />

<provider    android:name="com.facebook.FacebookContentProvider"    android:authorities="com.facebook.app.FacebookContentProvider233936543368280"    android:exported="true" />