Follow by Email

Tuesday, 20 November 2012

How to use a String Variable as Drawable dynamically in android?



Sometimes you may need to change the ImageView dynamically with the some String varible in your code. This is how you can easily call a drawable from a String .


 int dInt = getResources().getIdentifier(STRING_YOU_ARE_USING, "drawable","your.package.name");

    Drawable pDrawable = getResources().getDrawable(dInt);
    ImageView im=(ImageView)findViewById(R.id.IV);
    im.setBackgroundDrawable(pDrawable);


Your Comments are always welcome!
Simple But effective...



 33T9MN3VTPW7

Sunday, 4 November 2012

Installing an Android App from .apk file Programmatically.


Here is a simple but effective example , which shows how to install an app from its .apk file from another app's Activity.:

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File("/mnt/sdcard/AppName.apk")), "application/vnd.android.package-archive");
startActivity(intent); 

Your Comments are always welcome!
Simple But Effective...

Thursday, 9 August 2012

Download files from a server in android

Here is a really simple way to code for downloading a file from any given url or server





public static void download(String URL, String location, String filename,Context ctx)
{
System.out.println(URL);
//String URL = "";

InputStream in = null;      
try {
in = OpenHttpConnection(URL);


if(in!=null){

                           saveToInternalSorage(location,in,filename,ctx);
             
in.close();
} }
catch (Exception e1) {
e1.printStackTrace();
}

}
     private static InputStream OpenHttpConnection(String urlString)
throws IOException
{
InputStream in = null;
int response = -1;

URL url = new URL(urlString);
URLConnection conn = url.openConnection();

if (!(conn instanceof HttpURLConnection))                  
throw new IOException("Not an HTTP connection");

try{
System.out.println("OpenHttpConnection called");

HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();

response = httpConn.getResponseCode();

System.out.println("response is"+response);
System.out.println(HttpURLConnection.HTTP_OK);

if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
System.out.println("Connection Ok");
return in;
}                  
}
catch (Exception ex)
{
throw new IOException("Error connecting");          
}
return in;  
}
private static void saveToInternalSorage(String location,InputStream in,String filename,Context ctx)
{
    try {
      File dir=new File(location);
    dir.mkdir();
   
    FileOutputStream fos = new FileOutputStream(location+filename);
 
        byte[] buffer=new byte[1024];
     
        int len1 ;
        while ( (len1 = in.read(buffer) )!=-1 ) {
            fos.write(buffer);
         

        }

     
 
    } catch (Exception e) {
        e.printStackTrace();
    }
Your Comments are always welcome!

Monday, 16 July 2012

Detecting Screen size and Density in Android

To detect the screen size use this piece of code:


 //Determine screen size
    if ((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {     
        Toast.makeText(this, "Large screen",Toast.LENGTH_LONG).show();

    }
    else if ((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {     
        Toast.makeText(this, "Normal sized screen" , Toast.LENGTH_LONG).show();

    } 
    else if ((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) {     
        Toast.makeText(this, "Small sized screen" , Toast.LENGTH_LONG).show();
    }
    else {
        Toast.makeText(this, "Screen size is neither large, normal or small" , Toast.LENGTH_LONG).show();
    }




To detect the screen density use this:



 //Determine density
    DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int density = metrics.densityDpi;

        if (density==DisplayMetrics.DENSITY_HIGH) {
            Toast.makeText(this, "DENSITY_HIGH... Density is " + String.valueOf(density),  Toast.LENGTH_LONG).show();
        }
        else if (density==DisplayMetrics.DENSITY_MEDIUM) {
            Toast.makeText(this, "DENSITY_MEDIUM... Density is " + String.valueOf(density),  Toast.LENGTH_LONG).show();
        }
        else if (density==DisplayMetrics.DENSITY_LOW) {
            Toast.makeText(this, "DENSITY_LOW... Density is " + String.valueOf(density),  Toast.LENGTH_LONG).show();
        }
        else {
            Toast.makeText(this, "Density is neither HIGH, MEDIUM OR LOW.  Density is " + String.valueOf(density),  Toast.LENGTH_LONG).show();
        }
Your Comments are always welcome!

Friday, 18 May 2012

ScrollView inside ScrollView in Android.


While designing rich layouts you might need to use two scrollview in your app.
Well ideally its not advised to use two scrollview in a view. So try to avoid it.

Why this problem occurs ? :

When you put two scrollview android just get confused which scroll view is touched. So sometimes it gets unable to deliver touch event.
But even if the requirement forces you to make such layouts. Try this…
Say case is somewhat like this….
<ScrollView android:id=”@+id/parent_scroll” 
            android:layout_width=”fill_parent”
            android:layout_height=”wrap_content”
            android:layout_weight=”1″
            android:background=”@drawable/dotted_bg”
            android:focusableInTouchMode=”false”>
                        <LinearLayout   />
                        <LinearLayout   />
                        <LinearLayout  >
                        <ScrollView android:id=”@+id/child_scroll”  
                        android:layout_width=”fill_parent”
                        android:layout_height=”fill_parent”
                        android:background=”@drawable/text_box_bg”>
                    <TextView android:id=”@+id/text_description”
                        android:layout_width=”fill_parent”
                        android:layout_height=”fill_parent”
                        android:textColor=”@color/gray”
                        android:textSize=”12dip”
                        android:padding=”5dip”
                        android:scrollbars=”vertical”/>
                    <!–ScrollView>
                  </LinearLayout>
</ScrollView>

Step 1 : Provide unique id to both the scrollview.
Step 2 : get reference of that two scrollview in your activity.

     parentScroll=(ScrollView)findViewById(R.id.parent_scroll);
     childScroll=(ScrollView)findViewById(R.id.child_scroll);

Step 3: Now set touch listeners for both.

            parentScroll.setOnTouchListener(new View.OnTouchListener() {
                public boolean onTouch(View v, MotionEvent event) {
                    Log.v(TAG,”PARENT TOUCH”);
                    findViewById(R.id.child_scroll).getParent().requestDisallowInterceptTouchEvent(false);
                    return false;
                }
            });
            childScroll.setOnTouchListener(new View.OnTouchListener() {
                public boolean onTouch(View v, MotionEvent event) 
                {
                    Log.v(TAG,”CHILD TOUCH”);
                                        // Disallow the touch request for parent scroll on touch of child view
                    v.getParent().requestDisallowInterceptTouchEvent(true);
                    return false;
                }
            });
Simple But effective...