Sunday 23 November 2014

removing and add one value in array saved in Parse table with Parse.com

Hello all,

In the Previous Post ,I have explained how to add the array and Parse File in Parse table

Now let's move to another step in Parse.com series which is to remove one value from the array and also adding one value in an array which is saved in Parse table 

The difference : in the Previous Post I have explained to add the whole array in Parse table , But In this post I am going to explain how to modify (add/remove) the array which is saved in Parse DB

Let's make a Parse table named "channel" having  usersArray (datatype : array) column 

Now first we will add a value in the usersArray in "channel" . For this we have to follow following steps: 
1: Assume an List<String> list1= new ArrayList<String>
2: Check usersArray  is null or not
3: Assign the value of usersArray to list1
4: Check that list1 contains that value (which is need to be added)
5: If not Add the value in list1 .
6: save the list1 in usersArray in channel table.

For this please check the below code to add one value in array :

                 List<String> list11 =  new ArrayList<String>();
String object_id = "123456"; //change this according to your need.
ParseQuery<ParseObject> pQuery = ParseQuery.getQuery("Channel");
pQuery.whereEqualTo("objectId",object_id);
pQuery.findInBackground(new FindCallback<ParseObject>() {

@Override
public void done(List<ParseObject> list, ParseException e) {
if (e==null) {
if (list.size()>0) {
ParseObject p = list.get(0);
if (p.getList("usersArray")!=null) {
list11 =  p.getList("usersArray");
}
else
{
list11= null;
}

if (list11!=null) {
if (!list11.contains(user_id)) {
list11.add(user_id);
}
                                                }
if (list11!=null) 
p.put("usersArray", list11);
else
p.put("usersArray",null );
   p.saveInBackground(new SaveCallback() {

@Override
public void done(ParseException arg0) {
                     Toast.makeText(mActivity,"done",Toast.LENGTH_LONG).show();
}
});
}
}
}
}

});


Now let's move to remove one value from the usersArray in "channel" . For this we have to follow following steps: 
1: Assume an List<String> list1= new ArrayList<String>
2: Check usersArray  is null or not
3: Assign the value of usersArray to list1
4: Check that list1 contains that value (which is need to be added)
5: If yes remove the value from list1 .
6: save the list1 in usersArray in channel table again.

For this please check the below code to remove one value from saved array :

  final List<String> list11 =  new ArrayList<String>();
String object_id = "123456"; //change this according to your need.
ParseQuery<ParseObject> pQuery = ParseQuery.getQuery("Channel");
pQuery.whereEqualTo("objectId",object_id);
pQuery.findInBackground(new FindCallback<ParseObject>() {

@Override
public void done(List<ParseObject> list, ParseException e) {
if (e==null) {
if (list.size()>0) {
ParseObject p = list.get(0);
if (p.getList("usersArray")!=null) {
list11 =  p.getList("usersArray");
}
else
{
list11= null;
}

if (list11!=null) {
if (list11.contains(user_id)) {
list11.remove(user_id);
}
                                       }
if (list11!=null) 
p.put("usersArray", list11);
else
p.put("usersArray",null );
p.saveInBackground(new SaveCallback() {

@Override
public void done(ParseException arg0) {
              Toast.makeText(mActivity,"done",Toast.LENGTH_LONG).show();
}
});
}
}}
});

That's all..for remove and add one value from/to the array which is saved in Parse table with Parse.com.
In above code I have applied condition on the basis of objectId  you have to change according to your need.
Please leave any comment if you have any query.Thanks...



Sunday 16 November 2014

adding array and Parse file in Parse table with Parse.com

Hello all,

In the Previous Blog I have explained to add and remove different data types in Parse table.

Now again adding the next step in the Parse.com series I am sharing the code to add array in Parse table also in the post I will share the code to add the Parse File in Parse table .

Let's make a table named "channel" having following columns with the data types :

1.  pic (datatype: File(parse file))
2.  usersArray (datatype : array)

Lets us assume the List<String>  mAryUsers =  new ArrayList<String>(); ,it is used to save the array of users.
Lets  us assume the  byte [] imagearray = null; it is used to upload the pic in Parse table

Note:  -> image ,pdf etc. will upload as a Parse File in Parse table  in the form of  byte [] ,Here I am uploading an image picked from gallery ,then change it to byte[] then will upload to the parse table(code below)

-> mAryUsers  will have the array of name of users which will save in array column in Parse table .

Lets take a look on the code to add the byte []  and  List<String>  in the columns pic (datatype: File(parse file)) and usersArray (datatype : array)

    final ParseObject testObject = ParseObject.create("channel");

if (mAryUsers!=null) {

 testObject.put("usersArray",mAryUsers);//ADDING ARRAY IN "usersArray" column
}

