03/05/2017

RecyclerView with animation in Android Application.


1. Add Support Libary: dependencies { compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.android.support:recyclerview-v7:23.1.1' compile 'com.squareup.picasso:picasso:2.5.2' } Add RecyclerView to the layout File: Add the following code in your activity.xml file. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="app.androidrecyclerview.MainActivity"> <android.support.v7.widget.RecyclerView android:id="@+id/list" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="5dp" android:layout_marginTop="8dp" /> </RelativeLayout> Create a custom row Layout Add the following code in your custom_row.xml file: <?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="wrap_content" android:padding="20dp" android:orientation="vertical"> <ImageView android:id="@+id/image" android:layout_width="match_parent" android:layout_height="100dp" android:background="#11000000" android:scaleType="centerCrop"/> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:textSize="18sp"/> </LinearLayout> Create a Class: MainActivity.Java public class MainActivity extends AppCompatActivity { private List<String> list = new ArrayList<String>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.list); mRecyclerView.setHasFixedSize(true); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); arrayList(); } public void arrayList(){ for (int i = 0; i< 20; i++){ list.add("This is row of number "+ i); } } } Creating RecyclerView Adapter class public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> { private List<String> list ; public Context context; ViewHolder viewHolder; int lastPosition = -1; public Adapter(List<String> list, Context context) { this.list = list; this.context = context; } @Override public int getItemCount() { return list.size(); } public void onBindViewHolder(final ViewHolder viewHolder, final int position ) { viewHolder.textView.setText(list.get(position)); Picasso.with(context).load(R.drawable.image) .into(viewHolder.imageView); viewHolder.textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(v.getContext(), "OnClick :" + list.get(position), Toast.LENGTH_SHORT).show(); } }); if(position >lastPosition) { Animation animation = AnimationUtils.loadAnimation(context, R.anim.up_from_bottom); viewHolder.itemView.startAnimation(animation); lastPosition = position; } } @Override public Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { //Inflate the layout, initialize the View Holder View itemLayoutView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_list, null); viewHolder = new ViewHolder(itemLayoutView); return viewHolder; } // initializes textview and imageview to be used by RecyclerView. public static class ViewHolder extends RecyclerView.ViewHolder { public TextView textView; public ImageView imageView; public ViewHolder(View view) { super(view); textView = (TextView) view.findViewById(R.id.text); imageView = (ImageView) view.findViewById(R.id.image); } } }

02/05/2017

19/08/2016

Sqlite database

package com.main.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBadapter extends SQLiteOpenHelper{
    private static final String DATABASE_NAME = "test";
    private static final int DATABASE_VERSION = 2;
    private static final String API_CONFIG_TABLE = "CREATE TABLE tablename(id INTEGER PRIMARY KEY  NOT NULL  UNIQUE, test1 VARCHAR, test2 VARCHAR);";


    public DBadapter(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(API_CONFIG_TABLE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS tablename");

        onCreate(db);
    }
}
-------------------------------
public class DBmethods {
    private static final String DATABASE_TABLE = "test.sqlite";
    SQLiteDatabase sdb;
    Context sctx;
    DBadapter sdbhelper;

    public DBmethods(Context ctx) {
        this.sctx = ctx;
    }

    public DBmethods open() throws SQLException {
        sdbhelper = new DBadapter(sctx);
        sdb = sdbhelper.getWritableDatabase();
        return this;
    }

    public void close() {
        sdbhelper.close();
    }
/*-----------------INSERT METHOD-------------------------*/
    public boolean insertdetails(Beanclass beanclass) {
        open();
        boolean sucess = true;
        try {
            String query = "INSERT INTO tablename(test1,test2)VALUES(\""
                    + beanclass.gettest1 + "\",\""
                    + beanclass.gettest2 + "\')";
            Log.d("QUERY===>",query);
            sdb.execSQL(query);
        } catch (Exception e) {
            close();
            sucess = false;
            e.printStackTrace();
        }
        close();
        return sucess;
    }

/*-----------------SELECT METHOD-------------------------*/
   public String getvalue() {
        open();
        String result="";
        try {
            String query = "SELECT test2 from tablename";
            Log.d("QUERY", query);
            Cursor cursor = sdb.rawQuery(query, null);
            if (cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) {
                cursor.moveToFirst();
                // mcu = new HashMap<String, String>();
                try
                {
                    int _test2 = cursor.getColumnIndexOrThrow("test2");
                    result=cursor.getString(_test2 );
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Log.d("Table - version", "null");
            }
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        close();
        return result;
    }
public ArrayList<Bean> get_list(){
        ArrayList<Bean> value_list = new ArrayList<Bean>();
        open();
        try {
            String query = "SELECT * from querytable";
            Log.d("QUERY", query);
            Cursor cursor = sdb.rawQuery(query, null);
            if (cursor!= null && cursor.getCount() > 0){
                cursor.moveToFirst();
                int _Title = cursor.getColumnIndexOrThrow
                value_list.add(new Bean(cursor.getString(_Title)));
                while (cursor.moveToNext()) {
                    _Title = cursor.getColumnIndexOrThrow("Title");
                    value_list.add(new Bean(cursor.getString(_Title)));
                }
            }
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        close();
        return value_list;
    }


 public void deletmethod_table() {
        open();
        String query = "delete FROM tablename";
        Log.d("QUERY", query);
        sdb.execSQL(query);
        close();
    }
}







26/02/2016

Realm Using value Insert

Class Name : Sampledb.class
package com.main.android.databasemodels;
public class Sampledb extends RealmObject {
 @PrimaryKey
 private String id;
 private String name;
 public String getId() {
    return id;
}
 public void setId(String id) {
   this.id= id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name= name;
}
}
Class Name: Mainactivity
public class Mainactivity extends AppCompatActivity{
 Realm realm;
 @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sample);
    realm = Realm.getDefaultInstance();
    removeExamlisttable();
    realm.beginTransaction();
   for(int i=0;i<arraylistres.length();i++){
    //Create ExamList Realm Object    
Sampledb sampledb= realm.createObject(Sampledb.class);
    sampledb.setId(arraylistres.get(i).getId());
   sampledb.setName(arraylistres.get(i).getName());   }
  realm.commitTransaction();
 }
private void removeSampledbtable(){
    try {
        realm.beginTransaction();
        realm.clear(sampledb.class);
    }catch (Exception e){
        e.printStackTrace(); 
    }finally {
        realm.commitTransaction();
    }
} 
// Find All value 
Sampledb sampledb=realm.where(Sampledb.class).findAll);
}

06/01/2016

Listview Using Custom Adapter

public class Mainactivity extends FragmentActivity{
      private ArrayList<Places> list = new ArrayList<Places>();
      private PlaceListAdapter mPlaceListAdapter;
private ListView placelistview;
       @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nearbydreserlistview_layout);
               placelistview = (ListView)findViewById(R.id.placelistview);
              list.add(new Places("a"));
              list.add(new Places("b"));
              list.add(new Places("c"));
              list.add(new Places("d"));
              mPlaceListAdapter = new PlaceListAdapter(context, list);
    placelistview.setAdapter(mPlaceListAdapter);
       }
      public class PlaceListAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<Places> mplaceList;
private LayoutInflater mLayoutInflater = null;

public PlaceListAdapter(Context context, ArrayList<Places> list) {
mContext = context;
mplaceList = list;
mLayoutInflater = (LayoutInflater)            mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return mplaceList.size();
}
@Override
public Object getItem(int pos) {
return mplaceList.get(pos);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
try {
final ListViewHolder viewHolder;
if (convertView == null) {
LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = li.inflate(R.layout.placelistadapter_layout, parent,false);
viewHolder = new ListViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ListViewHolder) convertView.getTag();
}
viewHolder.name.setText(mplaceList.get(position).getName());
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
}
class ListViewHolder {
   public TextView name;
   public ListViewHolder(View base){
    super();
    try {
    name= (TextView) base.findViewById(R.id.txt_name);
    }catch(Exception e){e.printStackTrace();}
   }
}
}

