Search This Blog

Sunday, March 24, 2013

Tween animation: Rotate animation

Create /res/anim/rotate_center.xml for animation of rotating around center
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<rotate
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="2000"
android:startOffset="0"/>
</set>


Create /res/anim/rotate_corner.xml for animation of rotating around the upper-left corner


<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<rotate
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="0%"
android:pivotY="0%"
android:duration="2000"
android:startOffset="0"/>
</set>



modify main.xml as below.

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

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Button
android:id="@+id/rotatecenter"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Rotate around center"/>
<Button
android:id="@+id/rotatecorner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Rotate around corner"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center">

<ImageView
android:id="@+id/floatingimage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />

</LinearLayout>

</LinearLayout>


main activitypackage com.exercise.AndroidAnimTranslate;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;

public class AndroidAnimTranslateActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button buttonRotateCenter = (Button)findViewById(R.id.rotatecenter);
Button buttonRotateCorner = (Button)findViewById(R.id.rotatecorner);
final ImageView floatingImage = (ImageView)findViewById(R.id.floatingimage);

final Animation animationRotateCenter = AnimationUtils.loadAnimation(this, R.anim.rotate_center);
buttonRotateCenter.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
floatingImage.startAnimation(animationRotateCenter);
}});

final Animation animationRotateCorner = AnimationUtils.loadAnimation(this, R.anim.rotate_corner);
buttonRotateCorner.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
floatingImage.startAnimation(animationRotateCorner);
}});
}
}

Sunday, March 3, 2013

Calling the web-service in android with POST and GET method

Hello guys Here i am posting the method of calling the webservice in android using POST and GET method.


public class RestClient {

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

Now here is the calling example of the method.

RestClient client = new RestClient(URL of the webservice); 
client.AddParam("param1", "String of param1"); 
client.AddParam("param2", "String of param2"); 
client.AddParam("Email", email); 
client.AddParam("Passwd", passcode); 
          try { 
                   client.Execute(RequestMethod.POST);  //  OR GET 
              }   
            catch (Exception e) {  
                  e.printStackTrace(); 
            }
 String response = client.getResponse();

Friday, February 8, 2013

Get the current location from the location listener


public class MainActivity extends Activity {

public TextView t;
LocationManager locationManager;
LocationListener locationListener;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t = (TextView) findViewById(R.id.Text1);

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
5000, 10, locationListener);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}

private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location loc) {

t.setText("");

Toast.makeText(
getBaseContext(),
"Location changed: Lat: " + loc.getLatitude() + " Lng: "
+ loc.getLongitude(), Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " + loc.getLongitude();
Log.v("long/lant", longitude);
String latitude = "Latitude: " + loc.getLatitude();
Log.v("long/lant", latitude);

String cityName = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());

List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getLocality(); 
} catch (IOException e) {
e.printStackTrace();
}

String s = longitude + "\n" + latitude + "\n\nMy Current City is: "
+ cityName;
t.setText(s);
}

@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}

@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}

Monday, February 4, 2013

ROTATE MULTIPLE IMAGES IN SINGLE IMAGE VIEW LIKE A VIDEO

First of all add all the images in drawable no metter how big it is.

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;

public class MainActivity extends Activity {

                  ImageView image1;
                  Gallery gallery;
                  private Runnable r;
                  private static int i = 0;
                  int[] image_array = { R.drawable.i_pad0000, R.drawable.i_pad0001,
                                       R.drawable.i_pad0002, R.drawable.i_pad0003, R.drawable.i_pad0004,
                                      R.drawable.i_pad0005, R.drawable.i_pad0006, R.drawable.i_pad0007,
                                      R.drawable.i_pad0008, R.drawable.i_pad0009, R.drawable.i_pad0010,
                                      R.drawable.i_pad0011, R.drawable.i_pad0012, R.drawable.i_pad0013,
                                      R.drawable.i_pad0014, R.drawable.i_pad0015, R.drawable.i_pad0016,
                                      R.drawable.i_pad0017, R.drawable.i_pad0018, R.drawable.i_pad0019,
                                      R.drawable.i_pad0020, R.drawable.i_pad0021, R.drawable.i_pad0022,
                                      R.drawable.i_pad0023, R.drawable.i_pad0024, R.drawable.i_pad0025,
                                      R.drawable.i_pad0027, R.drawable.i_pad0028, R.drawable.i_pad0029,
                                      R.drawable.i_pad0030, R.drawable.i_pad0031, R.drawable.i_pad0032,
                                      R.drawable.i_pad0033, R.drawable.i_pad0034, R.drawable.i_pad0035,
                                      R.drawable.i_pad0036, R.drawable.i_pad0037, R.drawable.i_pad0038,
                                      R.drawable.i_pad0039, R.drawable.i_pad0040, R.drawable.i_pad0041,
                                      R.drawable.i_pad0042, R.drawable.i_pad0043, R.drawable.i_pad0044,
                                      R.drawable.i_pad0045, R.drawable.i_pad0046, R.drawable.i_pad0047,
                                      R.drawable.i_pad0048, R.drawable.i_pad0049, R.drawable.i_pad0050,
                                      R.drawable.i_pad0051, R.drawable.i_pad0052, R.drawable.i_pad0053,
                                      R.drawable.i_pad0054, R.drawable.i_pad0055, R.drawable.i_pad0056,
                                      R.drawable.i_pad0057, R.drawable.ipad0058, R.drawable.i_pad0059,
                                      R.drawable.i_pad0060, R.drawable.i_pad0061, R.drawable.i_pad0062,
                                      R.drawable.i_pad0063, R.drawable.i_pad0064, R.drawable.i_pad0065,
                                      R.drawable.i_pad0066, R.drawable.i_pad0067, R.drawable.i_pad0068,
                                      R.drawable.i_pad0069, R.drawable.i_pad0070, R.drawable.i_pad0071,
                                      R.drawable.i_pad0072, R.drawable.i pad0073, R.drawable.i_pad0074};