if (imagearray!=null) {
final ParseFile  file = new ParseFile("123.png",imagearray);
                file.saveInBackground(new SaveCallback() {

@Override
public void done(ParseException arg0) {
testObject.put("pic", file);//ADDING IMAGE IN "pic" column
testObject.saveInBackground();
}
});
       
}
              testObject.saveInBackground(new SaveCallback() {

@Override
public void done(ParseException e) {
  Log.e("Exception", "get: " +e);
         if (e == null) {
 Toast.makeText(getApplicationContext(),"Channel Added                Succesfully",Toast.LENGTH_LONG).show();
  }
                                  else {
   
        Toast.makeText(getApplicationContext(),"Something went wrong.Please try again later",Toast.LENGTH_LONG).show();
  }
}
});

For more info you can  see this: Add array in parse Table in right way

That's all for adding the Parse file and array in Parse table with the help of Parse.com.






Add different types of data in Parse Table and fetch them from the Parse table in Parse.com

Hello all,

In the previous post I have explained how to signup and login as a Parse User in Parse Table with the help of Parse.com sdk

Now I am going to add one another tutorial in Parse.com series.

Today I am going to share the code to add different types of data(string,int,boolean) in the Parse Table and then explains the code to fetch them.

First you have to create a table in Parse database manually,then add the columns with different data types according to your need

I have made a Parse Table named "channel" and add the following columns  in it :

1. name(String)
2. isPrivate(boolean)
3. maxSize(int)

Now below is the code to add the values to the Parse table(here  "channel") in runtime:

boolean b_privacy = false;
String s_name = "XYZ";
int max_size = 50;

 final ParseObject testObject = ParseObject.create("channel");

                 testObject.put("isPrivate",b_privacy);
testObject.put("maxSize",max_size);
 testObject.put("name",s_name);
 testObject.saveInBackground(new SaveCallback() {

@Override
public void done(ParseException e) {

 if (e == null) {
Toast.makeText(getApplicationContext(),"Channel Added            Succesfully",Toast.LENGTH_LONG).show();
 } 
                                        else {
Toast.makeText(getApplicationContext(),"Something went wrong.Please try again later",Toast.LENGTH_LONG).show();

   }
}
});

After that lets move to the second part of the post that is to fetch the data from the Parse table in runtime:

Let's us assume to fetch the data from the "channel" table.Now we have to fetch the name(String) , isPrivate (boolean) and  maxsize(int).

Here is the code to fetch the data from "channel" table:

Note: Here I am fetching the data on the basis of objectId.

            ParseQuery<ParseObject> query = ParseQuery.getQuery("channel");
   query.whereEqualTo("objectId",objid);
   query.findInBackground(new FindCallback<ParseObject>() {
       public void done(List<ParseObject> userList, ParseException e) {
       
                if (e == null) {
          
            Log.d(">>",">>"+userList.size());
            if (userList.size()>0) {

        ParseObject p = userList.get(0);

String s_name = p.getString("name");
boolean is_private = p.getBoolean("isPrivate");
int max_size =p.getInt("maxSize");

        }} 
              else {
               // error
            Log.d(">>",">>"+e);
           }
       }
   });


Note : if you want to fetch or add the data in Parse User table you have to replace this line :
ParseQuery<ParseObject> query = ParseQuery.getQuery("channel");
by
ParseQuery<ParseObject> query = ParseQuery.getQuery("_User");

->"_User" is used to represent the ParseUser table .

That's all .Hope it will be useful for you . thanks


Friday 7 November 2014

SignUp and login as a Parse User with Parse.com(Parse sdk)


SignUp And Login Screen

   Hello friends,

Today I am going to started new series of code of Parse.com(Parse sdk) .It is a new open source sdk ,used by many android ,iphone apps.

Today I am going to share the code to signup and login with the help of Parse.com.

Parse.com is mainly a package collection of many Parse classes,which are used for many different functionalities ,one of these parse classes is Parse User class .It is used to register any user with parse table .

For getting started with Parse sdk read the tutorialAndroid Quick Start Guide
For more info please read android tutorial of Parse.com 

Now let's move to the actual topic of this blog:

For create account ,I am only sharing the java class as the xml is very easy

SignUpActivity.java

import com.constants.Alert;
import com.constants.ConnectionDetector;
import com.constants.FunctionsValue;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import com.parse.SignUpCallback;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SignUpActivity extends Activity{

EditText edttxt_uname,edttxt_email,edttxt_password,edttxt_phone;
String str_uname,str_email,str_password,str_phone;
Button btn_submit;
ConnectionDetector cd;
ProgressDialog dlg;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.signup_layout);
inItUi();
inItAction();
}