24/09/2015

Jsonfunction common class

Class Name: Jsonfunctions

https://www.dropbox.com/s/2u4ty3ds7tqn4x1/Jsonfunctions.java?dl=0


package com.main.sample

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerPNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

public class Jsonfunctions {
private static final int TIMEOUT = 50000;
private static final int CONNECTION_TIMEOUT = 50000;
private static final int SOCKET_TIMEOUT = 50000;
private static final long MCC_TIMEOUT = 50000;
private Context context;

public Jsonfunctions (Context context) {
this.context = context;
}
public String uploadfile(String URL,String file,String securitykey,String id){
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
String serverResponseMessage = null ;
String pathToOurFile =file;
String urlServer = URL;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary =  "*****";
try
{
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("id_task", id);
connection.setRequestProperty("security", securitykey);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ "/public_html/wp-content/task_record/"
+ pathToOurFile + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
byte[] buffer = new byte[4096];
int read = 0;
while ((read = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
serverResponseMessage = connection.getResponseMessage();
fileInputStream.close();
outputStream.flush();
outputStream.close();
} catch (Exception ex) {

}
return serverResponseMessage;
}

public final String getJSONfromURL(String url){
InputStream is = null;
String result = "";
if(isConnected()) {
DefaultHttpClient client;
       HttpParams params = new BasicHttpParams();
       HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
     
       HttpProtocolParams.setContentCharset(params, "UTF-8");
       params.setBooleanParameter("http.protocol.expect-continue", false);      
       HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);
       HttpConnectionParams.setSoTimeout(params, TIMEOUT);      
       SchemeRegistry registry = new SchemeRegistry();
       registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
       ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);      
       client = new DefaultHttpClient(ccm, params);      
       client.getCredentialsProvider().setCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials("", ""));
   try{
    url = convertSpaceToEncode(url);
    Log.d("Web URL","===="+url);
    HttpGet get = new HttpGet(url);
    setTimeouts(get.getParams());
    HttpResponse response = client.execute(get);
   
           HttpEntity entity = response.getEntity();
           is = entity.getContent();
   }catch(Exception e){
    Log.e("log_tag", "Error in http connection "+e.toString());
   }    
   try{
         // BufferedReader reader = new BufferedReader(new InputStreamReader(is, HTTP.ISO_8859_1),8);
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8000);
           StringBuilder sb = new StringBuilder();
           String line = null;
           while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
           }
           is.close();
           result=sb.toString();
           Log.d("Web Responce", "===="+result);
   }catch(Exception e){
    Log.e("log_tag", "Error converting result "+e.toString());
   }
} else {
Builder builder = new AlertDialog.Builder(context);
             builder.setTitle("Error");
             builder.setMessage("No internet connection");
             builder.setCancelable(true);
             builder.setPositiveButton("cancel", null);
             AlertDialog dialog = builder.create();
             dialog.show();
}
   return result;
}

