Friday, February 22, 2013

Android: Add Dynamic Image from server to ViewSwitcher


In your main.xml layout file, you'll want something like the followng


    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

            android:id="@+id/vfShow"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
       
       
   

  -------------------------------------------------------------------------------------------------------------

  In your example_Layout.xml layout file, you'll want something like the followng


  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
   
   
   

-------------------------------------------------------------------------------------------------------------------------------

In code image download from the server and display dynamically in view switcher

In your code then where this layout file is referenced, you can initialize your Views as follows...

 public class deal extends Activity {
      private static final int SWIPE_MIN_DISTANCE = 120;
      private static final int SWIPE_THRESHOLD_VELOCITY = 200;
 

//http://www.example.com/abc/

     String imageUrl="http://www.example.com/abc/";
     String[] im={"img1.png","img2.png","img3.png","img4.png","img5.png"};
     private ImageView imageLoader;
     private ProgressDialog bar;
     private final int ONE = 0;
     private ImageView img;
      private ViewFlipper vf;
      private Context mContext;
      private final GestureDetector detector = new GestureDetector(
            new MyGestureDetector());

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mContext = this;
        //new ImageDownload().execute(im[1]);
        vf = (ViewFlipper) this.findViewById(R.id.vfShow);
        vf.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(final View view, final MotionEvent event) {
                detector.onTouchEvent(event);
                return true;
            }
        });
        Bundle extras = getIntent().getExtras(); 
      
        String a = extras.getString("deal");
        for(int i=0;i<4 br="" i="">        {
           img = new ImageView(getApplicationContext());
          //AsyncImageLoaderv asyncImageLoaderTop = new AsyncImageLoaderv();
        //   img.setImageBitmap(new DownloadImagesTask().execute(imageUrl + im[i]));
         // ImageView ima =(ImageView)findViewById(R.id.imageView1);
         //TextView t= (TextView)findViewById(R.id.textView1);
        //  t.setText("Deals No - " );
         
             Bitmap bitmap = DownloadImage(imageUrl + im[i]);
           
              img.setImageBitmap(bitmap);
           
            
                        vf.addView(img);
            
                 }
      
        vf.setDisplayedChild(1);
      
        Toast.makeText(mContext, "Current Deal are = " +a,Toast.LENGTH_LONG).show();
        int a1= Integer.parseInt(a);
        for(int i=1;i<=a1 ;i++)
        {
            vf.showNext();
        }

    }

    View addImageView(int resId) {
        ImageView iv = new ImageView(this);
        iv.setImageResource(resId);

        return iv;
    }

    class MyGestureDetector extends SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                float velocityY) {
            try {

                // right to left swipe
                if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
                        && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    vf.setInAnimation(AnimationUtils.loadAnimation(mContext,
                            R.anim.left_in));
                    vf.setOutAnimation(AnimationUtils.loadAnimation(mContext,
                            R.anim.left_out));
                    vf.showNext();
                    return true;
                } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
                        && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    vf.setInAnimation(AnimationUtils.loadAnimation(mContext,
                            R.anim.right_in));
                    vf.setOutAnimation(AnimationUtils.loadAnimation(mContext,
                            R.anim.right_out));
                    vf.showPrevious();
                    return true;
                }

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

            return false;
        }
    }
  
      private 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{
                      HttpURLConnection httpConn = (HttpURLConnection) conn;
                      httpConn.setAllowUserInteraction(false);
                      httpConn.setInstanceFollowRedirects(true);
                      httpConn.setRequestMethod("GET");
                      httpConn.connect();

                      response = httpConn.getResponseCode();              
                      if (response == HttpURLConnection.HTTP_OK) {
                          in = httpConn.getInputStream();                              
                      }                  
                  }
                  catch (Exception ex)
                  {
                      throw new IOException("Error connecting");          
                  }
                  return in;  
              }
              private Bitmap DownloadImage(String URL)
              {      
                  Bitmap bitmap = null;
                  InputStream in = null;      
                  try {
                      in = OpenHttpConnection(URL);
                      bitmap = BitmapFactory.decodeStream(in);
                      in.close();
                  } catch (IOException e1) {
                      // TODO Auto-generated catch block
                      e1.printStackTrace();
                  }
                  return bitmap;              
              }
            
            public class DownloadImagesTask extends AsyncTask {

              @Override
              protected Bitmap doInBackground(String... urls) {
                  return download_Image(urls[0]);
              }

              @Override
              protected void onPostExecute(Bitmap result) {
                  img.setImageBitmap(result);              // how do I pass a reference to mChart here ?
              }


              private Bitmap download_Image(String url) {
                  //---------------------------------------------------
                  Bitmap bm = null;
                  try {
                      URL aURL = new URL(url);
                      URLConnection conn = aURL.openConnection();
                      conn.connect();
                      InputStream is = conn.getInputStream();
                      BufferedInputStream bis = new BufferedInputStream(is);
                      bm = BitmapFactory.decodeStream(bis);
                      bis.close();
                      is.close();
                  } catch (IOException e) {
                     // Log.e("Hub","Error getting the image from server : " + e.getMessage().toString());
                  }
                  return bm;
                  //---------------------------------------------------
              }


              }

}

   

