Friday 18 March 2016

Android: Google+ and Facebook Login without SDK and libray

 Google+ Login

  • Create project at https://console.developers.google.com/

         and Get CLIENT_ID and CLIENT_SECRET

  • Create one class GetAccessToken.java


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class GetAccessToken {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    public GetAccessToken() {
    }
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    Map<String, String> mapn;
    DefaultHttpClient httpClient;
    HttpPost httpPost;

    public JSONObject gettoken(String address,String token,String client_id,String client_secret,String redirect_uri,String grant_type) {
        // Making HTTP request
        try {
            // DefaultHttpClient
            httpClient = new DefaultHttpClient();
            httpPost = new HttpPost(address);

            params.add(new BasicNameValuePair("code", token));
            params.add(new BasicNameValuePair("client_id", client_id));
            params.add(new BasicNameValuePair("client_secret", client_secret));
            params.add(new BasicNameValuePair("redirect_uri", redirect_uri));
            params.add(new BasicNameValuePair("grant_type", grant_type));

            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
           
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            
            json = sb.toString();
            Log.e("JSONStr", json);
        } catch (Exception e) {
        e.getMessage();
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        // Parse the String to a JSON Object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        // Return JSON String
        return jObj;
    }
    
}


  • Now create Android activity to login at google+
package learn2crack.weboauth2;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

private static String CLIENT_ID = "2620035374-elvgrman1ltj8280ahbi027kff46gl8s.apps.googleusercontent.com";
// Use your own client id
private static String CLIENT_SECRET = "YDapcX77bFeMZSHd31P_sEhMsL";
// Use your own client secret
private static String REDIRECT_URI = "http://localhost";
private static String GRANT_TYPE = "authorization_code";
private static String TOKEN_URL = "https://accounts.google.com/o/oauth2/token";
private static String OAUTH_URL = "https://accounts.google.com/o/oauth2/auth";
private static String OAUTH_SCOPE = "email%20profile";
// Change the Scope as you need
WebView web;
Button auth;
SharedPreferences pref;
TextView Access;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = getSharedPreferences("AppPref", MODE_PRIVATE);
Access = (TextView) findViewById(R.id.Access);
auth = (Button) findViewById(R.id.auth);
auth.setOnClickListener(new View.OnClickListener() {
Dialog auth_dialog;

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
auth_dialog = new Dialog(MainActivity.this);
auth_dialog.setContentView(R.layout.auth_dialog);
web = (WebView) auth_dialog.findViewById(R.id.webv);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl(OAUTH_URL + "?redirect_uri=" + REDIRECT_URI
+ "&response_type=code&client_id=" + CLIENT_ID
+ "&scope=" + OAUTH_SCOPE);
web.setWebViewClient(new WebViewClient() {

boolean authComplete = false;
Intent resultIntent = new Intent();

@Override
public void onPageStarted(WebView view, String url,
Bitmap favicon) {
super.onPageStarted(view, url, favicon);

}

String authCode;

@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);

if (url.contains("?code=") && authComplete != true) {
Uri uri = Uri.parse(url);
authCode = uri.getQueryParameter("code");
Log.i("", "CODE : " + authCode);
authComplete = true;
resultIntent.putExtra("code", authCode);
MainActivity.this.setResult(Activity.RESULT_OK,
resultIntent);
setResult(Activity.RESULT_CANCELED, resultIntent);

SharedPreferences.Editor edit = pref.edit();
edit.putString("Code", authCode);
edit.commit();
auth_dialog.dismiss();
new TokenGet().execute();
Toast.makeText(getApplicationContext(),
"Authorization Code is: " + authCode,
Toast.LENGTH_SHORT).show();
} else if (url.contains("error=access_denied")) {
Log.i("", "ACCESS_DENIED_HERE");
resultIntent.putExtra("code", authCode);
authComplete = true;
setResult(Activity.RESULT_CANCELED, resultIntent);
Toast.makeText(getApplicationContext(),
"Error Occured", Toast.LENGTH_SHORT).show();

auth_dialog.dismiss();
}
}
});
auth_dialog.show();
auth_dialog.setTitle("Authorize Learn2Crack");
auth_dialog.setCancelable(true);
}
});
}

private class TokenGet extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
String Code;

@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Contacting Google ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
Code = pref.getString("Code", "");
pDialog.show();
}

@Override
protected JSONObject doInBackground(String... args) {
GetAccessToken jParser = new GetAccessToken();
JSONObject json = jParser.gettoken(TOKEN_URL, Code, CLIENT_ID,
CLIENT_SECRET, REDIRECT_URI, GRANT_TYPE);
return json;
}

@Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
if (json != null) {

try {
pDialog.dismiss();
Toast.makeText(getApplicationContext(), json.toString(),
Toast.LENGTH_SHORT).show();
final String tok = json.getString("access_token");
String expire = json.getString("expires_in");
//String refresh = json.getString("refresh_token");
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
fetchNameFromProfileServer(tok);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
Log.d("Token Access", tok);
Log.d("Expire", expire);
//Log.d("Refresh", refresh);
auth.setText("Authenticated");
Access.setText("Access Token:" + tok + "\nExpires:"
+ expire + "\nRefresh Token:");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

} else {
Toast.makeText(getApplicationContext(), "Network Error",
Toast.LENGTH_SHORT).show();
}
}
}

private void fetchNameFromProfileServer(String token) throws IOException,
JSONException {

URL url = new URL(
"https://www.googleapis.com/oauth2/v1/userinfo?access_token="
+ token);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
int sc = con.getResponseCode();
Log.e("sc"+con.getResponseMessage(),""+sc);
if (sc == 200) {
InputStream is = con.getInputStream();
final String GOOGLE_USER_DATA = readResponse(is);
is.close();

runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, GOOGLE_USER_DATA, 1).show();
android.webkit.CookieManager.getInstance().removeAllCookie();
}
});
return;
} else if (sc == 401) {

return;
} else {

return;
}
}

private static String readResponse(InputStream is) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] data = new byte[2048];
int len = 0;
while ((len = is.read(data, 0, data.length)) >= 0) {
bos.write(data, 0, len);
}
return new String(bos.toByteArray(), "UTF-8");
}

}

--------------------------------------------------------------------------------------------------------------------------

Facebook Login

First create facebook app at https://developers.facebook.com/ for web platform

you will get AppID and App Secret automatically

Then set redirect url at Setting->advance Setting-> Redirect URL

Now Create  FBGraph.java and FBConnection.java following way

FBGraph.java..................................

