Monday, July 14, 2014

CalenderView Example

Hi Guys,

Today I am sharing the code for CalenderView. This class is a calendar widget for displaying and selecting dates. The range of dates supported by this calendar is configurable. A user can select a date by taping on it and can scroll and fling the calendar to a desired date.

activity_main.xml







MainActivity.java

package com.sunil.calenderexample;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CalendarView;
import android.widget.CalendarView.OnDateChangeListener;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity implements OnDateChangeListener {

private CalendarView calenderview=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
calenderview=(CalendarView)findViewById(R.id.calendarView_cl);
calenderview.setOnDateChangeListener(this);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

@Override
public void onSelectedDayChange(CalendarView arg0, int arg1, int arg2, int arg3) {

Toast.makeText(getBaseContext(), arg1+"/"+arg2+"/"+arg3, Toast.LENGTH_LONG).show();
}
}


Result is:
Here you can download the source code CalenderView Example

Saturday, June 21, 2014

Check Network Connectivity

Hi Guys,

I am sharing the code for check the internet connectivity of your device either mobile or wifi connectivity.
More detail Here 
Java Code:

private void checkNetworkConnection() {
ConnectivityManager connMgr =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
if (activeInfo != null && activeInfo.isConnected()) {
wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
if(wifiConnected) {
Log.i(TAG, "WIFI connected");
} else if (mobileConnected){
Log.i(TAG, "Mobile Connected");
}
} else {
Log.i(TAG,"Neither Mobile nor WIFi connected.");
}
}
or second way

public static boolean isInternetOn(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
Log.v("Util", "Internet is working");
// txt_status.setText("Internet is working");
return true;
} else {
// txt_status.setText("Internet Connection Not Present");
Log.v("Util", "Internet Connection Not Present");
return false;
}
}
Please do not forget to add the permission in AndroidMenifest file.




Monday, November 4, 2013

Multiple Row Item Deleted from Listview Android

Hi Guys!!

First of all Happy Diwali to all my friends and fans.

In this article we are learning the new android API concept that delete the multiple  row item of the list view.
Before we have knowledge about the delete the row item with the help of check box. But in new API-18 have provide the features to delete the multiple row item from the list-view without the check-box uses.

This feature is available inside the contextual action mode in higher android version 3.0. So here question is what is contextual action mode?
The contextual action mode is a system implementation of ActionMode that focuses user interaction toward performing contextual actions. When a user enables this mode by selecting an item, a contextual action bar appears at the top of the screen to present actions the user can perform on the currently selected item(s). While this mode is enabled, the user can select multiple items (if you allow it), deselect items, and continue to navigate within the activity (as much as you're willing to allow). The action mode is disabled and the contextual action bar disappears when the user deselects all items, presses the BACK button, or selects the Done action on the left side of the bar.

This event happen when the user performs a long-click on the view.  Contextual actions on groups of items in a ListView or GridView (allowing the user to select multiple items and perform an action on them all).
More details about this contextual menu. and MultiChoiceModeListener.

So lets start the to coding to see this features.


main_activity.xml









MainActivity.java

package com.sunil.listviewmuntilerowdelete;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.ListView;

@SuppressLint("NewApi")
public class MainActivity extends Activity implements MultiChoiceModeListener{

private String[] myfriendname=null;
private String[] myfriendnickname=null;
private int[] photo=null;
ListView listView=null;
Context contex=null;
MyListAdapter adapter=null;
private List list=new ArrayList();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contex=this;
listView = (ListView) findViewById(R.id.listview);

myfriendname = new String[] { "Sunil Gupta", "Abhishek Tripathi","Sandeep Pal", "Amit Verma" };
myfriendnickname = new String[] { "sunil android", "Abhi cool","Sandy duffer", "Budhiya jokar"};
photo = new int[] { R.drawable.sunil, R.drawable.abhi, R.drawable.sandy, R.drawable.amit};

for(int index=0; index< myfriendname.length; index++){
MyFriendsSDetails details=new MyFriendsSDetails(myfriendname[index], myfriendnickname[index], photo[index]);
list.add(details);
}

adapter=new MyListAdapter(contex, list);
listView.setAdapter(adapter);
listView.setMultiChoiceModeListener(this);
listView.setChoiceMode(listView.CHOICE_MODE_MULTIPLE_MODAL);

}
@Override
public boolean onActionItemClicked(ActionMode arg0, MenuItem arg1) {
switch (arg1.getItemId()) {
case R.id.delete:
SparseBooleanArray selected = adapter.getSelectedIds();
for (int i = (selected.size() - 1); i >= 0; i--) {
if (selected.valueAt(i)) {
MyFriendsSDetails selecteditem = adapter.getItem(selected.keyAt(i));
adapter.remove(selecteditem);
}
}
// Close CAB
arg0.finish();
return true;
default:
return false;
}
}
@Override
public boolean onCreateActionMode(ActionMode arg0, Menu arg1) {
arg0.getMenuInflater().inflate(R.menu.main, arg1);
return true;

}
@Override
public void onDestroyActionMode(ActionMode arg0) {
adapter.removeSelection();
}
@Override
public boolean onPrepareActionMode(ActionMode arg0, Menu arg1) {
return false;
}
@Override
public void onItemCheckedStateChanged(ActionMode arg0, int arg1, long arg2, boolean arg3) {

final int checkedCount = listView.getCheckedItemCount();
arg0.setTitle(checkedCount + " Selected");
adapter.toggleSelection(arg1);
}

}