How To Create Screen Size Independent Android Applications


How To Create Screen Size Independent Android Applications

How To Create Screen Size Independent Android Applications

 

Screen Sizes: large, normal, small
Density: high (hdpi), medium (mdpi), and low (ldpi).
Here are some of the techniques we can use to create a screen-size independent application

Low density: 120dpi; Skin: QVGA (320px*240px).
Medium density: 160dpi; Skin: HVGA (480px*320px).
High density: 240dpi; Skin: WGVA800 (800px*480px).

 

Resources folders

So, thinking a bit about screen elements, sizes, densities... we can arrive at the conclusion that the size of the screen affects the views, and the layouts we create, and the density of the screen affects the images we set in the layout.
One of the things we can do (there are many) is create layouts, views and images for every specific size and density. So, the resources directory could be something like:
res/layout/layout.xml
res/layout-small/layout.xml
res/layout-large/layout.xml
res/drawable-ldpi/icon.png
res/drawable-hdpi/icon.png 
 
 Like.


This way, in the “layout” directory, we put the layouts that are going to fit in a “normal” screen size, “layout-small” stores the same layouts but modified so they display on small screens properly. The same process is done in the “drawable” folders. In the “drawable-ldpi” and “drawable-hdpi” folders we store the images we use in our application, changing its density.

And after creating folder your file display look like ,

 For Small Layout folder layout display like,



 For Medium Layout in Layout Folder display like,















For Large Layout Folder display like,















Manifest

In Android , we have a new element in the manifest, the  tag. With this tag we can say how many screen sizes our application supports. android:smallScreens,android:normalScreensandroid:largeScreens and android:anyDensity.
This is a piece of the manifest:
 
android:largeScreens="false"
android:normalScreens="true"
android:smallScreens="true" 
android:xlargeScreens="true"
android:anyDensity="true" />



After going through all the resources we can use in our application to create the most “screen-size” independent.





for each screen resolution you can do following things,

You need to create different layout for diff screen size. Support all screen you need to create following layout:
  1. Low density Small screens QVGA 240x320 (120dpi):
    layout-small-ldpi (240x320)  
    layout-small-land-ldpi (320x240)
    
  2. Low density Normal screens WVGA400 240x400 (x432) (120dpi):
    layout-ldpi  (240 x 400 )
    layout-land-ldpi  (400 x 240 )
    
  3. Medium density Normal screens HVGA 320x480 (160dpi):
    layout-mdpi (320 x 480 )
    layout-land-mdpi (480 x 320 )
    
  4. Medium density Large screens HVGA 320x480 (160dpi):
    layout-large-mdpi (320 x 480 )
    layout-large-land-mdpi (480 x 320)
    
  5. Galaxy Tab ( 240 dpi ):
    layout-large  (600 x 1024) 
    layout-large-land  (1024 x 600)
    
  6. High density Normal screens WVGA800 480x800 (x854) (240 dpi):
    layout-hdpi (480 x 800)
    layout-land-hdpi (800 x 480)
    
  7. Xoom (medium density large but 1280x800 res) (160 dpi):
    layout-xlarge (800 x 1280)
    layout-xlarge-land (1280 x 800)

