Thursday, 12 February 2015

Select image from gallery and camera

First; user having two choice – take photo from camera and Choose from library; the user will need to choose any one option from list. Then depending on the option chosen by the user, we will either open the gallery or capture an image from the camera. 
Step 1
Open "AndroidManifest" and add the following code to it: 
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.chhavi.uploadingandviewimage"
    android:versionCode="1"
    android:versionName="1.0" >

  <uses-permission android:name="android.permission.CAMERA" />
  <uses-feature android:name="android.hardware.camera" />
  <uses-feature android:name="android.hardware.camera.autofocus" />
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

  <uses-sdk
      android:minSdkVersion="7"
      android:targetSdkVersion="16" />

  <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
    <activity
        android:name="com.chhavi.uploadingandviewimage.MainActivity"
        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> 
Note the permission "WRITE_EXTERNAL_STORAGE" is to save the image captured to the gallery. "CAMERA" permissions enables use of the camera of your Android phone.
Step 2:
Open "activity_main" and add the following code to it:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:id="@+id/LinearLayout1"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical"
              android:padding="10dp" >

  <LinearLayout
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:gravity="center"
          android:padding="5dp" >

    <Button
            android:id="@+id/btnSelectPhoto"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Select Photo" />

  </LinearLayout>

  <LinearLayout
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:orientation="vertical"
          android:padding="10dp" >

    <ImageView
            android:id="@+id/viewImage"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/camera" />

  </LinearLayout>

</LinearLayout> 
The layout looks like:
im1.jpg
 Later the selected image will be displayed in the ImageView.
Step 3:
Open "MainActivity" and add the following code to it: 
package com.chhavi.uploadingandviewimage;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class MainActivity extends Activity {

    ImageView viewImage;
    Button b;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b=(Button)findViewById(R.id.btnSelectPhoto);
        viewImage=(ImageView)findViewById(R.id.viewImage);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectImage();
            }
        });
    }

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

      private void selectImage() {

        final CharSequence[] options = { "Take Photo""Choose from Gallery","Cancel" };

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Add Photo!");
        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (options[item].equals("Take Photo"))
                {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                    startActivityForResult(intent, 1);
                }
                else if (options[item].equals("Choose from Gallery"))
                {
                    Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, 2);

                }
                else if (options[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                File f = new File(Environment.getExternalStorageDirectory().toString());
                for (File temp : f.listFiles()) {
                    if (temp.getName().equals("temp.jpg")) {
                        f = temp;
                        break;
                    }
                }
                try {
                    Bitmap bitmap;
                    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();

                    bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
                            bitmapOptions); 
                   
                    viewImage.setImageBitmap(bitmap);

                    String path = android.os.Environment
                            .getExternalStorageDirectory()
                            + File.separator
                            + "Phoenix" + File.separator + "default";
                    f.delete();
                    OutputStream outFile = null;
                    File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
                    try {
                        outFile = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                        outFile.flush();
                        outFile.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (requestCode == 2) {

                Uri selectedImage = data.getData();
                String[] filePath = { MediaStore.Images.Media.DATA };
                Cursor c = getContentResolver().query(selectedImage,filePath, nullnullnull);
                c.moveToFirst();
                int columnIndex = c.getColumnIndex(filePath[0]);
                String picturePath = c.getString(columnIndex);
                c.close();
                Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
                Log.w("path of image from gallery......******************.........", picturePath+"");
                viewImage.setImageBitmap(thumbnail);
            }
        }
    }   
}

