Monday, September 26, 2011

Touch Events


package com.sai.touch;


import android.app.Activity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.widget.Toast;


public class TouchActivity extends Activity implements OnGestureListener {


private GestureDetector gestureDetector;


@Override


public void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);


setContentView(R.layout.main);


gestureDetector = new GestureDetector(this);


}


@Override


public boolean onTouchEvent(MotionEvent event) {


return gestureDetector.onTouchEvent(event);


}


@Override


public boolean onDown(MotionEvent e) {


Toast.makeText(this,"oNDown called",Toast.LENGTH_SHORT).show();


return false;


}


@Override


public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,


float velocityY) {


Toast.makeText(this,"oNFling called",Toast.LENGTH_SHORT).show();
return false;


}


@Override


public void onLongPress(MotionEvent e) {


Toast.makeText(this,"OnLongPress called",Toast.LENGTH_SHORT).show();


}


@Override


public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,


float distanceY) {


Toast.makeText(this,"onScroll called",Toast.LENGTH_SHORT).show();


return false;


}


@Override
public void onShowPress(MotionEvent e) {


Toast.makeText(this,"onShowPress called",Toast.LENGTH_SHORT).show();


}


@Override


public boolean onSingleTapUp(MotionEvent e) {


Toast.makeText(this,"oNsingleTap called",Toast.LENGTH_SHORT).show();




return false;
}


}

How to Create a Dialog Window and Start a new Activity on the Selection

Java Code:



package com.sai.sample;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;


public class DialogWindow extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialogscreen);


final String items[] = {"Iphone","Android","TMobile"};


AlertDialog.Builder ab=new AlertDialog.Builder(DialogWindow.this);
ab.setTitle("Title");
ab.setSingleChoiceItems(items, 0,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// onClick Action
}
})
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {

if(items[0].contains("Iphone")){
startActivity(new Intent(DialogWindow.this,Iphone.class)); 
}

}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// on cancel button action
}
});
ab.show();
}
}


XMl Layout :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
    <TextView 
    android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Dialog Screen" 
android:id="@+id/textView1"
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content"></TextView>
    
</LinearLayout>


Click on the Dialog Button.


Select the Iphone Radio button and click on the Ok Button to start the new Activity.




Login Page for Android

Java Code:




package com.sencide;


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


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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class AndroidLogin extends Activity implements OnClickListener {

Button ok,back,exit;
TextView result;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        // Login button clicked
        ok = (Button)findViewById(R.id.btn_login);
        ok.setOnClickListener(this);
       
        result = (TextView)findViewById(R.id.lbl_result);
       
    }
   
    public void postLoginData() {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
       
        /* login.php returns true if username and password is equal to saranga */
        HttpPost httppost = new HttpPost("http://reddies.in/login.php");


        try {
            // Add user name and password
        EditText uname = (EditText)findViewById(R.id.txt_username);
        String username = uname.getText().toString();


        EditText pword = (EditText)findViewById(R.id.txt_password);
        String password = pword.getText().toString();
       
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("username", username));
            nameValuePairs.add(new BasicNameValuePair("password", password));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));


            // Execute HTTP Post Request
            Log.w("SENCIDE", "Execute HTTP Post Request");
            HttpResponse response = httpclient.execute(httppost);
           
            String str = inputStreamToString(response.getEntity().getContent()).toString();
            Log.w("SENCIDE", str);
           
            if(str.toString().equalsIgnoreCase("true"))
            {
            Log.w("SENCIDE", "TRUE");
            result.setText("Login successful");
            Intent intent = new Intent (AndroidLogin.this, Ok.class);
            startActivity(intent);
            finish();
           
            }else
            {
            Log.w("SENCIDE", "FALSE");
            result.setText(str);            
            }


        } catch (ClientProtocolException e) {
        e.printStackTrace();
        } catch (IOException e) {
        e.printStackTrace();
        }
    }

    private StringBuilder inputStreamToString(InputStream is) {
    String line = "";
    StringBuilder total = new StringBuilder();
    // Wrap a BufferedReader around the InputStream
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    // Read response until the end
    try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
    // Return full string
    return total;
    }


@Override
public void onClick(View view) {
if(view == ok){
postLoginData();
}
}


}


XMl Layout:




<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<EditText android:layout_width="150px" android:layout_height="wrap_content" android:textSize="18sp" android:id="@+id/txt_username" android:layout_y="132dip" android:layout_x="128dip"></EditText>
<EditText android:layout_width="150px" android:layout_height="wrap_content" android:textSize="18sp" android:password="true" android:id="@+id/txt_password" android:layout_x="128dip" android:layout_y="192dip"></EditText>
<Button android:layout_width="100px" android:layout_height="wrap_content" android:id="@+id/btn_login" android:layout_x="178dip" android:layout_y="252dip" android:text="Login"></Button>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/lbl_username" android:text="User Name" android:layout_x="37dip" android:layout_y="150dip"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/lbl_password" android:text="Password" android:layout_y="207dip" android:layout_x="50dip"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/lbl_top" android:textSize="16sp" android:typeface="sans" android:text="Please Loggin First" android:layout_x="29dip" android:layout_y="94dip"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_y="312dip" android:layout_x="50dip" android:id="@+id/lbl_result"></TextView>
</AbsoluteLayout>



Username and Password are hardcoded in the php file as Username:sai krishna Password :hello123


Friday, September 16, 2011

How to Set a AlertDialog before closing the App