private void inItAction() {
btn_submit.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
str_email = edttxt_email.getText().toString();
str_uname = edttxt_uname.getText().toString();
str_password = edttxt_password.getText().toString();
str_phone = edttxt_phone.getText().toString();
if (str_uname.equals("")) {
Alert.alertOneBtn(SignUpActivity.this,"Empty","Please enter your name!");
}
else if (str_email.equals("")) {
Alert.alertOneBtn(SignUpActivity.this,"Empty","Please enter your email!");
}
else if (str_password.equals("")) {
Alert.alertOneBtn(SignUpActivity.this,"Empty","Please enter your password!");
}
else if (str_phone.equals("")) {
Alert.alertOneBtn(SignUpActivity.this,"Empty","Please enter your phone number!");
}
else if (!FunctionsValue.checkEmail(str_email)) {
Alert.alertOneBtn(SignUpActivity.this,"Empty","Email is not valid!");
}
else if(!cd.isConnectingToInternet())
{
Alert.alertOneBtn(SignUpActivity.this, "No Internet Connection",
"You don't have internet connection.");

}
else
{
if (Build.VERSION.SDK_INT >= 11 ) {
  dlg = new ProgressDialog(SignUpActivity.this,AlertDialog.THEME_HOLO_LIGHT );
     } else {
        dlg = new ProgressDialog(SignUpActivity.this);
       }
       dlg.setMessage("Registering...");
       dlg.show();
signUp(str_uname, str_email, str_password,str_phone);

}

}
});
}

protected void signUp(String name, String email,
String password, String str_phone2) {
final ParseUser user = new ParseUser();

user.setUsername(name);
user.setPassword(password);
user.setEmail(email);
user.put("phone", str_phone2);


user.signUpInBackground(new SignUpCallback() {

 public void done(ParseException e) {
 dlg.dismiss();
   if (e == null) {
     signUpMsg("Account Created Successfully");

     startActivity(new Intent(getApplicationContext(),LoginActivity.class));
   } else {
    
    Log.d("error",">>"+e);
    signUpMsg("Something went wrong.Please try again later!!");
   }
 }
});

}
protected void signUpMsg(String msg) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}

private void inItUi() {
cd = new ConnectionDetector(getApplicationContext());
edttxt_email = (EditText)findViewById(R.id.edttxt_email_signuplayout);
edttxt_password = (EditText)findViewById(R.id.edttxt_password_signuplayout);
edttxt_phone = (EditText)findViewById(R.id.edttxt_phone_signuplayout);
edttxt_uname = (EditText)findViewById(R.id.edttxt_username_signuplayout);
btn_submit = (Button)findViewById(R.id.btn_submit_signuplayout);
}


}


In above code I have used some classes for showing alert,detect connection and save value in shared preference,you can changed it according to the requirement.

LoginActivity.java:

import com.constants.Alert;
import com.constants.ConnectionDetector;
import com.constants.PreferenceSetting;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseUser;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class LoginActivity extends Activity{
EditText edttxt_username,edttxt_password;
String str_uname,str_password;
Button btn_submit;
ConnectionDetector cd;
ProgressDialog dlg;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login_layout);
inItUi();
inItAction();
}
private void inItAction() {
btn_submit.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
str_uname = edttxt_username.getText().toString();
str_password = edttxt_password.getText().toString();
if (str_uname.equals("")) {
Alert.alertOneBtn(LoginActivity.this,"Empty","Please enter your username!");

}
else if (str_password.equals("")) {
Alert.alertOneBtn(LoginActivity.this,"Empty","Please enter your password!");

}
else
{
boolean isInternetPresent = cd.isConnectingToInternet();
// check for Internet status
if (isInternetPresent) {
if (Build.VERSION.SDK_INT >= 11 ) {
  dlg = new ProgressDialog(LoginActivity.this,AlertDialog.THEME_HOLO_LIGHT );
     } else {
        dlg = new ProgressDialog(LoginActivity.this);
       }
       dlg.setMessage("Please wait...");
       dlg.show();
attemptLogin(str_uname,str_password);
     
} else {
// Internet connection is not present
// Ask user to connect to Internet
Alert.alertOneBtn(LoginActivity.this, "No Internet Connection",
"You don't have internet connection.");
}

}

}
});
}
protected void attemptLogin(String str_email2, String str_password2) {
ParseUser.logInInBackground(str_email2, str_password2, new LogInCallback() {
@Override
public void done(ParseUser user, ParseException e) {
dlg.dismiss();
if(e == null)
{
Log.d(">>>",">>"+user.getObjectId()+">>>"+user.getUsername());
PreferenceSetting.SaveLoginInfo(LoginActivity.this,user.getObjectId(),usergetUsername());
startActivity(new Intent(getApplicationContext(),HomeTabActivity.class));
}
else
loginUnSuccessful();
}
});
}