Android - How to check contact exists in Contact list


To check whether the contact exists in Contact list or not

 public class Conatclist extends Activity {
   @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.conatct);

        //Check if contact is already exists or not in Contact list
        if(contactExists(this,"4561237890"))
        {
            Toast.makeText(GanzfeldActivity.this,"exists",Toast.LENGTH_SHORT).show();
           
        }
        else
        {
            Toast.makeText(GanzfeldActivity.this," not exists",Toast.LENGTH_SHORT).show();
        }

}

public  boolean contactExists(Activity _activity,String number){
      Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,Uri.encode(number));

     String[] mPhoneNumberProjection = { PhoneLookup._ID, PhoneLookup.NUMBER, PhoneLookup.DISPLAY_NAME };

    Cursor cur = _activity.getContentResolver().query(lookupUri,mPhoneNumberProjection, null, null, null);
  try {
        if (cur.moveToFirst()) {
          // if contact are in contact list it will return true
          return true;
       }} finally {
           if (cur != null)
              cur.close();
      }
         //if contact are not match that means contact are not added
        return false;
    }

 }



For that you have give permission to mmanifest file.

 


This code will help you when you are working with contact backup & restore or server side backup & restore.

Android - How to add contact Contact list

To add contact in Contact list


public class Conatclist extends Activity {

   @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.conatct);
        //add contact  in Contact list
        addContact("Lee","7465447504");         addContact("Peter","735645423");         addContact("Sagar","453463426");         addContact("James","5643566546");         addContact("prem","5465654");
}

private void addContact(String name, String phone) {

      ContentValues values = new ContentValues();

      values.put(People.NUMBER, phone);

      values.put(People.TYPE, Phone.TYPE_CUSTOM);

      values.put(People.LABEL, name);

      values.put(People.NAME, name);





       Uri dataUri = getContentResolver().insert(People.CONTENT_URI, values);

       Uri updateUri = Uri.withAppendedPath(dataUri, People.Phones.CONTENT_DIRECTORY);



       values.clear();

       values.put(People.Phones.TYPE, People.TYPE_MOBILE);

       values.put(People.NUMBER, phone);

       updateUri = getContentResolver().insert(updateUri, values);





}



}



For that you have give permission to mmanifest file.



This code will help you when you are working with contact backup & restore or server side backup & restore.

How to remove Title Bar


To remove the Title bar for the single page or all page we set the code given bellow,

requestWindowFeture(Window.FEATURE_NO_TITLE);

and for all page you can set it on Androidmanifast file 


       android:theme="@android:style/Theme.NoTitleBar" >
                android:screenOrientation="portrait"
                  android:label="@string/app_name">
           
               
               
           

       

 

Android - Hide Status Bar by using the Class file


HIDE STSTUS BAR


@Override
protected void onCreate(Bundle savedInstanceState)
{

super.onCreate(savedInstanceState);

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,

                WindowManager.LayoutParams.FLAG_FULLSCREEN);

......

}

How to Hide Keyboard onStartup of Activity in Android


How to Hide Keyboard onStartup of Activity in Android



For Hide Keyboard:
 
put code on the onCreate() method 
 
getWindow().setSoftInputMode(WindowManager.LayoutParams.
SOFT_INPUT_STATE_ALWAYS_HIDDEN);

For Appear Keyboard:
getWindow().setSoftInputMode(WindowManager.LayoutParams.
SOFT_INPUT_STATE_ALWAYS_VISIBLE);

Unzip zip file using java.util.zip in android


Unzip zip file using java.util.zip



Example to unzip /mnt/sdcard/test/test.zip file to /mnt/sdcard/test/unzip/ folder.

