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

Check internet's connection ON/OFF event

public static int TYPE_WIFI = 1;
public static int TYPE_MOBILE = 2;
public static int TYPE_NOT_CONNECTED = 0;


public static int getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return TYPE_WIFI;

if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return TYPE_MOBILE;
}
return TYPE_NOT_CONNECTED;
}


public static String getConnectivityStatusString(Context context) {
int conn = NetworkUtil.getConnectivityStatus(context);
String status = null;
if (conn == NetworkUtil.TYPE_WIFI) {
status = "Wifi enabled";
} else if (conn == NetworkUtil.TYPE_MOBILE) {
status = "Mobile data enabled";
} else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
status = "Not connected to Internet";
}
return status;
}



public class NetStartReceiver extends BroadcastReceiver {
Context mContext;

@Override
public void onReceive(Context context, Intent intent) {

try {
String status =getConnectivityStatusString(context);
mContext = context;
if (status.equals("Wifi enabled")
|| status.equals("Mobile data enabled")) {


}
}
} catch (Exception ce) {
ce.printStackTrace();
}

}
}


receiver android:name="NetStartReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>

NotificationPanel with Button

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.RemoteViews;

public class NotificationPanel {

private Context parent;
private NotificationManager nManager;
private NotificationCompat.Builder nBuilder;
private RemoteViews remoteView;

public NotificationPanel(Context parent) {
// TODO Auto-generated constructor stub
this.parent = parent;
nBuilder = new NotificationCompat.Builder(parent)
.setContentTitle("")
.setSmallIcon(R.drawable.ic_launcher).setOngoing(true);

remoteView = new RemoteViews(parent.getPackageName(),
R.layout.notificationview);

// set the button listeners
setListeners(remoteView);
nBuilder.setContent(remoteView);

nManager = (NotificationManager) parent
.getSystemService(Context.NOTIFICATION_SERVICE);
nManager.notify(2, nBuilder.build());
}

public void setListeners(RemoteViews view) {
// listener 1
Intent volume = new Intent(parent, CameraONOFFService.class);



PreferenceSetting preferenceSetting = PreferenceSetting
.getInstance(parent);

if (!preferenceSetting.getON())
{

volume.putExtra("DO", "on");
view.setImageViewResource(R.id.btn1, R.drawable.off);
view.setInt(R.id.lay_main, "setBackgroundColor", android.graphics.Color.WHITE);
}
else
{

volume.putExtra("DO", "off");

view.setImageViewResource(R.id.btn1, R.drawable.on);
view.setInt(R.id.lay_main, "setBackgroundColor", android.graphics.Color.BLACK);
}

PendingIntent btn1 = PendingIntent.getService(parent, 0, volume, PendingIntent.FLAG_UPDATE_CURRENT);
view.setOnClickPendingIntent(R.id.lay_main, btn1);

}

public void notificationCancel() {
nManager.cancel(2);
}
}

Sunday 20 September 2015

Rest Client to call webservice

package com.cleanindia.utills;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;

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.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.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

public class RestClient {
public enum RequestMethod {
GET, POST
}
    private ArrayList <NameValuePair> params;
    private ArrayList <NameValuePair> headers;

    private String url;

    private int responseCode;
    private String message;

    private String response;

    public String getResponse() {
        return response;
    }

    public String getErrorMessage() {
        return message;
    }

    public int getResponseCode() {
        return responseCode;
    }

    public RestClient(String url)
    {
        this.url = url;
        params = new ArrayList<NameValuePair>();
        headers = new ArrayList<NameValuePair>();
    }

    public void AddParam(String name, String value)
    {
        params.add(new BasicNameValuePair(name, value));
    }

    public void AddHeader(String name, String value)
    {
        headers.add(new BasicNameValuePair(name, value));
    }

    public void Execute(RequestMethod method) throws Exception
    {
        switch(method) {
            case GET:
            {
                //add parameters
                String combinedParams = "";
                if(!params.isEmpty()){
                    combinedParams += "?";
                    for(NameValuePair p : params)
                    {
                        String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
                        if(combinedParams.length() > 1)
                        {
                            combinedParams  +=  "&" + paramString;
                        }
                        else
                        {
                            combinedParams += paramString;
                        }
                    }
                }

                HttpGet request = new HttpGet(url + combinedParams);

                //add headers
                for(NameValuePair h : headers)
                {
                    request.addHeader(h.getName(), h.getValue());
                }

                executeRequest(request, url);
                break;
            }
            case POST:
            {
                HttpPost request = new HttpPost(url);

                //add headers
                for(NameValuePair h : headers)
                {
                    request.addHeader(h.getName(), h.getValue());
                }

                if(!params.isEmpty()){
                    request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                }

                executeRequest(request, url);
                break;
            }
        }
    }