@Override
public void onBackPressed() {
   AlertDialog.Builder builder = new AlertDialog.Builder(this);
   builder.setMessage("Are you sure you want to exit?")
          .setCancelable(false)
          .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int id) {
                   FirstScreenActivity.this.finish();
              }
          })
          .setNegativeButton("No", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int id) {
                   dialog.cancel();
              }
          });
   AlertDialog alert = builder.create();
   alert.show();


}

Android Grid View Gallery

XMl Layout:



<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content">


<ImageView android:id="@+id/ImageView01"
android:layout_width="fill_parent" 
android:layout_height="fill_parent"
android:layout_centerHorizontal="true" 
android:scaleType="fitXY"/>


<ScrollView android:id="@+id/ScrollView01"
android:layout_width="wrap_content" 
android:layout_below="@+id/ImageView01"
android:layout_height="fill_parent">


</ScrollView>


<Button android:id="@+id/Button01" 
android:layout_above="@id/ScrollView01"
android:layout_width="wrap_content" 
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" 


android:text="Close" />





Java Source Code:



package com.sai.grid;


import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;


public class gridview extends Activity {
//---the thumbnail images to display---
Integer[] imageIDs = {
R.drawable.a_1, R.drawable.a_2, R.drawable.a_3, R.drawable.a_4,
R.drawable.sample_2, R.drawable.sample_3,
         R.drawable.sample_4, R.drawable.sample_5,
         R.drawable.sample_6, R.drawable.sample_7,
         R.drawable.sample_0, R.drawable.sample_1,
         R.drawable.sample_2, R.drawable.sample_3,
         R.drawable.sample_4, R.drawable.sample_5,
         R.drawable.sample_6, R.drawable.sample_7,
         R.drawable.sample_0, R.drawable.sample_1,
         R.drawable.sample_2, R.drawable.sample_3,
         R.drawable.sample_4, R.drawable.sample_5,
         R.drawable.sample_6, R.drawable.sample_7
};
//---the actual images to display---
Integer[] imageLargeIDs = {
R.drawable.a_1, R.drawable.a_2, R.drawable.a_3, R.drawable.a_4,
R.drawable.sample_2, R.drawable.sample_3,
         R.drawable.sample_4, R.drawable.sample_5,
         R.drawable.sample_6, R.drawable.sample_7,
         R.drawable.sample_0, R.drawable.sample_1,
         R.drawable.sample_2, R.drawable.sample_3,
         R.drawable.sample_4, R.drawable.sample_5,
         R.drawable.sample_6, R.drawable.sample_7,
         R.drawable.sample_0, R.drawable.sample_1,
         R.drawable.sample_2, R.drawable.sample_3,
         R.drawable.sample_4, R.drawable.sample_5,
         R.drawable.sample_6, R.drawable.sample_7
};


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set up main content view
setContentView(R.layout.main);


GridView gridView = (GridView) findViewById(R.id.gridview);
gridView.setAdapter(new ImageAdapter(this));


gridView.setOnItemClickListener(new OnItemClickListener()
{
            public void onItemClick(AdapterView parent,
View v, int position, long id)
{
                final Dialog dialog = new Dialog(gridview.this);
dialog.setContentView(R.layout.layoutdialog);
dialog.setTitle("Gallery Review");
dialog.setCancelable(true);


//set up image view
ImageView img = (ImageView) dialog.findViewById(R.id.ImageView01);
img.setPadding(5, 5, 5, 5);




img.setImageResource(imageLargeIDs[position]);


//set up button
Button button = (Button) dialog.findViewById(R.id.Button01);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
        dialog.dismiss();
}
});
//now that the dialog is set up, it's time to show it
dialog.show();
}
});


}


public class ImageAdapter extends BaseAdapter
{
private Context context;


public ImageAdapter(Context c)
{
context = c;
}


//---returns the number of images---
public int getCount() {
return imageIDs.length;
}


//---returns the ID of an item---
public Object getItem(int position) {
return position;
}


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


//---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(80,80));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setPadding(5, 5, 5, 5);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(imageIDs[position]);
return imageView;
}
}
}




Click on any one of the Image.




Android ListView with Searchbox Sort items

XML layout


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical">

<EditText android:id="@+id/EditText01" 

android:layout_height="wrap_content" 
android:layout_width="fill_parent"
 android:hint="Search"></EditText>

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

</LinearLayout>

Java Source Code

package com.sai.sample;

import java.util.ArrayList;



import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;


public class Sort extends Activity {

private  ListView listview;
private  EditText edittext;
private String list[]={"Iphone",
"Cupcake","Andoird","Blackberry","Samsung","Nokia"
   
    };
private ArrayList<String > arraylist= new ArrayList<String>();
private int textlenght=0;
@Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.listview);
       
       listview=(ListView)findViewById(R.id.ListView01);
       edittext=(EditText)findViewById(R.id.EditText01);
       listview.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , list));
       edittext.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
textlenght=edittext.getText().length();
arraylist.clear();
for(int i=0;i<list.length;i++){
if(textlenght<=list[i].length())
       {
       if(edittext.getText().toString().equalsIgnoreCase((String) list[i].subSequence(0, textlenght)))
       {
       arraylist.add(list[i]);
       }
       }
}
listview.setAdapter(new ArrayAdapter<String>(Sort.this,android.R.layout.simple_list_item_1 , arraylist));
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
}
});
       
       }
}

Run as Android Application