protected void loginUnSuccessful() {
    Alert.alertOneBtn(LoginActivity.this,"Login", "Username or Password is invalid.");
edttxt_username.setText("");
edttxt_password.setText("");

}
private void inItUi() {
cd = new ConnectionDetector(getApplicationContext());
edttxt_password = (EditText)findViewById(R.id.edttxt_password_loginlayout);
edttxt_username = (EditText)findViewById(R.id.edttxt_username_loginlayout);
btn_submit = (Button)findViewById(R.id.btn_submit_loginlayout);

}
}


The above two classes are used for signup and login with parse sdk.I will share more code related to parse sdk in next blogs.If you faced any difficulty to understand this code ,please mention in comment.


Tuesday 12 August 2014

Fetching Twitter Following (Friends) List using twitter 4j


Twitter Following(Friends) List With Twitter Integration


Hello friends, Today I am going to share the code for fetching twitter following/friends list with twitter integration.I am fetching in list the following's id,name and picture ,you can modify the code according to your need

->First step you have to get your consumer key ans consumer secret for your app

To get Consumer Key & Consumer Secret, you have to create an app in Twitter via
Then you'll be taken to a page containing Consumer Key & Consumer Secret.
Please note that you have selected your application access type: Read,Write and Access direct messages

-> After getting the consumer key and consumer secret,next step is to add jar files in libs folder of your project .You have to add following jar files in the libs folder:

1.- signpost-commonshttp4-1.2.jar

2.- signpost-core-1.2.1.1.jar

3.- signpost-jetty6-1.2.1.1.jar

4.- simple-social-sharing-1.0.2-with-sources.jar

5.- twitter4j-core-4.0.1.jar

6.- universal-image-loader-1.9.1.jar

-The first three that are signpost libraries,you can get it from the link:     https://code.google.com/p/oauth-signpost/downloads/list

-And for simple-social -sharing from the link:  https://github.com/nostra13/Android-Simple-Social-Sharing/tree/master/Jar

-And for twitter4j core the link is : http://twitter4j.org/en/index.html#download

- Download the universal image loader from this link : https://github.com/nostra13/Android-Universal-Image-Loader/tree/master/downloads

You can also get these jars from my source code which I have added in last,you can get it after adding the code in your google drive.

->Let's move to the coding part ,first we have to make a layout having a listview to the the following list .I have named it 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"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/list_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>


</LinearLayout>

->make another package in src folder named  "nrtd.twittersh" and then add following three classes in this new package :

1.- PreferenceUtils.java

package nrtd.twittersh;

import twitter4j.auth.AccessToken;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class PreferenceUtils 
{
private SharedPreferences sharedPref;
    private Editor editor;

    private static final String TWEET_AUTH_KEY = "auth_key";
    private static final String TWEET_AUTH_SECRET_KEY = "auth_secret_key";
    private static final String TWEET_USER_NAME = "user_name";
    private static final String TWEET_USER_ID = "user_id";
    private static final String TWEET_USER_SCREEN_NAME = "user_screen_name";
    
    private static final String SHARED = "SOT_Preferences";

    public PreferenceUtils(Context context)
    {
        sharedPref = context.getSharedPreferences(SHARED, Context.MODE_PRIVATE);

        editor = sharedPref.edit();
    }

    public void storeAccessToken(AccessToken accessToken, String username) 
    {
        editor.putString(TWEET_AUTH_KEY, accessToken.getToken());
        editor.putString(TWEET_AUTH_SECRET_KEY, accessToken.getTokenSecret());
        editor.putString(TWEET_USER_NAME, username);

        editor.commit();
    }
    
    public void storeUserCredentials(long userId, String userScreenName)
    {
    editor.putLong(TWEET_USER_ID, userId);
    editor.putString(TWEET_USER_SCREEN_NAME, userScreenName);
    
    editor.commit();
    }

    public void resetAccessToken() 
    {
        editor.putString(TWEET_AUTH_KEY, null);
        editor.putString(TWEET_AUTH_SECRET_KEY, null);
        editor.putString(TWEET_USER_NAME, null);

        editor.commit();
    }

    public String getUsername() 
    {
        return sharedPref.getString(TWEET_USER_NAME, "");
    }
    
    public long getUserId() 
    {
        return sharedPref.getLong(TWEET_USER_ID, 0);
    }
    
    public String getUserScreenName() 
    {
        return sharedPref.getString(TWEET_USER_SCREEN_NAME, "");
    }
    
    public String getToken() 
    {
        return sharedPref.getString(TWEET_AUTH_KEY, "");
    }
    
    public String getTokenSecret() 
    {
        return sharedPref.getString(TWEET_AUTH_SECRET_KEY, "");
    }

    public AccessToken getAccessToken() 
    {
        String token = sharedPref.getString(TWEET_AUTH_KEY, null);
        String tokenSecret = sharedPref.getString(TWEET_AUTH_SECRET_KEY, null);

        if (token != null && tokenSecret != null)
            return new AccessToken(token, tokenSecret);
        else
            return null;
    }
    
public void clearCredentials() 
{
editor.remove(TWEET_AUTH_KEY);
editor.remove(TWEET_AUTH_SECRET_KEY);
editor.remove(TWEET_USER_NAME);
editor.remove(TWEET_USER_ID);
editor.remove(TWEET_USER_SCREEN_NAME);
editor.commit();
}

}