    private void executeRequest(HttpUriRequest request, String url)
    {
        HttpClient client = new DefaultHttpClient();
       

        HttpResponse httpResponse;

        try {
            httpResponse = client.execute(request);
            responseCode = httpResponse.getStatusLine().getStatusCode();
            message = httpResponse.getStatusLine().getReasonPhrase();

            HttpEntity entity = httpResponse.getEntity();

            if (entity != null) {

                InputStream instream = entity.getContent();
                response = convertStreamToString(instream);

                // Closing the input stream will trigger connection release
                instream.close();
            }

        } catch (ClientProtocolException e)  {
            client.getConnectionManager().shutdown();
            e.printStackTrace();
        } catch (IOException e) {
            client.getConnectionManager().shutdown();
            e.printStackTrace();
        }
    }

    private static String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

Saturday 19 September 2015

Web Service response object's class


public class BasicResponse {

private String mDescription = "";
private int mCode;



public String getDescription() {
return this.mDescription;

}

public void setDescription(String desc) {
this.mDescription = desc;

}

public int getCode() {
return this.mCode;

}

public void setCode(int code) {
this.mCode = code;

}

}

PreferenceSetting in Android

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class PreferenceSetting {


private String PREF_VALUE = "pref_value";

private static PreferenceSetting store;
SharedPreferences pref;

public static PreferenceSetting getInstance(Context context) {
if (store == null)
store = new PreferenceSetting(context);

return store;
}

private PreferenceSetting(Context context) {
pref = PreferenceManager.getDefaultSharedPreferences(context);
}

public void setValue(String value) {
pref.edit().putString(PREF_VALUE, value).commit();
}

public String getValue() {
return pref.getString(PREF_VALUE, "-");

}


}

Basic DataBase for Android




package com.app.util;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;


public class AppDbAdapter {

    private static final String DATABASE_NAME = "app.db";
    private static final String DATABASE_TABLE_COURSES = "courses";

    private static final int DATABASE_VERSION = 1;

    public static final String KEY_ID = "_id";
    public static final String KEY_COURSE_CID = "cid";
    public static final String KEY_COURSE_CNAME = "cname";
    public static final String KEY_COURSE_COUNT = "cdcount";


    private static final String DATABASE_CREATE_COURSE = "create table "            + DATABASE_TABLE_COURSES + " (" + KEY_ID            + " integer primary key autoincrement, " + KEY_COURSE_CID            + " integer, " + KEY_COURSE_CNAME + " text, " + KEY_COURSE_COUNT            + " integer);";


    // Variable to hold the database instance    private SQLiteDatabase db;

    // Context of the application using the database.    private final Context context;

    // Database open/upgrade helper    private DBHelper dbHelper;

    public AppDbAdapter(Context _context) {
        context = _context;
        dbHelper = new DBHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public AppDbAdapter open() throws SQLException {
        db = dbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        db.close();
    }

    public synchronized Cursor getAllCourses() {
        Cursor cursor = null;
        try {
            final String SQL_STATEMENT = "SELECT * FROM "                    + DATABASE_TABLE_COURSES + " order by " + KEY_COURSE_CID;

            cursor = db.rawQuery(SQL_STATEMENT, null);
        } catch (Exception e) {
            // TODO: handle exception            e.printStackTrace();
        }

        return cursor;
    }


   /* public long insertEntry(Document objDoc) {
        ContentValues contentValues = new ContentValues();        try {

            contentValues.put(KEY_COURSE_CID, objDoc.cid);            contentValues.put(KEY_DOCUMENT_DID, objDoc.id);            contentValues.put(KEY_DOCUMENT_PATH, objDoc.filepath);            contentValues.put(KEY_DOCUMENT_IMAGE_PATH, objDoc.imagePath);            contentValues.put(KEY_DOCUMENT_DATE, objDoc.date);            contentValues.put(KEY_DOCUMENT_NAME, objDoc.name);
        } catch (Exception e) {            // TODO: handle exception
            e.printStackTrace();        }        return db.insert(DATABASE_TABLE_DOCS, null, contentValues);    }*/
    public void truncateCourseTable() {

        try {
            db.execSQL("DROP TABLE " + DATABASE_TABLE_COURSES);

            db.execSQL(DATABASE_CREATE_COURSE);
        } catch (Exception ce) {
            ce.printStackTrace();
        }
    }

   /* public void truncateDocsTable() {
        try {            db.execSQL("DROP TABLE " + DATABASE_TABLE_DOCS);
            db.execSQL(DATABASE_CREATE_DOCS);        } catch (Exception ce) {            ce.printStackTrace();        }    }*/
    private static class DBHelper extends SQLiteOpenHelper {
        public DBHelper(Context context, String name, CursorFactory factory,
                        int version) {
            super(context, name, factory, version);
        }

        // Called when no database exists in disk and the helper class needs to        // create a new one        @Override        public void onCreate(SQLiteDatabase _db) {

            try {
                _db.execSQL(DATABASE_CREATE_COURSE);

            } catch (Exception e) {
                // TODO: handle exception                e.printStackTrace();
            }

        }

        @Override        public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

        }
    }
}

Basic functions of android 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) {
}
}