In the code above, "AlertDialog" will create a pop-up dialog box that will ask the user to choose "Take Photo", in other words capture an image from the camera or "Choose from Gallery" or "Cancel". Note that in both "Choose from Gallery" and "Take Photo", you can add any code in "startActivityForResult".
Output snapshots:
Run the application on an Android phone.
The first screen looks like:
im2f.png
Clicking on the button "Select Photo" you will get the alert dialog box like:
im3f.png
Selecting "Take photo" will open your camera.
im4f.png
After clicking the photo, you can discard it or save it by selecting the tick mark:
im5f.png
Finally the image clicked will be displayed in the ImageView.
im8f.png
Selecting "Choose from Gallery" will open your gallery (note that the image captured earlier has been added to the phone gallery).
im6f.jpg
Selecting an image from these albums will be displayed in the ImageView like:
im7f.png

Monday, 9 February 2015

Scroll View

Main Activity
package com.scrollview;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import com.squareup.picasso.Picasso;

import android.R.string;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

public class MainActivity extends Activity {
Timer time=new Timer();

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

final List<String> url = new ArrayList<String>();

url.add("http://androidexample.com/media/webservice/LazyListView_images/image0.png");
url.add("http://androidexample.com/media/webservice/LazyListView_images/image1.png");
url.add("http://androidexample.com/media/webservice/LazyListView_images/image2.png");
url.add("http://androidexample.com/media/webservice/LazyListView_images/image3.png");
url.add("http://androidexample.com/media/webservice/LazyListView_images/image7.png");
url.add("http://androidexample.com/media/webservice/LazyListView_images/image4.png");
url.add("http://androidexample.com/media/webservice/LazyListView_images/image0.png");
url.add("http://androidexample.com/media/webservice/LazyListView_images/image1.png");
url.add("http://androidexample.com/media/webservice/LazyListView_images/image2.png");
url.add("http://androidexample.com/media/webservice/LazyListView_images/image3.png");
url.add("http://androidexample.com/media/webservice/LazyListView_images/image7.png");
url.add("http://androidexample.com/media/webservice/LazyListView_images/image4.png");

LinearLayout main = (LinearLayout) findViewById(R.id.container1);

ImageView img11 = (ImageView) findViewById(R.id.imageView1);
Picasso.with(getApplicationContext()).load(url.get(0)).into(img11);


for (int i = 0; i < url.size(); i++) {

ImageView img = new ImageView(getApplicationContext());
img.setId(i);
RelativeLayout.LayoutParams mParms = new RelativeLayout.LayoutParams(
200, 200);
img.setLayoutParams(mParms);
img.setScaleType(ScaleType.FIT_XY);
Picasso.with(getApplicationContext()).load(url.get(i)).into(img);
img.setTag(url.get(i));
main.addView(img);

img.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

ImageView img = (ImageView) findViewById(R.id.imageView1);
Picasso.with(getApplicationContext())
.load(v.getTag().toString()).into(img);



time.cancel();


}
});

}


time.scheduleAtFixedRate(new TimerTask() {

@Override
public void run() {

runOnUiThread(new Runnable() {

@Override
public void run() {

Random r = new Random();
int i1 = r.nextInt((url.size()-1) - 0) + 0;
System.out.println(""+i1);
ImageView img11 = (ImageView) findViewById(R.id.imageView1);
Picasso.with(getApplicationContext()).load(url.get(i1)).into(img11);


}
});

}
}, 3000 ,3000);

}
}
Screen Shots


Friday, 6 February 2015

To show full size image of gallery images

Main Activity
package com.example.imagegallry;

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

import android.app.Activity;
import android.os.Bundle;
import android.widget.GridView;
import android.widget.ListView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        List<String> urls=new ArrayList<String>();
        urls.add("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTaBYSb4nVQrEn2c2xAbrQlLmbBeWuHdwScXTP4ooVzUhC9ZfKzXA");        
        urls.add("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRveXT-rTUftVUUbgbSTpYh1sVfFEOlah1yr1DPQ2ScY7dMR7gc");
        urls.add("https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRoijmXrh12Ux48kbZMPfLMlog6LatW2IplODMEX0IBqiI9JZaC");
        urls.add("https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSkep0_haj0l6RsmK922iADQjWj1r2MibNsbqsr6QFeLXk2TIPSSw");
        urls.add("https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcT0k39CFKC6dKMSaMXxIKA9UoNtLL-wzBwOAhf6o3gkmEvyzqnK6w");
        urls.add("https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcR0XcapD77nGfmhYvucYQyzq4W2VnrLij8BCANBuZGY-1tOqGht&reload=on");
      galleryadapter adp=new galleryadapter(urls, getApplicationContext());
      
          
           GridView g1=(GridView)findViewById(R.id.gridView1);
           g1.setAdapter(adp);  
           }
}