2.- TwitterDialog.java

package nrtd.twittersh;

import com.twitter.follower.R;

import nrtd.twittersh.TwitterApp.TwDialogListener;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Display;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

public class TwitterDialog extends Dialog {

    static final float[] DIMENSIONS_LANDSCAPE = { 460, 260 };
    static final float[] DIMENSIONS_PORTRAIT = { 280, 420 };
    static final FrameLayout.LayoutParams FILL = new FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.FILL_PARENT,
            ViewGroup.LayoutParams.FILL_PARENT);
    static final int MARGIN = 4;
    static final int PADDING = 2;
    private String mUrl;
    private TwDialogListener mListener;
    private ProgressDialog mSpinner;
    private WebView mWebView;
    private LinearLayout mContent;
    private TextView mTitle;
    private boolean progressDialogRunning = false;
    private Context mContext;

    public TwitterDialog(Context context, String url, TwDialogListener listener) {
        super(context);
        mContext = context;
        mUrl = url;
        mListener = listener;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSpinner = new ProgressDialog(getContext());

        mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mSpinner.setMessage("Loading...");

        mContent = new LinearLayout(getContext());

        mContent.setOrientation(LinearLayout.VERTICAL);

        setUpTitle();
        setUpWebView();

        Display display = getWindow().getWindowManager().getDefaultDisplay();
        final float scale = getContext().getResources().getDisplayMetrics().density;
        float[] dimensions = (display.getWidth() < display.getHeight()) ? DIMENSIONS_PORTRAIT
                : DIMENSIONS_LANDSCAPE;

        addContentView(mContent, new FrameLayout.LayoutParams(
                (int) (dimensions[0] * scale + 0.5f), (int) (dimensions[1]
                        * scale + 0.5f)));
    }

    private void setUpTitle() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        Drawable icon = getContext().getResources().getDrawable(
                R.drawable.ic_launcher);

        mTitle = new TextView(getContext());

        mTitle.setText("Twitter");
        mTitle.setTextColor(Color.WHITE);
        mTitle.setTypeface(Typeface.DEFAULT_BOLD);
        mTitle.setBackgroundColor(0xFFbbd7e9);
        mTitle.setPadding(MARGIN + PADDING, MARGIN, MARGIN, MARGIN);
        mTitle.setCompoundDrawablePadding(MARGIN + PADDING);
        mTitle.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);

        mContent.addView(mTitle);
    }

    private void setUpWebView() {
        mWebView = new WebView(getContext());

        mWebView.setVerticalScrollBarEnabled(false);
        mWebView.setHorizontalScrollBarEnabled(false);
        mWebView.setWebViewClient(new TwitterWebViewClient());
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.loadUrl(mUrl);
        mWebView.setLayoutParams(FILL);

        mContent.addView(mWebView);
    }

    private class TwitterWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith(TwitterApp.CALLBACK_URL)) {
                mListener.onComplete(url);

                TwitterDialog.this.dismiss();

                return true;
            } else if (url.startsWith("authorize")) {
                return false;
            }
            return true;
        }

        @Override
        public void onReceivedError(WebView view, int errorCode,
                String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            mListener.onError(description);
            TwitterDialog.this.dismiss();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            mSpinner.show();
            progressDialogRunning = true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            String title = mWebView.getTitle();
            if (title != null && title.length() > 0) {
                mTitle.setText(title);
            }
            progressDialogRunning = false;
            mSpinner.dismiss();
        }

    }

    @Override
    protected void onStop() {
        progressDialogRunning = false;
        super.onStop();
    }

    public void onBackPressed() {
        if(!progressDialogRunning){
            TwitterDialog.this.dismiss();
        }
       
    }
}


3.- TwiiterApp.java

package nrtd.twittersh;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;

import twitter4j.PagableResponseList;
import twitter4j.Status;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Window;