MyFriendsSDetails.java

package com.sunil.listviewmuntilerowdelete;

public class MyFriendsSDetails {

private String myfriendname=null;
private String myfriendnickname=null;
private int photo=0;

public MyFriendsSDetails(String friendname, String friendnickname, int myphoto){
this.myfriendname=friendname;
this.myfriendnickname=friendnickname;
this.photo=myphoto;
}

public String getMyfriendname() {
return myfriendname;
}

public void setMyfriendname(String myfriendname) {
this.myfriendname = myfriendname;
}

public String getMyfriendnickname() {
return myfriendnickname;
}

public void setMyfriendnickname(String myfriendnickname) {
this.myfriendnickname = myfriendnickname;
}

public int getPhoto() {
return photo;
}

public void setPhoto(int photo) {
this.photo = photo;
}


}

list_item.xml













MyListAdapter.java

package com.sunil.listviewmuntilerowdelete;

import java.util.List;

import android.content.Context;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class MyListAdapter extends ArrayAdapter{

Context context;
LayoutInflater inflater;
List list;
private SparseBooleanArray mSelectedItemsIds;

public MyListAdapter(Context context, List list) {
super(context, 0, list);
mSelectedItemsIds = new SparseBooleanArray();
this.context = context;
this.list = list;
inflater = LayoutInflater.from(context);
}

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

final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_item, null);
holder.name = (TextView) convertView.findViewById(R.id.title);
holder.nickname = (TextView) convertView.findViewById(R.id.subtitle);
holder.photo = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(list.get(position).getMyfriendname());
holder.nickname.setText(list.get(position).getMyfriendnickname());
holder.photo.setImageResource(list.get(position).getPhoto());
return convertView;
}

public void toggleSelection(int position) {
selectView(position, !mSelectedItemsIds.get(position));
}

public void selectView(int position, boolean value) {
if (value)
mSelectedItemsIds.put(position, value);
else
mSelectedItemsIds.delete(position);
notifyDataSetChanged();
}

public void removeSelection() {
mSelectedItemsIds = new SparseBooleanArray();
notifyDataSetChanged();
}

public SparseBooleanArray getSelectedIds() {
return mSelectedItemsIds;
}
private class ViewHolder {
TextView name;
TextView nickname;
ImageView photo;
}
}
Screen shot:


