Browse Author: Ankita Deshmukh

Uploading image to Google Drive from Android

Below code will help to upload image directly to your google drive

private void saveFileToDrive() {

    final Bitmap image = mBitmapToSave;
    Drive.DriveApi.newDriveContents(getGoogleApiClient())
            .setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {

                @Override
                public void onResult(DriveApi.DriveContentsResult result) {

                    if (!result.getStatus().isSuccess()) {
                        Log.i("ERROR", "Failed to create new contents.");
                        return;
                    }

                    final DriveContents driveContents = result.getDriveContents();

                    new Thread() {
                        @Override
                        public void run() {
                            // write content to DriveContents
                            OutputStream outputStream = driveContents.getOutputStream();
                            // Write the bitmap data from it.
                            ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
                            image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
                            try {
                                outputStream.write(bitmapStream.toByteArray());
                            } catch (IOException e1) {
                                Log.i("ERROR", "Unable to write file contents.");
                            }
                            // Create the initial metadata - MIME type and title.
                            // Note that the user will be able to change the title later.
                            MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
                                    .setMimeType("image/jpeg").setTitle("Android Photo.png").build();
                            // Create an intent for the file chooser, and start it.
                            IntentSender intentSender = Drive.DriveApi
                                    .newCreateFileActivityBuilder()
                                    .setInitialMetadata(metadataChangeSet)
                                    .setInitialDriveContents(driveContents)
                                    .build(getGoogleApiClient());
                            try {
                                startIntentSenderForResult(
                                        intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
                            } catch (IntentSender.SendIntentException e) {
                                Log.i("ERROR", "Failed to launch file chooser.");
                            }
                        }
                    }.start();


                }
            });
}

Volley Library to make network connection from Android App

Android volley is a networking library was introduced to make networking calls much easier, faster without writing tons of code. By default all the volley network calls works asynchronously, so we don’t have to worry about using asynctask anymore.

Volley comes with lot of features. Some of them are

1. Effective request cache and memory management
2. Cancelling the requests

To use volley library just make below changes in your build.gradle file:

dependencies {
    compile 'com.mcxiaoke.volley:library:1.0.17'
}

Now add below code to make network calls

StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
               //get response 
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) { 
            }
        }) {
    @Override
    protected Map<String, String> getParams() {
           // send parameters for post
        return map;
    }

};

To set connection timeout add below code:
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
        10000,
        DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
        DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);





First onsite experience in my dream country … Australia

1610868_897869220236745_5334705507768285628_n 1622788_895949123762088_7174656833152448812_n 10885195_892058004151200_8731903846153530047_nDSC00545

It was my school days dream that I wanted to go Australia and now I still cant believe that I got an opportunity to work onsite for the first time in Australia and that too in the capital city CANBERRA. I was shocked as well as surprised when I came to know that Nanostuffs have chosen me for this opportunity .

The biggest hurdle for me to grab the opportunity was getting the passport as well the visa on time. Client had an immediate requirement and

I had to manage everything within 15 days. Finally I got the passport and sad thing was my visa got rejected for the first time. I was very sad when I came to know about it. but then Nishant & Ankita consoled me and we applied one more time. This time ball was in our court and visa was granted. I had to fly in next 2 days . It was again an amazing experience to manage everything in two days.

I was very excited and at same time had butterflies in my stomach as I was flying for the first time. I was quite nervous when I reached the client office on the first day. Everyone was new to me. But as days passed I got settled and everything worked smoothly. I loved the work culture of Australia.

People are very helpful and polite here. I never felt that I was new to this country. people are so caring & friendly.

I got an opportunity to visit Crazy, Picturesque Scenic, Modern, Dynamic city like SYDNEY. It was a dream come true experience. I got to see their National Animal Kangaroo and even Koalas. Even I visited Parliament house of Australia which is a rare experience. I got attached to Australia in very less time I never felt like coming back. 🙂

Overall it was a memorable experience for me and I thank Nishant and Ankita for giving me this wonderful opportunity at such a young age. Cheers Nanostuffs.

…. Ankita Deshmukh, Senior Android Developer, Nanostuffs.

 

How to Login via Facebook,get facebook friendlist and their details, post on friends wall and get newsfeeds details

How to Login with Facebook:

follow the below steps to add login via facebook:

step1: register app on developers.facebook.com

step 2: get the app_id , add it to strings file and add following code to manifest file:

<meta-data

android:name=”com.facebook.sdk.ApplicationId”

android:value=”@string/app_id” />

//add meta-data inside appication tag.

<activity android:name=”com.facebook.LoginActivity” >
</activity>

step 3: Download latest facebooksdk and import it as project in your project

step 4: add following code onclick of login with facebook button:

try {

PackageInfo info = getPackageManager().getPackageInfo( “package_name”, PackageManager.GET_SIGNATURES);

for (Signature signature : info.signatures)

{

MessageDigest md = MessageDigest.getInstance(“SHA”); md.update(signature.toByteArray());

Log.d(“KeyHash:”, Base64.encodeToString(md.digest(), Base64.DEFAULT));

}

} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
} //

 

//Get keyhash from above code and add it to developers.facebook in your project
session1 = Session.getActiveSession();

if (session1 == null)

{ session1 = new Session(Login.this);

Session.setActiveSession(session1);

if (session1.getState().equals( SessionState.CREATED_TOKEN_LOADED))

{

session1.openForRead(new Session.OpenRequest(Login.this) .setCallback(statusCallback));

access_token = session1.getAccessToken();

}

}

if (!session1.isOpened() && !session1.isClosed())

{

session1.openForRead(new Session.OpenRequest(Login.this) .setCallback(statusCallback));

access_token = session1.getAccessToken();

} else

{

Session.openActiveSession(Login.this, true, statusCallback);

access_token = session1.getAccessToken();

}

}

/// Add this method to your code:

private Session.StatusCallback statusCallback = new Session.StatusCallback() {
@Override public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

public void onCompleted(GraphUser user, Response response) {
if (user != null) {

user.getId();

fbid = user.getId();

fbname = user.getName();
} } });
} }
};

 

//override this method of activity:

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

super.onActivityResult(requestCode, resultCode, data);

Session.getActiveSession() .onActivityResult(this, requestCode, resultCode, data);

}

 

–>How to Get Facebook friendlist:

Create async task and use below url to get facebookfriend list:

https://graph.facebook.com/me/friends?access_token=”session access_token”

Note: parse the data using Json .

–>How to share on friends wall:

add below code to share on friends wall:

private void publishFeedDialog(int position) {

try{

Bundle params = new Bundle();

params.putString(“message”,”YOUR MESSAGE” );

params.putString(“to”,”Friends userid”);

WebDialog feedDialog = (   new WebDialog.FeedDialogBuilder(Context,  Session.getActiveSession(),    params))                .setOnCompleteListener(null)   .build();

feedDialog.show();

} catch(Exception e){

e.printStackTrace(); }

}

 

–> How to Get NewsFeed:

Use below url to get newsfeed:

link: https://graph.facebook.com/me/home?access_token=access_token

Note: use Json parsing to retrive details of each newsfeed.

 

Loading image from url using AQuery

Download android-query.jar from below link:

http://www.java2s.com/Code/Jar/a/Downloadandroidqueryfull0243jar.htm

 

Add following code where you want to load image :

public ImageLoader imageLoader;

imageLoader = new ImageLoader(this);

AQuery androidAQuery=new AQuery(getApplicationContext());

androidAQuery.id(ImageView).image(url, true, true, 100,default_pic);

 

Note: if you dont want to store image in cache memory set true parameters to false.