public class TwitterApp {
    private Twitter mTwitter;
    private PreferenceUtils mSession;
    private CommonsHttpOAuthConsumer mHttpOauthConsumer;
    private OAuthProvider mHttpOauthprovider;
    private AccessToken mAccessToken;
    private String mConsumerKey;
    private String mSecretKey;
    private ProgressDialog mProgressDlg;
    private TwDialogListener mListener;
    private Activity context;
ArrayList<HashMap<String,String>> ShowMap = new ArrayList<HashMap<String,String>>();
private PagableResponseList<User> mList ;
    public static final String  OAUTH_CALLBACK_SCHEME   = "x-oauthflow-twitter";
    public static final String  OAUTH_CALLBACK_HOST     = "callback";
    public static final String  CALLBACK_URL      = OAUTH_CALLBACK_SCHEME + "://" + OAUTH_CALLBACK_HOST;
    private static final String TWITTER_ACCESS_TOKEN_URL = "https://api.twitter.com/oauth/access_token";
    private static final String TWITTER_AUTHORZE_URL = "https://api.twitter.com/oauth/authorize";
    private static final String TWITTER_REQUEST_URL = "https://api.twitter.com/oauth/request_token";
    
    public TwitterApp(Activity context, String consumerKey, String secretKey) 
    {
    this.context = context;
   
        mTwitter = new TwitterFactory().getInstance();
        mSession = new PreferenceUtils(context);
        mProgressDlg = new ProgressDialog(context);

        mProgressDlg.requestWindowFeature(Window.FEATURE_NO_TITLE);

        mConsumerKey = consumerKey;
        mSecretKey = secretKey;

        mHttpOauthConsumer = new CommonsHttpOAuthConsumer(mConsumerKey, mSecretKey);

        String request_url=TWITTER_REQUEST_URL;
        String access_token_url=TWITTER_ACCESS_TOKEN_URL;
        String authorize_url=TWITTER_AUTHORZE_URL;

        mHttpOauthprovider = new DefaultOAuthProvider(request_url, access_token_url, authorize_url);
        mAccessToken = mSession.getAccessToken();

        configureToken(); 
    }
    
    public void setListener(TwDialogListener listener) {
        mListener = listener;
    }

    private void configureToken() {
        if (mAccessToken != null)
        {
            mTwitter.setOAuthConsumer(mConsumerKey, mSecretKey);
            mTwitter.setOAuthAccessToken(mAccessToken);
        }
    }

    public boolean hasAccessToken() {
        return (mAccessToken == null) ? false : true;
    }

    public void resetAccessToken() {
        if (mAccessToken != null) {
            mSession.resetAccessToken();

            mAccessToken = null;
        }
    }

    public String getUsername() {
        return mSession.getUsername();
    }
    
    public long getUserId() {
        return mSession.getUserId();
    }
    
    public String getUserScreenName() {
        return mSession.getUserScreenName();
    }
    
    public String getToken() {
        return mSession.getToken();
    }
    
    public String getTokenSecret() {
        return mSession.getTokenSecret();
    }
    public String getProfilePic(long id)
    {
    User user;
    String url ="";
try {

user = mTwitter.showUser(id);

url = user.getProfileImageURL();

} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return url;
    }
    public Status updateStatus(String status) throws Exception {
        try {
            return mTwitter.updateStatus(status);
        } catch (TwitterException e) {
            throw e;
        }
    }
    
    public Status updateStatus(StatusUpdate status) throws Exception {
        try {
        return mTwitter.updateStatus(status);
        } catch (TwitterException e) {
            throw e;
        }
    }
    