You can download the full source code ListViewMultipleRowDelete and here

Cheers Guys!!

Sunday, October 13, 2013

Alarm via BoardCast Reciever Android

Hi Guys,

This tutorial might be helpful for leaning about the Alarm with Broadcast Receiver in android.
A Broadcast Receiver is an Android component which allows you to register for system or application events. All registered receivers for an event will be notified by the Android run-time once this event happens. 

A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). Once your code returns from this function, the system considers the object to be finished and no longer active.

If registering a receiver in your Activity.onResume() implementation, you should unregistered it in Activity.onPause(). (You won't receive intents when paused, and this will cut down on unnecessary system overhead). Do not unregistered in Activity.onSaveInstanceState(), because this won't be called if the user moves back in the history stack.  More detail about broadcast receiever Here.

Alarm Manager class provides access to the system alarm services. These allow you to schedule your application to be run at some point in the future. When an alarm goes off, the Intent that had been registered for it is broadcast by the system, automatically starting the target application if it is not already running. Registered alarms are retained while the device is asleep (and can optionally wake the device up if they go off during that time), but will be cleared if it is turned off and rebooted.

The Alarm Manager holds a CPU wake lock as long as the alarm receiver's onReceive() method is executing. This guarantees that the phone will not sleep until you have finished handling the broadcast. Once onReceive() returns, the Alarm Manager releases this wake lock. This means that the phone will in some cases sleep as soon as your onReceive() method completes.

There are two way we can registered and unregistered the broadcast receive.
1. Dynamic way
2. Static Way 

Dynamic way:-

You can register a receiver dynamically via the Context.registerReceiver() method. You can also dynamically unregister receiver by using Context.unregisterReceiver() method.

Static Way:-

You can use the PackageManager class to enable or disable receivers registered in your AndroidManifest.xml file.
For Register
ComponentName receiver = new ComponentName(this, AlarmManagerBR.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
For UnRegister
ComponentName receiver = new ComponentName(this, AlarmManagerBR.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);

main_activity.xml




MainActivity.java

package com.sunil.br;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

private Button btnstartalarm=null;
private Button btncancelalarm=null;
private Button btnenablebr=null;
private Button btndiablebr=null;
AlarmManager amanager=null;
PendingIntent pi=null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btnstartalarm = (Button)findViewById(R.id.button_startalarm);
btncancelalarm = (Button)findViewById(R.id.button_cancelalarm);
btnenablebr = (Button)findViewById(R.id.button_enablebr);
btndiablebr = (Button)findViewById(R.id.button_disablebr);

btnstartalarm.setOnClickListener(this);
btndiablebr.setOnClickListener(this);
btncancelalarm.setOnClickListener(this);
btnenablebr.setOnClickListener(this);

}

@Override
public void onClick(View arg0) {

if(arg0==btnstartalarm)
{
amanager=(AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
Intent intent= new Intent(this, AlarmManagerBR.class);
pi=PendingIntent.getBroadcast(this, 0, intent, 0);
//After after 2 seconds
amanager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000*4, pi);
Toast.makeText(this, "Start Repating Alarm", Toast.LENGTH_SHORT).show();

}
else if (arg0==btncancelalarm) {

amanager.cancel(pi);
Toast.makeText(this, "Canceled Alarm", Toast.LENGTH_SHORT).show();
}

else if(arg0==btnenablebr){

ComponentName receiver = new ComponentName(this, AlarmManagerBR.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
Toast.makeText(this, "Enable Boradcast Reciever", Toast.LENGTH_SHORT).show();
}
else if (arg0==btndiablebr) {

ComponentName receiver = new ComponentName(this, AlarmManagerBR.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
Toast.makeText(this, "Diable Boradcast Reciever", Toast.LENGTH_SHORT).show();
}
}
}

AlarmManagerBR.java

package com.sunil.br;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class AlarmManagerBR extends BroadcastReceiver{

@SuppressLint("SimpleDateFormat")
@Override
public void onReceive(Context arg0, Intent arg1) {

StringBuilder sb=new StringBuilder();
SimpleDateFormat format=new SimpleDateFormat("hh:mm:ss a");
sb.append(format.format(new Date()));
Toast.makeText(arg0, sb, Toast.LENGTH_SHORT).show();
}

}

Manifest.xml


















You can download the source code BoradCastRecieverExample
Cheers Guys!!

Saturday, October 5, 2013

Insert And Retrieve Image into DB

Hi Guys,

In this tutorial we are sharing the code to insert the image into db and retrieve the image from db. I hope this article might be helpful to all learning developer.

SQLite is really a quick and compact android database technology which incorporates SQL syntax to create queries and also handle data.

Android SDK by itself provides the SQLite support which without doubt making the setup as well as utilization process within our applications with no trouble.

Whenever we make use of an Android SQLite Database all of us undoubtedly require the help of SQLiteOpenHelper to handle our data.SQLiteOpenHelper is surely an superb destination to place some initial values right into the android sqlite database when it is built.

For storing the image we are using the blob type. Blob is a Java interface representing the SQL BLOB type.
An SQL BLOB type stores a large array of binary data (bytes) as the value in a column of a database.
The java.sql.Blob interface provides methods for setting and retrieving data in the Blob, for querying Blob data length, and for searching for data within the Blob. More details about Blob Here

But i think in big level storing the image in database is not valuable because database sqlite have limited space so store the image path is valuable.

main_activity.xml








MainActivity.java

package com.sunil.insertimageindb;

import java.io.ByteArrayOutputStream;

import com.sunil.insertimageindb.R;

import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

private ImageView imageview=null;
private Button btninsert=null;
private Button btnretrive=null;
private MyDataBase mdb=null;
private SQLiteDatabase db=null;
private Cursor c=null;
private byte[] img=null;
private static final String DATABASE_NAME = "ImageDb.db";
public static final int DATABASE_VERSION = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btninsert=(Button)findViewById(R.id.button_insert);
btnretrive= (Button)findViewById(R.id.button_retrieve);
imageview= (ImageView)findViewById(R.id.imageView_image);
imageview.setImageResource(0);
btninsert.setOnClickListener(this);
btnretrive.setOnClickListener(this);
mdb=new MyDataBase(getApplicationContext(), DATABASE_NAME,null, DATABASE_VERSION);


Bitmap b=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 100, bos);
img=bos.toByteArray();
db=mdb.getWritableDatabase();
}
@Override
public void onClick(View arg0) {

if(btninsert==arg0)
{
ContentValues cv=new ContentValues();
cv.put("image", img);
db.insert("tableimage", null, cv);
Toast.makeText(this, "inserted successfully", Toast.LENGTH_SHORT).show();
}
else if(btnretrive==arg0)
{
String[] col={"image"};
c=db.query("tableimage", col, null, null, null, null, null);

if(c!=null){
c.moveToFirst();
do{
img=c.getBlob(c.getColumnIndex("image"));
}while(c.moveToNext());
}
Bitmap b1=BitmapFactory.decodeByteArray(img, 0, img.length);

imageview.setImageBitmap(b1);
Toast.makeText(this, "Retrive successfully", Toast.LENGTH_SHORT).show();
}
}

}