public final String postToURL(String url, HashMap<String, String> val){
InputStream is = null;
String result = "";
DefaultHttpClient client;
Log.d("POST VALUES",url+ val.toString());      
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "utf-8");
        params.setBooleanParameter("http.protocol.expect-continue", false);    
        HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, TIMEOUT);      
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));    
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);      
        client = new DefaultHttpClient(ccm, params);      
        client.getCredentialsProvider().setCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials("", ""));
   try{
    url = convertSpaceToEncode(url);
    Log.d("Web URL",url);
    HttpPost post = new HttpPost(url);    
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    Iterator<String> myVeryOwnIterator = val.keySet().iterator();
    while(myVeryOwnIterator.hasNext()) {
       String key=(String)myVeryOwnIterator.next();
       String value=(String)val.get(key);
       nameValuePairs.add(new BasicNameValuePair(key, value));
    }      
       post.setEntity(new UrlEncodedFormEntity(nameValuePairs));      
    setTimeouts(post.getParams());
    HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
   }catch(Exception e){
    Log.e("log_tag", "Error in http connection "+e.toString());
   }  
   try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");            
            }
            is.close();
            result=sb.toString();
            Log.d("Web Responce", result);
   }catch(Exception e){
    Log.e("log_tag", "Error converting result "+e.toString());
   }
 
   return result;
}
public String postFileWebservice(String url, HashMap<String, String> val, File file) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
Log.d("POST VALUES", "===="+val.toString());
Log.d("POST URL", "===="+url);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("filename", new FileBody(file));
Iterator<String> myVeryOwnIterator = val.keySet().iterator();
    while(myVeryOwnIterator.hasNext()) {
       String key=(String)myVeryOwnIterator.next();
       String value=(String)val.get(key);
       entity.addPart(key, new StringBody(value));
    }
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
Log.d("Responce", "===="+sResponse);
return sResponse;
} catch (Exception e) {
Log.e(e.getClass().getName(), e.getMessage(), e);
return "";
}
}
private static void setTimeouts(HttpParams params) {
   params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
   params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, SOCKET_TIMEOUT);
   params.setLongParameter(ConnManagerPNames.TIMEOUT, MCC_TIMEOUT);
}

public String convertSpaceToEncode(String str) {
   String url = null;
   try{
    url = new String(str.trim().replace(" ", "%20"));
   }catch(Exception e){
       e.printStackTrace();
   }
   return url;
}
public String convertSpaceToDecode(String str) {
   String url = null;
   try{
    url = new String(str.trim().replace("%20", " "));
   }catch(Exception e){
       e.printStackTrace();
   }
   return url;
}

/*** Check the Internet connectivity ***/
    public boolean isConnected()
{
ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
return false;
}

}

Image view Rounded

Classname:Imageroundedview