                  int[] verse_titles_hindi = { R.drawable.img_1,
                                     R.drawable.img_2, R.drawable.img_3,
                                     R.drawable.img_4, R.drawable.img_5,
                                     R.drawable.img_6, R.drawable.v_7,
                                     R.drawable.img_8, R.drawable.img_9,
                                     R.drawable.img_10, R.drawable.img_11,
                                     R.drawable.img_12, R.drawable.img_13,
                                     R.drawable.img_14, R.drawable.img_15,
                                     R.drawable.img_16, R.drawable.img_17,
                                     R.drawable.img_18,  R.drawable.img_19,
                                     R.drawable.img_20, R.drawable.img_21,
                                     R.drawable.img_22, R.drawable.img_23,
                                     R.drawable.img_24, R.drawable.img_25,
                                     R.drawable.img_26, R.drawable.img_27,
                                     R.drawable.img_28, R.drawable.img_29,
                                     R.drawable.img_30, R.drawable.img_31,
                                     R.drawable.img_32, R.drawable.img_33,
                                     R.drawable.img_34, R.drawable.img_35,
                                     R.drawable.img_36, R.drawable.img_37,
                                     R.drawable.img_38, R.drawable.img_39,
                                     R.drawable.img_40, R.drawable.img_41,
                                     R.drawable.img_42, R.drawable.img_43 };

            @SuppressWarnings("deprecation")
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                             super.onCreate(savedInstanceState);
                             setContentView(R.layout.activity_main);
                             image1 = (ImageView) findViewById(R.id.image);
                             gallery = (Gallery) findViewById(R.id.versesIndex);
                             gallery.setAdapter(new ImageAdapter(this, verse_titles_hindi));

                             r = new Runnable() {
                                         public void run() {
                                                      image1.setImageResource(image_array[i]);
                                                      System.gc();
                                                      i++;
                                                      image1.postDelayed(r, 25);
                                                      if (i >= image_array.length) {
                                                                   Log.i("log_tag", "" + i);
                                                                   i = 0;
                                                                  // image1.removeCallbacks(r);
                                                      }
                                           } 
                              };
              image1.postDelayed(r, 25);
           }

           private class ImageAdapter extends BaseAdapter {
                                   int mGalleryItemBackground;
                                   private Context mContext;
                                   private int[] verse_title;

                                   public ImageAdapter(Context c, int[] verse_title) {
                                   // TODO Auto-generated constructor stub
                                                         this.verse_title = verse_title;
                                                         this.mContext = c;
                                                         TypedArray a = obtainStyledAttributes(R.styleable.Theme);
                                                         mGalleryItemBackground = a.getResourceId(
                                                            R.styleable.Theme_android_galleryItemBackground, 0);
                                                         a.recycle();
                                    }  

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

                                   @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; 
                                    }

                                    @SuppressWarnings("deprecation")
                                    @Override
                                    public View getView(int position, View convertView, ViewGroup parent) {
                                    // TODO Auto-generated method stub
                                                        ImageView i = new ImageView(mContext);
                                                        i.setImageResource(verse_title[position]);
                                                        i.setLayoutParams(new Gallery.LayoutParams(353, 159));
                                                        i.setScaleType(ImageView.ScaleType.FIT_XY);
                                                        i.setBackgroundResource(mGalleryItemBackground);
                                                        return i;
                                     }

               }
}

This would be run with the gallery as well as multiple image in one image view.

Monday, January 7, 2013

LISTVIEW gets refresh and change the value while scroling issue(SOLVED)



First of all main.xml file will be like below:


<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"
    tools:context=".MainActivity" >
    <ListView
        android:id="@+id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        
         />
</RelativeLayout>