Gallery Adapter
package com.example.imagegallry;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;

public class galleryadapter extends BaseAdapter {
List<String> myimages;
Context ctx;

public galleryadapter(List<String> images, Context applicationContext) {
myimages = images;
this.ctx = applicationContext;
}

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

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

}

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

@Override      
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater li = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = li.inflate(R.layout.gridlayout, null);
ImageView img = (ImageView) convertView.findViewById(R.id.imageView1);
Picasso.with(ctx).load(myimages.get(position)).into(img);
img.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent in=new Intent(ctx, MainActivityfull.class);
in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
in.putExtra("img", myimages.get(position));
ctx.startActivity(in);
}
});

return convertView;
}

}
Main Activity full Image
package com.example.imagegallry;

import com.squareup.picasso.Picasso;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivityfull extends Activity {

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

String img = getIntent().getStringExtra("img");
Toast.makeText(getApplicationContext(), img, 2000).show();

ImageView imageView = (ImageView) findViewById(R.id.imageView1);
Picasso.with(getApplicationContext()).load(img).into(imageView);
}
}
Screen Shot of images in gallery


Screen Shot of full image





How to retrieve Data From Shared Preferences ?

Data can be retrieved from saved preferences by calling getString() (For string) method. This method should be called on Shared Preferences not on Editor.
// returns stored preference value
// If value is not present return second param value - In this case null
pref.getString("key_name"null); // getting String
pref.getInt("key_name"null); // getting Integer
pref.getFloat("key_name"null); // getting Float
pref.getLong("key_name"null); // getting Long
pref.getBoolean("key_name"null); // getting boolean

Thursday, 5 February 2015

REGISTRATION SCREEN USING SHARED PREFERENCE

Main Activity

package com.example.share1;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
   
    private EditText uname;
    private EditText upass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
       
        SharedPreferences prf1 = getApplicationContext().getSharedPreferences("abc", 0);
        boolean isLogin=prf1.getBoolean("islogin", false);
        getui();
        if(isLogin==true)
        {
           
            Intent intent=new Intent(MainActivity.this,MainActivity1.class);
            startActivity(intent);
           
        }}
       
        public void getui()
        {
         uname=(EditText) findViewById(R.id.editText1);
         upass=(EditText) findViewById(R.id.editText2);
       
   
        }
       
        public void Registeration(View v)
        {
            Intent obj = new Intent(MainActivity.this, MainActivity1.class);
            startActivity(obj);
            }
        public void Login(View v)
        {
           
            SharedPreferences prf = getApplicationContext().getSharedPreferences("xyz", 0);
       
           
           
            String un=prf.getString("un", "");
            String up=prf.getString("up", "");
           
                if(un.equalsIgnoreCase(uname.getText().toString())&& up.equalsIgnoreCase(upass.getText().toString()))
                {
                    Toast.makeText(getApplicationContext(), "Login", Toast.LENGTH_LONG).show();
                   
                SharedPreferences prf1 = getApplicationContext().getSharedPreferences("abc", 0);
                    Editor edit = prf1.edit();
                    edit.putBoolean("islogin", true);
                    edit.commit();
                   
                   
                   
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "Login failed", Toast.LENGTH_LONG).show();
                   
                }
           
        }       
           
    }

Main Activity 1