    public void authorize() {
        mProgressDlg.setMessage("Loading...");
        mProgressDlg.show();

        new Thread() {
            @Override
            public void run() {
                String authUrl = "";
                int what = 1;

                try {
                    authUrl = mHttpOauthprovider.retrieveRequestToken(
                            mHttpOauthConsumer, CALLBACK_URL);
                    what = 0;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mHandler.sendMessage(mHandler
                        .obtainMessage(what, 1, 0, authUrl));
            }
        }.start();
    }

    public void processToken(String callbackUrl) {
        mProgressDlg.setMessage("Finalizing ...");
        mProgressDlg.show();

        final String verifier = getVerifier(callbackUrl);

        new Thread() {
            @Override
            public void run() {
                int what = 1;

                try {
                    mHttpOauthprovider.retrieveAccessToken(mHttpOauthConsumer,
                            verifier);

                    mAccessToken = new AccessToken(
                            mHttpOauthConsumer.getToken(),
                            mHttpOauthConsumer.getTokenSecret());

                    configureToken();

                    User user = mTwitter.verifyCredentials();
                    
                    mSession.storeAccessToken(mAccessToken, user.getName());

                    mSession.storeUserCredentials(user.getId(), user.getScreenName());
                    
                    what = 0;
                } catch (Exception e) {
                    e.printStackTrace();
                }

                mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
            }
        }.start();
    }

    public ArrayList<HashMap<String, String>> getFriendList(String str,long arg1)
    {
    Log.d("FriendList",">>");
    try {


mList  = mTwitter.getFriendsList(str, -1);
Log.d("FriendList","22>>"+mTwitter.getFriendsList(str,-1));
for (int i = 0; i < mList.size(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Log.d("FriendList","266>>"+mList.get(i).getName());
Log.d("User",">.>"+mList.get(i).getProfileImageURL());
Log.d("User",">.>"+mList.get(i).getId());
map.put("friend_id", ""+mList.get(i).getId());
map.put("friend_name", mList.get(i).getName());
map.put("friend_photo",mList.get(i).getProfileImageURL());
ShowMap.add(map);
}

} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
    return ShowMap;
    }
    private String getVerifier(String callbackUrl) {
        String verifier = "";

        try {
            callbackUrl = callbackUrl.replace(OAUTH_CALLBACK_SCHEME, "http");

            URL url = new URL(callbackUrl);
            String query = url.getQuery();

            String array[] = query.split("&");

            for (String parameter : array) {
                String v[] = parameter.split("=");

                if (URLDecoder.decode(v[0]).equals(
                        oauth.signpost.OAuth.OAUTH_VERIFIER)) {
                    verifier = URLDecoder.decode(v[1]);
                    break;
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        return verifier;
    }

    private void showLoginDialog(String url) {
        final TwDialogListener listener = new TwDialogListener() {

            public void onComplete(String value) {
                processToken(value);
            }

            public void onError(String value) {
                mListener.onError("Failed opening authorization page");
            }
        };

        new TwitterDialog(context, url, listener).show();
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mProgressDlg.dismiss();

            if (msg.what == 1) {
                if (msg.arg1 == 1)
                    mListener.onError("Error getting request token");
                else
                    mListener.onError("Error getting access token");
            } else {
                if (msg.arg1 == 1)
                    showLoginDialog((String) msg.obj);
                else
                    mListener.onComplete("");
            }
        }
    };

    public interface TwDialogListener {
        public void onComplete(String value);

        public void onError(String value);
    }



}

->After adding above three classes in the new package in src folder ,let's write the code in MainActivity.java

Note: Please replace  TWITTER_CONSUMER_KEY and  TWITTER_SECRET_KEY with your consumer key and secret key.

package com.twitter.follower;


import java.util.ArrayList;
import java.util.HashMap;

import nrtd.twittersh.TwitterApp;
import nrtd.twittersh.TwitterApp.TwDialogListener;
import com.twitter.follower.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity{

public static String TAG = MainActivity.class.getName();
String userScreenName;
 long user_id;
 ArrayList<HashMap<String,String>> ShowList = new ArrayList<HashMap<String,String>>();
ListView list_main;
private Handler mHandler=null;
private TwitterApp mTwitter=null;
private ProgressDialog progressdialog=null,pDialog = null;

public static final String TWITTER_CONSUMER_KEY = "ADD YOUR APP CONSUMER KEY HERE";
public static final String TWITTER_SECRET_KEY = "ADD YOUR APP SECRET KEY HERE";

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list_main = (ListView)findViewById(R.id.list_main);
mHandler = new Handler();
mTwitter = new TwitterApp(MainActivity.this,TWITTER_CONSUMER_KEY,TWITTER_SECRET_KEY);
LoadTwitter();
}

private void LoadTwitter() {
mTwitter.setListener(mTwLoginDialogListener); 
if (mTwitter.hasAccessToken()) 
{

postMsgOnTwitter("");

}else 
{
mTwitter.authorize();
}
}
public TwDialogListener mTwLoginDialogListener = new TwDialogListener() 
{
@Override
        public void onComplete(String value) 
        {
postMsgOnTwitter("");

        }

@Override
        public void onError(String value) 
        {
showToast("Twitter login failed");
            mTwitter.resetAccessToken();
        }


    };

  private void postMsgOnTwitter(final String msg)
   {
    showProgressDialog("loading..");
    try 
{

Log.e(TAG, "Id>>>"+mTwitter.getUserId()+"<<UserName>>"+ mTwitter.getUserScreenName());
hideProgressDialog();

     showToast("Login successfully.");
     showToast("Id>>>"+mTwitter.getUserId()+"<<UserName>>"+ mTwitter.getUserScreenName());
      userScreenName  = mTwitter.getUserScreenName();
      user_id = mTwitter.getUserId();
  
       loadApi();

catch (Exception e) 
{
hideProgressDialog();
showToast("Failed to Login");
e.printStackTrace();
}

}
  private void loadApi() {
new ListLoad().execute();
  }
 class ListLoad extends AsyncTask<String, String, String>{
protected void onPreExecute() {
           super.onPreExecute();
           pDialog = new ProgressDialog(MainActivity.this);
           pDialog.setMessage("Loading Friends..");
         pDialog.setIndeterminate(false);
         pDialog.setCancelable(true);
         pDialog.show();
       }

@Override
protected String doInBackground(String... arg0) {

 ShowList =  mTwitter.getFriendList(userScreenName,user_id);
             
return null;
}
protected void onPostExecute(String file_url) {
try {

         pDialog.dismiss();
      list_main.setAdapter(null);
      list_main.setAdapter(new TwitterAdapter(MainActivity.this,ShowList));
} catch (Exception e) {
e.printStackTrace();
}
      }
}
private void showToast(final  String msg) {
// TODO Auto-generated method stub
  mHandler.post(new Runnable() 
{
@Override
public void run() 
{
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
}

public void showProgressDialog(String msg)
{
  runOnUiThread(new RunShowLoader(msg, false));
}
class RunShowLoader implements Runnable
{
private String strMsg;
private boolean isCancalable;

public RunShowLoader(String strMsg, boolean isCancalable) 
{
this.strMsg = strMsg;
this.isCancalable = isCancalable;
}

@Override
public void run() 
{
try
{
if(progressdialog == null ||(progressdialog != null && !progressdialog.isShowing()))
{
progressdialog = ProgressDialog.show(MainActivity.this, "", strMsg);
progressdialog.setCancelable(isCancalable);
}
}
catch(Exception e)
{
progressdialog = null;
e.printStackTrace();
}
}
}

/** For hiding progress dialog **/
public void hideProgressDialog()
{
runOnUiThread(new Runnable()
{
@Override
public void run() 
{
try
{
if(progressdialog != null && progressdialog.isShowing())
{
progressdialog.dismiss();
}
progressdialog = null;
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
}


}


->Now I have used an adapter to show data in custom list view the xml for single list item is as following .I have named it :  friend_list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:layout_gravity="center_horizontal"
              android:orientation="horizontal">

    <ImageView
            android:id="@+id/icon_friendlistitem"
            android:src="@drawable/ic_launcher"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_margin="3dp" />
    <LinearLayout
            android:orientation="vertical"
            android:layout_gravity="center_vertical"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="15dp" >
        <TextView
                android:id="@+id/name_friendlistitem"
                android:text="test"
                android:textColor="#333"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="18sp" />
     
    </LinearLayout>
</LinearLayout>

-> Last step is to make adapter class to show the following list.I have named it TwitterAdapter.java

package com.twitter.follower;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.twitter.follower.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;

public class TwitterAdapter extends BaseAdapter{
private ImageLoader imageLoader  = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder()
 
.showImageOnLoading(R.drawable.default_profile_3_bigger)
.showImageForEmptyUri(R.drawable.default_profile_3_bigger)
.showImageOnFail(R.drawable.default_profile_3_bigger)
.cacheInMemory(true)
.cacheOnDisc(true)
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
.bitmapConfig(Bitmap.Config.ARGB_8888)
.displayer(new FadeInBitmapDisplayer(300))
.build();
private class ViewHolder {
public RelativeLayout lnCover;
public TextView tvName;
public TextView tvTitle,txt_before;
public ImageView img_album;
public Button btn_after;
}
private LayoutInflater mLayoutInflater = null;
private Activity activity;
private ViewHolder holder;
private String name,cat_id,str_flag="";
ArrayList<HashMap<String,String>>  Show;
public TwitterAdapter(Activity activity2,
ArrayList<HashMap<String, String>> showList) {
this.activity = activity2;
this.Show = showList;
mLayoutInflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader.init(ImageLoaderConfiguration.createDefault(activity));
  
}

@Override
public int getCount() {
return Show.size();
}

@Override
public Object getItem(int position) {
return Show.get(position);
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

if (convertView == null) {
convertView = mLayoutInflater.inflate(R.layout.friend_list_item, null);

holder = new ViewHolder();
holder.tvTitle= (TextView) convertView.findViewById(R.id.name_friendlistitem);
holder.img_album = (ImageView)convertView.findViewById(R.id.icon_friendlistitem);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvTitle.setText(Show.get(position).get("friend_name")); 
      imageLoader.displayImage(Show.get(position).get("friend_photo"),holder.img_album, options);

return convertView;
}

}

->Now you have to add following permission in your menifest file: 

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

->Above is the all coding for fetching following list from twitter using twitter4j.You can easily paste this code in your app .Please add this code and share your experiences with me about this code .

->You can add the working example of this project in your google drive from here: 

FetchTwitterFollower

->Hope this will helpful for you.











Advanced Kotlin Coroutines : Introduction

 Hi,  Today I am unwraping the topic in Kotin world i.e. Coroutine . If you want to get started with Kotlin coroutine and ease your daily de...