ipackage com.example.root.testfacebook;
/*** Created by root on 7/3/16.*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

public class FBGraph {
private String accessToken;

public FBGraph(String accessToken) {
this.accessToken = accessToken;
}

public String getFBGraph() {
String graph = null;
try {

    String g = "https://graph.facebook.com/me?fields=id,name,email&" + accessToken;
    URL u = new URL(g);
    URLConnection c = u.openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(
            c.getInputStream()));
    String inputLine;
    StringBuffer b = new StringBuffer();
    while ((inputLine = in.readLine()) != null)
        b.append(inputLine + "\n");
    in.close();
    graph = b.toString();
    System.out.println(graph);
} catch (Exception e) {
    e.printStackTrace();
    throw new RuntimeException("ERROR in getting FB graph data. " + e);
}
return graph;
}

public Map getGraphData(String fbGraph) {
Map fbProfile = new HashMap();
try {
    JSONObject json = new JSONObject(fbGraph);
    fbProfile.put("id", json.getString("id"));
    fbProfile.put("name", json.getString("name"));
    if (json.has("email"))
        fbProfile.put("email", json.getString("email"));
    if (json.has("gender"))
        fbProfile.put("gender", json.getString("gender"));
} catch (JSONException e) {
    e.printStackTrace();
    throw new RuntimeException("ERROR in parsing FB graph data. " + e);
}
return fbProfile;
}
}





FBConnection.java..........................................


package com.example.root.testfacebook;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class FBConnection {
    public static final String FB_APP_ID = "1509052649408092";
    public static final String FB_APP_SECRET = "3c19b5928afaa0121241f964ce37b4c9";
    public static final String REDIRECT_URI = "http://192.168.168.24/xampp/index.php";


    static String accessToken = "";

    public String getFBAuthUrl() {
        String fbLoginUrl = "";
        try {
            fbLoginUrl = "http://www.facebook.com/dialog/oauth?" + "client_id="                    + FBConnection.FB_APP_ID + "&redirect_uri="                    + URLEncoder.encode(FBConnection.REDIRECT_URI, "UTF-8")
                    + "&scope=email";
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return fbLoginUrl;
    }

    public String getFBGraphUrl(String code) {
        String fbGraphUrl = "";
        try {
            fbGraphUrl = "https://graph.facebook.com/oauth/access_token?"                    + "client_id=" + FBConnection.FB_APP_ID + "&redirect_uri="                    + URLEncoder.encode(FBConnection.REDIRECT_URI, "UTF-8")
                    + "&client_secret=" + FB_APP_SECRET + "&code=" + code;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return fbGraphUrl;
    }

    public String getAccessToken(String code) {
        if ("".equals(accessToken)) {
            URL fbGraphURL;
            try {
                fbGraphURL = new URL(getFBGraphUrl(code));
            } catch (MalformedURLException e) {
                e.printStackTrace();
                throw new RuntimeException("Invalid code received " + e);
            }
            URLConnection fbConnection;
            StringBuffer b = null;
            try {
                fbConnection = fbGraphURL.openConnection();
                BufferedReader in;
                in = new BufferedReader(new InputStreamReader(
                        fbConnection.getInputStream()));
                String inputLine;
                b = new StringBuffer();
                while ((inputLine = in.readLine()) != null)
                    b.append(inputLine + "\n");
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("Unable to connect with Facebook "+ e);
            }

            accessToken = b.toString();
            if (accessToken.startsWith("{")) {
                throw new RuntimeException("ERROR: Access Token Invalid: "+ accessToken);
            }
        }
        return accessToken;
    }
}
Now create activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/webview_frame"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="#0099cc"
 tools:context=".MyActivity">
 <ProgressBar
 android:id="@+id/progressBar"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_gravity="center" />
 <WebView
 android:id="@+id/webview"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent" />
</FrameLayout>



Java class


package com.example.root.testfacebook;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaActionSound;
import android.net.Uri;

import android.net.UrlQuerySanitizer;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.GeolocationPermissions;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.util.Map;

public class MainActivity extends AppCompatActivity {
protected WebView mainWebView;
private ProgressBar mProgress;
private Context mContext;
private WebView mWebviewPop;
private FrameLayout mContainer;

FBConnection fbConnection;

@Overrideprotected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fbConnection = new FBConnection();
String url = fbConnection.getFBAuthUrl();

mainWebView = (WebView) findViewById(R.id.webview);

//Progress BarmProgress = (ProgressBar) findViewById(R.id.progressBar);

//Cookie manager for the webviewCookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);


mContainer = (FrameLayout) findViewById(R.id.webview_frame);

//SettingsWebSettings webSettings = mainWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAppCacheEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportMultipleWindows(true);

mainWebView.setWebViewClient(new MyCustomWebViewClient());
mainWebView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);

mainWebView.setWebChromeClient(new MyCustomChromeClient());
mainWebView.loadUrl(url);

mContext = this.getApplicationContext();


}


private class MyCustomWebViewClient extends WebViewClient {
@Overridepublic boolean shouldOverrideUrlLoading(WebView view, String url) {
    String host = Uri.parse(url).getHost();


    if (host.equals("m.facebook.com") || host.equals("www.facebook.com")) {
        return false;
    }

    if (url.contains("code")) {
        final Uri uri = Uri.parse(url);


        new Thread(new Runnable() {
            @Override            public void run() {

                String accessToken = fbConnection.getAccessToken(uri.getQueryParameter("code"));

                FBGraph fbGraph = new FBGraph(accessToken);
                String graph = fbGraph.getFBGraph();
                final Map<String, String> fbProfileData = fbGraph.getGraphData(graph);
                runOnUiThread(new Runnable() {
                    @Override                    public void run() {
                        Toast.makeText(MainActivity.this, fbProfileData.get("email").toString(),
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }).start();
    }

    view.loadUrl(url);

    return true;
}

@Overridepublic void onReceivedSslError(WebView view, SslErrorHandler handler,
                               SslError error) {

}

}

private class MyCustomChromeClient extends WebChromeClient {

@Overridepublic boolean onCreateWindow(WebView view, boolean isDialog,
                              boolean isUserGesture, Message resultMsg) {
    mWebviewPop = new WebView(mContext);
    mWebviewPop.setVerticalScrollBarEnabled(false);
    mWebviewPop.setHorizontalScrollBarEnabled(false);
    mWebviewPop.setWebViewClient(new MyCustomWebViewClient());
    mWebviewPop.getSettings().setJavaScriptEnabled(true);
    mWebviewPop.getSettings().setSavePassword(false);
    mWebviewPop.setLayoutParams(new FrameLayout.LayoutParams
   (ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));
    mContainer.addView(mWebviewPop);
    WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
    transport.setWebView(mWebviewPop);
    resultMsg.sendToTarget();

    return true;
}

@Overridepublic void onCloseWindow(WebView window) {

}

}

}



Thursday 31 December 2015

Android basic function for service

        @Override
public void onStart(Intent intent, int startId) {
handleStart(intent, startId);

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleStart(intent, startId);

// Only action ACTION_REFRESH creates background thread, so just return
// START_NOT_STICKY
return START_REDELIVER_INTENT;
}

private void handleStart(Intent intent, int startId) {

if (intent != null) {
               }
}

Sunday 20 December 2015

RecycleView with mutiple Layout

public class MainAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private ArrayList<Object> lstCommentsReply ;
    private static final int TYPE_COMMENT = 0;
    private static final int TYPE_REPLY = 1;

    public class ReplyViewHolder extends RecyclerView.ViewHolder {
        TextView mNotes;

        public ReplyViewHolder(View itemView) {
            super(itemView);
            mNotes=(TextView)itemView.findViewById(R.id.tv_notes);
        }
    }

    public class CommentViewHolder extends RecyclerView.ViewHolder {
        TextView mNotes;

        public CommentViewHolder(View itemView) {
            super(itemView);
            mNotes=(TextView)itemView.findViewById(R.id.tv_notes);

        }
    }
    
    @Override    public int getItemViewType(int position) {
        int viewType;
        if (lstCommentsReply.get(position) instanceof Comment) {
            viewType = TYPE_COMMENT;
        } else {
            viewType = TYPE_REPLY;
        }
        return viewType;
    }

    @Override    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        LayoutInflater mInflater = LayoutInflater.from(viewGroup.getContext());
        switch (viewType) {

            case TYPE_COMMENT:
                ViewGroup vImage = (ViewGroup) mInflater.inflate(R.layout.list_item_comment, viewGroup, false);
                CommentViewHolder vhComments = new CommentViewHolder(vImage);
                return vhComments;
            case TYPE_REPLY:
                ViewGroup vGroup = (ViewGroup) mInflater.inflate(R.layout.list_item_reply, viewGroup, false);
                ReplyViewHolder vhReply = new ReplyViewHolder(vGroup);
                return vhReply;
            default:
                ViewGroup vGroup0 = (ViewGroup) mInflater.inflate(R.layout.list_item_comment, viewGroup, false);
                ReplyViewHolder vhCommentsDefault = new ReplyViewHolder(vGroup0);
                return vhCommentsDefault;
        }
    }

    @Override    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int i) {
        switch (viewHolder.getItemViewType()) {

            case TYPE_COMMENT:

                Comment comment = (Comment) lstCommentsReply.get(i);

                CommentViewHolder commentViewHolder = (CommentViewHolder) viewHolder;

                commentViewHolder.mNotes.setText(comment.getCommentText());
                break;

            case TYPE_REPLY:
                Reply reply = (Reply) lstCommentsReply.get(i);
                ReplyViewHolder replyViewHolder = (ReplyViewHolder) viewHolder;
                replyViewHolder.mNotes.setText(reply.getReplyText());
                break;

        }
    }

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

    public MainAdapter(List<Object> commentsReplyList) {

        this.lstCommentsReply = new ArrayList<Object>(commentsReplyList);
    }
}


// Create and Set Adpater

Reply reply;
Comment comment;
mLstCommentsReply=new ArrayList<Object>();
comment=new Comment();
comment.setCommentText("Comment1");
mLstCommentsReply.add(comment);
comment=new Comment();
comment.setCommentText("Comment2");
mLstCommentsReply.add(comment);
reply=new Reply();
reply.setReplyText("Reply1");
mLstCommentsReply.add(reply);
for(int i=0;i<20;i++) {
    comment = new Comment();
    comment.setCommentText("Comment3");
    mLstCommentsReply.add(comment);
    reply = new Reply();
    reply.setReplyText("Reply2");
    mLstCommentsReply.add(reply);
}
RecyclerView  mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this,
        LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setAdapter(new MainAdapter(mLstCommentsReply));



//   item layout

list_item_comment.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/university_background"    android:orientation="vertical">

    <TextView        android:layout_width="match_parent" android:id="@+id/tv_notes" android:textColor="@color/white"        android:layout_height="wrap_content" />

</LinearLayout>


list_item_replay.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/communityname_background"    android:orientation="vertical">

    <TextView        android:layout_width="match_parent" android:id="@+id/tv_notes"        android:layout_height="wrap_content" />

</LinearLayout>

Tuesday 22 September 2015

Listview adapter

public class ReceiptAdapter extends BaseAdapter implements Filterable {

   private final Activity context;
   public ReceiptAdapter(Activity context) {

      this.context = context;

   }

   class ViewHolder {
      protected TextView number;
      protected TextView name;
      protected ImageButton imageButton;
   }

   @Override
   public View getView(final int position, View convertView,
         ViewGroup parent) {
      View view = null;
      try {
         if (convertView == null) {

            LayoutInflater inflator = context.getLayoutInflater();
            view = inflator.inflate(R.layout.receipt_item, null);
            final ViewHolder viewHolder = new ViewHolder();
            viewHolder.number = (TextView) view
                  .findViewById(R.id.tvnumber);

            viewHolder.name = (TextView) view.findViewById(R.id.tvname);

            viewHolder.imageButton = (ImageButton) view
                  .findViewById(R.id.delete_item);

            view.setTag(viewHolder);

         } else {
            view = convertView;

         }
         ViewHolder holder = (ViewHolder) view.getTag();

         

         holder.name.setText(mContactList.get(position).getName());
      } catch (Exception e) {
         // TODO: handle exception         e.printStackTrace();
      }
      return view;
   }

   @Override
   public int getCount() {
      // TODO Auto-generated method stub      return mContactList.size();
   }

   @Override
   public Object getItem(int position) {
      // TODO Auto-generated method stub      return position;
   }

   @Override
   public long getItemId(int position) {
      // TODO Auto-generated method stub      return position;
   }

}

Cardview example

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:padding="16dp"    >

    <android.support.v7.widget.CardView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/cv"        >

        <RelativeLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:padding="16dp"            >

            <ImageView                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:id="@+id/person_photo"                android:layout_alignParentLeft="true"                android:layout_alignParentTop="true"                android:layout_marginRight="16dp"                />

            <TextView                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:id="@+id/person_name"                android:layout_toRightOf="@+id/person_photo"                android:layout_alignParentTop="true"                android:textSize="30sp"                />

            <TextView                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:id="@+id/person_hobby"                android:layout_toRightOf="@+id/person_photo"                android:layout_below="@+id/person_name"                />

        </RelativeLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>


<android.support.v7.widget.RecyclerView    android:layout_width="match_parent"    android:layout_height="match_parent"    android:id="@+id/my_list"    />


Inialization

ArrayList<DeliveryLog> mDeliveryLog;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;

mRecyclerView = (RecyclerView) v.findViewById(R.id.cards_sms);

mRecyclerView.setHasFixedSize(true);

mLayoutManager = new LinearLayoutManager(getActivity());
((LinearLayoutManager) mLayoutManager).setOrientation(LinearLayoutManager.VERTICAL); 
mRecyclerView.setLayoutManager(mLayoutManager);

Adapter

public class CardViewDataAdapter extends      RecyclerView.Adapter<CardViewDataAdapter.ViewHolder> {
   public ArrayList<DeliveryLog> mDataset;

   // Provide a suitable constructor (depends on the kind of dataset)   public CardViewDataAdapter(ArrayList<DeliveryLog> myDataset) {
      mDataset = myDataset;
   }

   // Create new views (invoked by the layout manager)   @Override
   public CardViewDataAdapter.ViewHolder onCreateViewHolder(
         ViewGroup parent, int viewType) {
      // create a new view      View itemLayoutView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.smsreportcontent, parent, false);

      ViewHolder viewHolder = new ViewHolder(itemLayoutView);
      return viewHolder;
   }

   // Replace the contents of a view (invoked by the layout manager)   @Override
   public void onBindViewHolder(ViewHolder holder, final int position) {
   holder.tvMessge.setText(mDeliveryLog.get(position).messge);

   }

   // Return the size of your dataset (invoked by the layout manager)   @Override
   public int getItemCount() {
      return mDeliveryLog.size();
   }

   // inner class to hold a reference to each item of RecyclerView   public class ViewHolder extends RecyclerView.ViewHolder {

      protected TextView tvName,tvHobby;

      public ViewHolder(View view) {
         super(view);
         tvtime = (TextView) view.findViewById(R.id.tvtime);
         tvSent = (TextView) view.findViewById(R.id.tvsent);

      }
   }
}

How to set

mAdapter = new CardViewDataAdapter(mDeliveryLog);
mRecyclerView.setAdapter(mAdapter);

Monday 21 September 2015

Convert Seconds into Second/Minute/Hour

            long s = seconds % 60;
   long m = (seconds / 60) % 60;
   long h = (seconds / (60 * 60)) % 24;
   return String.format("%d:%02d:%02d", h,m,s);