package  com.sample.imageroundedview

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class ImageViewRounded extends ImageView {

    public ImageViewRounded(Context context) {
        super(context);
    }

    public ImageViewRounded(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ImageViewRounded(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        try {
            BitmapDrawable drawable = (BitmapDrawable) getDrawable();

            if (drawable == null) {
                return;
            }

            if (getWidth() == 0 || getHeight() == 0) {
                return;
            }

            Bitmap fullSizeBitmap = drawable.getBitmap();

            int scaledWidth = getMeasuredWidth();
            int scaledHeight = getMeasuredHeight();

            Bitmap mScaledBitmap;
            if (scaledWidth == fullSizeBitmap.getWidth()
                    && scaledHeight == fullSizeBitmap.getHeight()) {
                mScaledBitmap = fullSizeBitmap;
            } else {
                mScaledBitmap = Bitmap.createScaledBitmap(fullSizeBitmap,
                        scaledWidth, scaledHeight, true /* filter */);
            }

            // Bitmap roundBitmap = getRoundedCornerBitmap(mScaledBitmap);

            // Bitmap roundBitmap = getRoundedCornerBitmap(getContext(),
            // mScaledBitmap, 10, scaledWidth, scaledHeight, false, false,
            // false, false);
            // canvas.drawBitmap(roundBitmap, 0, 0, null);

            Bitmap circleBitmap = getCircledBitmap(mScaledBitmap);

            canvas.drawBitmap(circleBitmap, 0, 0, null);
        }catch (Exception e){e.printStackTrace();}

    }

    public Bitmap getRoundedCornerBitmap(Context context, Bitmap input,
                                         int pixels, int w, int h, boolean squareTL, boolean squareTR,
                                         boolean squareBL, boolean squareBR) {

        Bitmap output = Bitmap.createBitmap(w, h, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final float densityMultiplier = context.getResources()
                .getDisplayMetrics().density;

        final int color = 0xff424242;

        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, w, h);
        final RectF rectF = new RectF(rect);

        // make sure that our rounded corner is scaled appropriately
        final float roundPx = pixels * densityMultiplier;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        // draw rectangles over the corners we want to be square
        if (squareTL) {
            canvas.drawRect(0, 0, w / 2, h / 2, paint);
        }
        if (squareTR) {
            canvas.drawRect(w / 2, 0, w, h / 2, paint);
        }
        if (squareBL) {
            canvas.drawRect(0, h / 2, w / 2, h, paint);
        }
        if (squareBR) {
            canvas.drawRect(w / 2, h / 2, w, h, paint);
        }

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(input, 0, 0, paint);

        return output;
    }

    Bitmap getCircledBitmap(Bitmap bitmap) {

        Bitmap result = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Config.ARGB_8888);

        Canvas canvas = new Canvas(result);

        int color = Color.BLUE;
        Paint paint = new Paint();
        Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
//        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        canvas.drawCircle(bitmap.getWidth()/2, bitmap.getHeight()/2, bitmap.getHeight()/2, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return result;
    }

}


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

xml file:
<com.sample.imageroundedview.Imageroundedview
            android:id="@+id/imgview"
            android:layout_width="100dp"

            android:layout_height="100dp">

11/02/2015

Aquery Using Value Posting

EditText _loginUserName,_loginPassword;
String _userNmaeText,_passwordText;
_loginUserName = (EditText)findViewById(R.id.login_userid);
_loginPassword = (EditText)findViewById(R.id.login_password);
LOGIN_API = "Your URL"; _userNmaeText =_loginUserName.getText().toString();
_passwordText =_loginPassword.getText().toString();
if (_userNmaeText.equals("")) {
 Toast.makeText(getApplicationContext(), "Enter UName", Toast.LENGTH_SHORT).show();
else if (_passwordText.equals("")) {
 Toast.makeText(getApplicationContext(), "Enter Pwd", Toast.LENGTH_SHORT).show();
}
else{
Handler handler=new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Map<String, String> params = new HashMap<String, String>();
params.put("userid", _userNmaeText);
params.put("password", _passwordText);
postAqueryLoginResult(LOGIN_API, params);
}
}, 1000);
}

private void postAqueryLoginResult(String lOGIN_API2,Map<String, String> params) {
try {
if (NetworkStatus.isConnected(_context)) {
_loginAQuery.ajax(lOGIN_API2, params, JSONObject.class,new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject json,AjaxStatus status) {
getLoginStatus(url, json, status);
}
});
}else {
Toast.makeText(getApplicationContext(), "Check Your Network",Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}

protected void getLoginStatus(String url, JSONObject jsonResult, AjaxStatus status) {
try {
  if (jsonResult.has("status"))
 {
    String loginStatus = jsonResult.getString("status");
   if (loginStatus.equals("Success")) {
    }
 }
} catch (Exception e) {
   e.printStackTrace();
}
}












26/06/2014