Row file for the inflator is as below.



<?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:orientation="vertical" >
    <SeekBar
        android:id="@+id/seekBar1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:max="100"/>
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal">
        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="click to see row number" />
        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="0" />
    </LinearLayout>
</LinearLayout>




Now the class in the activity should be like this.... See the getview method for the logic of not refreshing the list view after scrolling :


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

ListView lv = (ListView) findViewById(R.id.list);
lv.setAdapter(new ListAdapter(MainActivity.this));
}

private class ListAdapter extends BaseAdapter {
private Context con;
private int size = 20;
private int s[] = new int[20];

public ListAdapter(MainActivity mainActivity) {
// TODO Auto-generated constructor stub
this.con = mainActivity;
for (int i = 0; i < size; i++) {
s[i] = 0;
}

}

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

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

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

@Override
public View getView(final int position, View convertView,ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = LayoutInflater.from(this.con);
View View = inflater.inflate(R.layout.list_row, null);
SeekBar seekbar = (SeekBar) View.findViewById(R.id.seekBar1);
Button btnrow = (Button) View.findViewById(R.id.button1);
final Button btnseek = (Button) View.findViewById(R.id.button2);

seekbar.setProgress(s[position]);
btnseek.setText("" + s[position]);

seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}

@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
btnseek.setText("" + progress);
s[position] = progress;

}
});

return View;
}

}

Wednesday, January 2, 2013

Get all the application installed on your system



First of all add the xml for the list of the application installed on your devices.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android1="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ListView
        android1:id="@+id/listView1"
        android1:layout_width="match_parent"
        android1:layout_height="wrap_content"
        android1:layout_alignParentLeft="true"
        android1:layout_alignParentTop="true" >
    </ListView>

</RelativeLayout>

Here is the code for the row of the list.

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

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="17dp"
        android:layout_marginTop="22dp"
       />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/imageView1"
        android:layout_marginLeft="36dp"
        android:layout_toRightOf="@+id/imageView1"
        android:text="TextView" />

</RelativeLayout>


Now after that add the following code in your main activity.


public class MainActivity extends Activity {

ArrayList<PInfo> arrylist;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PInfo p = new PInfo();

arrylist = getPackages();

for (int i = 0; i < arrylist.size(); i++) {
Log.i("log_tag", "=======" + arrylist.get(i).icon);
}

ListView l = (ListView) findViewById(R.id.listView1);

l.setAdapter(new ListAdatp(this, arrylist));

}

class PInfo {
private String appname = "";
private String pname = "";
private String versionName = "";
private int versionCode = 0;
private String move2sd;
private Drawable icon;

private void prettyPrint() {
Log.v(appname + "\t" + pname + "\t" + versionName + "\t"
+ versionCode, "");
}

}

private ArrayList<PInfo> getPackages() {
ArrayList<PInfo> apps = getInstalledApps(false); /*
* false = no system
* packages
*/

final int max = apps.size();
for (int i = 0; i < max; i++) {
apps.get(i).prettyPrint();

}
return apps;

}

private ArrayList<PInfo> getInstalledApps(boolean getSysPackages) {
ArrayList<PInfo> res = new ArrayList<PInfo>();
List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
for (int i = 0; i < packs.size(); i++) {
PackageInfo p = packs.get(i);
if ((!getSysPackages) && (p.versionName == null)) {
continue;
}
PInfo newInfo = new PInfo();
newInfo.appname = p.applicationInfo.loadLabel(getPackageManager())
.toString();
newInfo.pname = p.packageName;
newInfo.versionName = p.versionName;
newInfo.versionCode = p.versionCode;
newInfo.icon = p.applicationInfo.loadIcon(getPackageManager());

res.add(newInfo);
}
return res;
}

public class ListAdatp extends BaseAdapter {

Activity ativity;
ArrayList<PInfo> adptarrlist;

public ListAdatp(MainActivity mainActivity, ArrayList<PInfo> arrylist) {

// TODO Auto-generated constructor stub
ativity = mainActivity;
adptarrlist = arrylist;

}

@Override
public int getCount() {
// TODO Auto-generated method stub
return adptarrlist.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;
}

@Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub

LayoutInflater inflt = (LayoutInflater) ativity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

convertView = inflt.inflate(R.layout.listrow, null);

ImageView img = (ImageView) convertView
.findViewById(R.id.imageView1);
TextView txt = (TextView) convertView.findViewById(R.id.textView1);
img.setBackgroundDrawable(adptarrlist.get(position).icon);
txt.setText("(" + adptarrlist.get(position).appname + ")  "
+ adptarrlist.get(position).pname);

txt.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

Intent LaunchIntent = getPackageManager()
.getLaunchIntentForPackage(
adptarrlist.get(position).pname);
startActivity(LaunchIntent);
}
});

return convertView;
}

}

}