MyDatabase.java

package com.sunil.insertimageindb;


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

public class MyDataBase extends SQLiteOpenHelper{

public MyDataBase(Context context, String dbname, CursorFactory factory, int dbversion) {
super(context, dbname, factory, dbversion);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table tableimage(image blob);");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

}

Store the image in db looks like that


You can download the source code InsertImageintoDB.
Cheers Guys!!

Wednesday, October 2, 2013

PayPal Android SDK With Multiple In-App Payment

Hi Guys,

I hope this tutorial and article might be helpful for all android developer to make a multiple payment with this new android sdk pay pal in app.
PayPal announced a new Android SDK that tries to make it easier for developers to accept in-app payments on Google�s mobile platform.
As expected, the Android payments solution accepts both PayPal and credit card payments. The company says it is quick and easy to use, and �removes payment friction so developers can focus on creating amazing experiences.�

PayPal�s strategy is to make it as easy as possible for mobile developers to integrate its payments into their work. The pitch is simple: if consumers don�t have to leave your app to pay, and they can do so in more ways than one (click a PayPal button or scan a credit/debit card), they will be more likely to do so.

The new PayPal Android SDK supports Android version 2.2 and up. The new Android payment solution will allow developers to accept payments via PayPal and via credit cards. PayPal believes that giving users the option to pay quickly and easily via their PayPal account or by scanning a credit card will lure more customers into paying developers for their work.

PayPal says that it is also offering security features that will allow developers to �significantly reduce� fraud they encounter with payments. So I think that its really amazing concept for android developer.
More in detail visit the pay pal developer site and git-hub repository Pay Pay Developer.

 
 

main_activity.xml




MainActivity.java

package com.paypal.sunil.paypalandroidsdk;

import java.math.BigDecimal;

import org.json.JSONException;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;

public class MainActivity extends Activity {

// set to PaymentActivity.ENVIRONMENT_LIVE to move real money.
// set to PaymentActivity.ENVIRONMENT_SANDBOX to use your test credentials from https://developer.paypal.com
// set to PaymentActivity.ENVIRONMENT_NO_NETWORK to kick the tires without communicating to PayPal's servers.
private static final String CONFIG_ENVIRONMENT = PaymentActivity.ENVIRONMENT_NO_NETWORK;

// note that these credentials will differ between live & sandbox environments.
private static final String CONFIG_CLIENT_ID = "credential from developer.paypal.com";
// when testing in sandbox, this is likely the -facilitator email address.
private static final String CONFIG_RECEIVER_EMAIL = "matching paypal email address";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Intent intent = new Intent(this, PayPalService.class);

intent.putExtra(PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT, CONFIG_ENVIRONMENT);
intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, CONFIG_CLIENT_ID);
intent.putExtra(PaymentActivity.EXTRA_RECEIVER_EMAIL, CONFIG_RECEIVER_EMAIL);

startService(intent);
}