package com.example.share1;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity1 extends Activity {

   
     EditText uname;
     EditText upass;
     CheckBox ch;
     Button ok;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_activity1);

       
    }
    public void getui() {

         uname = (EditText) findViewById(R.id.editText1);
             upass = (EditText) findViewById(R.id.editText2);
            ok =(Button)findViewById(R.id.button1);
        }
   
    public void Registered(View v) {
        String name1 = uname.getText().toString();
        String pass1 = upass.getText().toString();
       
        if(name1.replace(" ","").length()==0 || pass1.replace(" ","").length()==0)
        {
            Toast.makeText(getApplicationContext(), "enter values", Toast.LENGTH_LONG).show();
        }
        else
        {
            SharedPreferences prf = getApplicationContext().getSharedPreferences("xyz", 0);
            Editor edit = prf.edit();
            edit.putString("un",name1);
            edit.putString("up", pass1);
            edit.commit();
           
            startActivity(new Intent(MainActivity1.this,MainActivity.class));
        }
     }
}

Main Activity 2

package com.example.share1;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;

public class MainActivity2 extends Activity {

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

       
    }
    public void logout(View v)
    {
        SharedPreferences prf1 = getApplicationContext().getSharedPreferences(
                "abc", 0);
        prf1.edit().clear().commit();
       
        Intent intent=new Intent(MainActivity2.this,MainActivity.class);
        startActivity(intent);
    }
    }

   



Wednesday, 4 February 2015

How to store data in Shared Preference?

 Data can be saved  into shared preferences using editor. All the primitive data types like booleans, floats, ints, longs, and strings are supported. Call editor.commit() in order to save changes to shared preferences.

editor.putBoolean("key_name"true); // Storing boolean - true/false
editor.putString("key_name""string value"); // Storing string
editor.putInt("key_name""int value"); // Storing integer
editor.putFloat("key_name""float value"); // Storing float
editor.putLong("key_name""long value"); // Storing long
editor.commit(); // commit changes

Monday, 2 February 2015

Shared Preferences

SharedPreference is the simplest mechanism to store the data in android. You do not worry about creating the file or using files API.It stores the data in XML files. SharedPreference stores the data in key value pair.The SharedPreferences class allows you to save and retrieve key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: boolean, floats, int, longs, and strings.The data is stored in XML file in the directory data/data//shared-prefs folder.
Application of SharedPreference
  • Storing the information about number of visitors (counter).
  • Storing the date and time (when your Application is updated).
  • Storing the username and password.
  • Storing the user settings.
Example:
For storing the data we will write the following code in main activity on save button:
SharedPreferences sf=getSharedPreferences("MyData", MODE_PRIVATE);

SharedPreferences.Editored= sf.edit(); 
ed.putString("name", txtusername.getText().toString()); 
ed.putString("pass", txtpassword.getText().toString()); 
ed.commit();

In this example I have taken two activities. The first is MainActivity and the second one is SecondActivity.When user click on save button the user name and password that you have entered in textboxes, will be stored in MyData.xml file.
Here MyData is the name of XML file .It will be created automatically for you. 



MODE_PRIVATE means this file is used by your application only.
txtusernameand txtpassword are two EditText control in MainActivity.
For retrieving the data we will write the following code in SecondActiviy when user click on Load button:
Public static final String DEFAULT=”N? A”;
DEFAULT is a String type user defined global variable.If the data is not saved in XML file and user click on load button then your application will not give the error. It will show message “No Data is found”. Here name and pass are same variable that I have used in MainActivity.
SharedPreferences sf=getSharedPreferences("MyData", Context.MODE_PRIVATE);
String Uname=sf.getString("name", DEFAULT);
String UPass=sf.getString("pass", DEFAULT);
if(name.equals(DEFAULT)||Pass.equals(DEFAULT)) 

{
Toast.makeText(this, "No data is found", Toast.LENGTH_LONG).show(); 
}

else
{
Txtusername.setText(Uname);

Txtpassword.setText(UPass) ;
}