Here you see the AndroidUnZipActivity.java in src folder
package com.AndroidUnZip;
 
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
 
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;
 
public class AndroidUnZipActivity extends Activity {
  
 String extStorageDirectory;
 final String testDir = "/test";
 final String unzipDir = "/unzip/";
 final String orgZipFile = "test.zip";
 String srcFile;
 String targetDir;
  
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
     
      CheckExtStorageDirectory();
      unzip();
      Toast.makeText(AndroidUnZipActivity.this,
     "Unzip finished!",
     Toast.LENGTH_LONG).show();
     
 
  }
 
  private void CheckExtStorageDirectory(){
   extStorageDirectory = Environment.getExternalStorageDirectory().toString();
   srcFile = extStorageDirectory + testDir + "/" + orgZipFile;
   targetDir = extStorageDirectory + testDir + unzipDir;
   Toast.makeText(AndroidUnZipActivity.this,
     srcFile + "\n\n" + targetDir,
     Toast.LENGTH_LONG).show(); 
    
  }
 
  private void unzip(){
    
   final int BUFFER_SIZE = 4096;
   BufferedOutputStream bufferedOutputStream = null;
      FileInputStream fileInputStream;
     
      try {
   fileInputStream = new FileInputStream(srcFile);
    
   ZipInputStream zipInputStream = new ZipInputStream(newBufferedInputStream(fileInputStream));
         ZipEntry zipEntry;
        
         while ((zipEntry = zipInputStream.getNextEntry()) != null){
          String zipEntryName = zipEntry.getName();
             File file = new File(targetDir + zipEntryName);
            
             if (file.exists()){
               
             }else{
              if(zipEntry.isDirectory()){
               file.mkdirs();
              }else{
               byte buffer[] = new byte[BUFFER_SIZE];
                
               FileOutputStream fileOutputStream = newFileOutputStream(file);
                     bufferedOutputStream
                      new BufferedOutputStream(fileOutputStream, BUFFER_SIZE);
                     int count;
                    
                     while ((count = zipInputStream.read(buffer, 0, BUFFER_SIZE)) != -1) {
                             bufferedOutputStream.write(buffer, 0, count);     
                     }
                    
                     bufferedOutputStream.flush();
                     bufferedOutputStream.close();
              }
             }
         }
         zipInputStream.close();
        
  catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  }
 
}
 
 
main.xml in res/layout folder
 

    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
  
 
 
 
 
 To create folder and save unzipped files in sdcard, AndroidManifest.xml have to be modified to add permission of "android.permission.WRITE_EXTERNAL_STORAGE".
 
xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.AndroidUnZip"
  android:versionCode="1"
  android:versionName="1.0" >
 
  <uses-sdk android:minSdkVersion="10" />
  <uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 
  <application
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name" >
      <activity
          android:name=".AndroidUnZipActivity"
          android:label="@string/app_name" >
          <intent-filter>
              <action android:name="android.intent.action.MAIN" />
 
              <category android:name="android.intent.category.LAUNCHER"/>
          </intent-filter>
      </activity>
  </application>
 
</manifest>
 
 
And finally you see the output.
 
 
 
Thank you.

Radio Buttons In Alert Dialog in android


 Radio Buttons In Dialog

 

AlertDialog Radio button;


final CharSequence[] items = {"good "," very good "," nice","soso"};
                
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Select The Difficulty Level");
                builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item) {
                   
                    Intent i=new Intent(getApplicationContext(),SudokuActivity.class);;
                    switch(item)
                    {
                        case 0:
                                // Your code when first option seletced
                                 break;
                        case 1:
                                // Your code when 2nd  option seletced
                                
                                break;
                        case 2:
                               // Your code when 3rd option seletced
                                break;
                        case 3:
                                 // Your code when 4th  option seletced                        
                                 break;
                        
                    }
                    levelDialog.dismiss();    
                    }
                });
                levelDialog = builder.create();
                levelDialog.show();


put your code in  java file then see the output.

Thank you.