public void onBuyPressed(View pressed) {
PayPalPayment thingToBuy = new PayPalPayment(new BigDecimal("1.75"), "USD", "hipster jeans");

Intent intent = new Intent(this, PaymentActivity.class);

intent.putExtra(PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT, CONFIG_ENVIRONMENT);
intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, CONFIG_CLIENT_ID);
intent.putExtra(PaymentActivity.EXTRA_RECEIVER_EMAIL, CONFIG_RECEIVER_EMAIL);

// It's important to repeat the clientId here so that the SDK has it if Android restarts your
// app midway through the payment UI flow.
intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, "credential-from-developer.paypal.com");
intent.putExtra(PaymentActivity.EXTRA_PAYER_ID, "your-customer-id-in-your-system");
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);

startActivityForResult(intent, 0);
}

@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
Log.i("paymentExample", confirm.toJSONObject().toString(4));

// TODO: send 'confirm' to your server for verification.
// see https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
// for more details.

} catch (JSONException e) {
Log.e("paymentExample", "an extremely unlikely failure occurred: ", e);
}
}
}
else if (resultCode == Activity.RESULT_CANCELED) {
Log.i("paymentExample", "The user canceled.");
}
else if (resultCode == PaymentActivity.RESULT_PAYMENT_INVALID) {
Log.i("paymentExample", "An invalid payment was submitted. Please see the docs.");
}
}

@Override
public void onDestroy() {
stopService(new Intent(this, PayPalService.class));
super.onDestroy();
}
}

Manifest.xml













































You can download the source code PaypalSDK

Saturday, September 28, 2013

Custom ListView AlertDialog With Filter and Search

Hi Guys,

I hope this tutorial might be helpful to all android developer to search or filter the item of the custom list view.
Here the list view which shows in Alert-dialog. And we can search the item of the list view.

Here I am creating the ListView and Editext programatically and search the item of the list view.
So lets start the coding to search the item of the listview in alert dialog.


Main_activity.xml






alertlistrow.xml








MainActivity.java

package com.sunil.listviewdialog;

import java.util.ArrayList;
import java.util.Arrays;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;

public class MainActivity extends Activity implements OnClickListener, OnItemClickListener{

private Button btn_listviewdialog=null;
private EditText txt_item=null;
private String TitleName[]={"Sunil Gupta","Ram Chnadra"," Abhishek Tripathi","Amit Verma","Sandeep Pal","Awadhesh Diwakar","Shishir Verma","Ravi Vimal","Prabhakr Singh","Manish Srivastva","Jitendra Singh","Surendra Pal"};
private ArrayList array_sort;
int textlength=0;
private AlertDialog myalertDialog=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

txt_item=(EditText)findViewById(R.id.editText_item);
btn_listviewdialog=(Button)findViewById(R.id.button_listviewdialog);
btn_listviewdialog.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {

AlertDialog.Builder myDialog = new AlertDialog.Builder(MainActivity.this);

final EditText editText = new EditText(MainActivity.this);
final ListView listview=new ListView(MainActivity.this);
editText.setCompoundDrawablesWithIntrinsicBounds(R.drawable.discoverseed_larg1, 0, 0, 0);
array_sort=new ArrayList (Arrays.asList(TitleName));
LinearLayout layout = new LinearLayout(MainActivity.this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(editText);
layout.addView(listview);
myDialog.setView(layout);
CustomAlertAdapter arrayAdapter=new CustomAlertAdapter(MainActivity.this, array_sort);
listview.setAdapter(arrayAdapter);
listview.setOnItemClickListener(this);
editText.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable s){

}
public void beforeTextChanged(CharSequence s,
int start, int count, int after){

}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
editText.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
textlength = editText.getText().length();
array_sort.clear();
for (int i = 0; i < TitleName.length; i++)
{
if (textlength <= TitleName[i].length())
{

if(TitleName[i].toLowerCase().contains(editText.getText().toString().toLowerCase().trim()))
{
array_sort.add(TitleName[i]);
}
}
}
listview.setAdapter(new CustomAlertAdapter(MainActivity.this, array_sort));
}
});
myDialog.setNegativeButton("cancel", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});

myalertDialog=myDialog.show();

}
@Override
public void onItemClick(AdapterView arg0, View arg1, int position, long arg3) {

myalertDialog.dismiss();
String strName=TitleName[position];
txt_item.setText(strName);
}

}

CustomAlertAdapter.java

package com.sunil.listviewdialog;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class CustomAlertAdapter extends BaseAdapter{

Context ctx=null;
ArrayList listarray=null;
private LayoutInflater mInflater=null;
public CustomAlertAdapter(Activity activty, ArrayList list)
{
this.ctx=activty;
mInflater = activty.getLayoutInflater();
this.listarray=list;
}
@Override
public int getCount() {

return listarray.size();
}

@Override
public Object getItem(int arg0) {
return null;
}

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

@Override
public View getView(int position, View convertView, ViewGroup arg2) {
final ViewHolder holder;
if (convertView == null ) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.alertlistrow, null);

holder.titlename = (TextView) convertView.findViewById(R.id.textView_titllename);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}

String datavalue=listarray.get(position);
holder.titlename.setText(datavalue);

return convertView;
}

private static class ViewHolder {
TextView titlename;
}
}





You can download the source code CustomListviewFilter.
Cheers Guys! 

 

Copyright @ 2013 Android Developers Tipss.