Adsense Ad

Tuesday, 30 January 2018

How to pass / transfer image from One ImageView to another


Image transfer between two activities

First Activity = ProfileActivity

ImageView imgvu1 = (ImageView) findViewbyId(R.id.img1);
imgvu1.buildDrawingCache();
Bitmap bmp=imgvu1.getDrawingCache();
Intent Int= new Intent(ProfileActivity.this,ViewImageActivity.class);
Int.putExtra("BitmapImage",bmp);
startActivity(Int);


Second Activity = ViewImageActivity
ImageView imgvu2 = (ImageView) findViewbyId(R.id.img2);
imageView = (ImageView) findViewById(R.id.viewimage);
if (getIntent().hasExtra("BitmapImage")) {
Bitmap bitmap = (Bitmap) getIntent().getParcelableExtra("BitmapImage");
imgvu2.setImageBitmap(bitmap);
}





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


Image transfer between to ImageView on Single Activity

ImageView imgvu1 = (ImageView) findViewbyId(R.id.img1);
ImageView imgvu2 = (ImageView) findViewbyId(R.id.img2);

Bitmap bmp=imgvu1.getDrawingCache();
imgvu2.setImageBitmap(bmp);

























Android: How to set and insert image in Image view and in db from camera or gallery

In this article we go through with android sample code in which we first get image from DB and set it into ImageView on activity create.
Then we click from camera or select image from gallery and set it into ImageView on activity result.
In last, we save image into sqlite DB table having blob column.

Sample Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.user.dailybook.ProfileActivity">

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

            <ImageView
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:id="@+id/img"
                android:src="@drawable/noimage"
                android:layout_gravity="center_horizontal"
                android:onClick="CatchImage"
                android:clickable="true"
                />
<Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Save"
                android:textSize="20sp"
                android:textColor="#fff"
                android:textStyle="bold"
                android:background="@color/colorPrimaryDark"
                android:id="@+id/btn_save"
                android:textAllCaps="false"
                android:layout_marginRight="5dp"
                android:layout_gravity="right"
                />

</LinearLayout>

</RelativeLayout>



//Database Handler Java Class
public class DatabaseHandler extends SQLiteOpenHelper {
    public static String Globalid="";
    SQLiteDatabase sqLiteDatabase=getWritableDatabase();
    private static final String dbname="mydatabase.db";
    private static final int dbver=1;
    public DatabaseHandler(Context context) {
        super(context, dbname, null, dbver);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    String CreateTableQry="Create Table if not exists UBAG(" +
            "id integer primary key autoincrement not null, " +
            "pic  blob  )";

            db.execSQL(CreateTableQry);
            Log.e("","UBAG Table Created...");
    }

    public long insert(ContentValues values,String TableName){
        return (long) sqLiteDatabase.insert(TableName,null,values);
    }
public Cursor getData(String query){
        Cursor cursor=null;
        try {
            cursor = sqLiteDatabase.rawQuery(query, null);
        }catch (Exception e){
            Log.e("GD","DB Helper Found Error " + query);
        }
        cursor.moveToFirst();
        return cursor;
    }
}


//Java Class for Activity

public class ProfileActivity extends AppCompatActivity {
    ImageView imgvu;
DatabaseHandler dbhandler;
Bitmap help1;
Uri file;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
        dbhandler = new DatabaseHandler(this);
        imgvu = (ImageView) findViewById(R.id.img);
       save = (Button) findViewById(R.id.btn_save);
Cursor cursor=null;
//On activity creation you can set image into imageview from db
        String query="select * from ubag where id='"+id+"'";
        cursor=dbhandler.getData(query);
        if (cursor!=null) {
            if (cursor.getCount() > 0) {
                while (!cursor.isAfterLast()) {
          
                    try {
                        byte[] image = cursor.getBlob(cursor.getColumnIndex("pic"));
                        Bitmap bmp = BitmapFactory.decodeByteArray(image, 0, image.length);
                        imgvu.setImageBitmap(bmp);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    cursor.moveToNext();
                }
            }
        }
save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    ContentValues cvs= new ContentValues();
                    Bitmap bitmap = ((BitmapDrawable)imgvu.getDrawable()).getBitmap();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG,100,baos);
                    byte [] img = baos.toByteArray();
                    cvs.put("pic",img);
                    long ins =0;
                    ins = dbhandler.insert(cvs,"UBAG","id='"+id+"'");
                    if(ins==0){
                        Toast.makeText(ProfileActivity.this,"Data Not Saved",Toast.LENGTH_LONG).show();
                    }else{
                        Toast.makeText(ProfileActivity.this,"Data Updated",Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

public void CatchImage(View v){
// use one method at a time for image saving and comment other one
        camerOpenForPic();  // Method use to save image from camera click
       // getPicFromGallery(); // Method use to save image from gallery
    }

@TargetApi(Build.VERSION_CODES.M)
    private boolean checkPermission(){
        if (ContextCompat.checkSelfPermission(this
                , Manifest.permission.WRITE_EXTERNAL_STORAGE) + ContextCompat
                .checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED){
            requestPermissions(new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            },33);
            return  false;
        }else {
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode==33){
            if (grantResults.length>0){
                boolean camerpermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
                boolean readexternalfile = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                boolean writeExternalfile = grantResults[2] == PackageManager.PERMISSION_GRANTED;
                if (camerpermission && readexternalfile && writeExternalfile){
                    camerOpenForPic();
                }else{
                    Toast.makeText(this,"Unable to collect pic",Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    private void camerOpenForPic() {
        if (checkPermission()){
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent,1);
        }
    }

    public void getPicFromGallery(){
        if (checkPermission()){
            Intent intent=new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.INTERNAL_CONTENT_URI);
            intent.setType("image/*");
            intent.putExtra("crop","true");
            intent.putExtra("scale",true);
            intent.putExtra("outputX",256);
            intent.putExtra("outputY",256);
            intent.putExtra("aspectX",1);
            intent.putExtra("aspectY",1);
            intent.putExtra("return-data",true);
            //startActivityForResult(Intent.createChooser(intent,"Select Picture"),113);
            startActivityForResult(intent,113);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1){
            if (resultCode== Activity.RESULT_OK){
                try {
                    Bitmap bitmap= (Bitmap) data.getExtras().get("data");
                    imgvu.setImageBitmap(bitmap);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }else if (requestCode==113){
            if (resultCode==Activity.RESULT_OK){
                try {
                    final Bundle extras = data.getExtras();
                    help1 = extras.getParcelable("data");
                    imgvu.setImageBitmap(help1);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

}

How to insert image on oracle blob column from sqlite blob column using jdbc in android

In this article we learn how to insert image on oracle blob column(table created on server) from sqlite blob column (mobile db) using jdbc in android.
For connecting mobile app to oracle database via jdbc, You can read my previous article
"How to connect Android App with Oracle Database".

we assume that image was already save in mobile sqlite db in table named as "and_db_img" and now we retrieve images from sqlite db and save it in oracle db table named as "ora_db_img" using jdbc:

Sample Code:

String sql = "INSERT INTO ora_db_img(Image_ID,image_file) VALUES (?,?)";

PreparedStatement ps;
ps = connection.prepareStatement(sql);
byte[] imageByteArray;
ByteArrayInputStream imageStream;


Cursor cursor = databaseHandler.getData("select imgId,ImgFile from and_db_img");

int 
cntr=0;

if (
cursor.getCount() > 0){
while (
cursor.moveToNext()) {
   cntr++;
   ps.setString(1,cursor.getString(0));  
 imageByteArray=cursor.getBlob(2);   
imageStream = new ByteArrayInputStream(imageByteArray);
ps.setBinaryStream(2,imageStream); 
ps.execute();
 }
}

Android Image Upload Using Retrofit and Ion(Observer Pattern)

Using Ion

  1. What is ion?
  2. Ion is an android library for asynchronous networking and image loading(Displaying bitmaps,Image Uploading, Downloading).There are many other libraries for image manipulation which we will discuss later.
Ion is light weight and very easy to implement for beginners. Today i am going to teach you how to use Ion for Image Upload in MySql Server using android. Let’s start.
Server Configuration:
  1. Install Xampp or Wamp server.
  2. Create a folder androidImageUpload inside htdocs(For xampp) or www(For wamp).
3.Create imageupload.php file and write code as below.
<?php
  echo $_FILES['image']['name'] . '<br/>';
  ini_set('upload_max_filesize', '10M');
  $target_path = "uploads/";
  $target_path = $target_path . basename($_FILES['image']['name']);

  try {
   if (!move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {
  throw new Exception('Could not move file');
  }

  echo "Image uploaded";
  } catch (Exception $e) {
  die('Image did not upload: ' . $e->getMessage());
  }
  ?>
4.Create another folder uploads in which you want to save image.
We just have completed server configuration.Now I am going to show you android client part.
Steps1: Create android project and add ion dependency on build.gradle of module.
compile 'com.koushikdutta.ion:ion:2.+'
Step 2:Add permission for internet, camera and external storage respectivally.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Step 3:Create Server Configuration class which holds static variables required for Network call.
ServerConfig.java
Note: 192.168.0.109 is computers IP which will be different in your case.
public class ServerConfig {
    public static final String IMAGE_UPLOAD_URL = "http://192.168.0.109/androidImageUpload/imageupload.php";
     public static final String IMAGE_DIRECTORY_NAME = "imageuploadtest";
}
Step 4:Create an activity from which you want to upload image to server.
i.Check wheater or not device support camera.
if (!isDeviceSupportCamera()) {
            Toast.makeText(getApplicationContext(),
                    "device doesn't support camera",
                    Toast.LENGTH_LONG).show();
             finish();
        }
ii.check device has camera hardware or not.
private boolean isDeviceSupportCamera() {
        if (getApplicationContext().getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA)) {
             return true;
        } else {
             return false;
        }
    }
iii.Capture image from camera .
private void captureImage() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        fileUri = getOutputMediaFileUri(1);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
         startActivityForResult(intent,1001);
    }
iv.Create a function that require image file path as an argument and do image upload logic here.
void uploadImage(String mImagePath) {
    if (!NetworkUtil.getConnectivityStatusString(this)) {
        Toast.makeText(this, "no internet",        Toast.LENGTH_SHORT).show();
        return;
    }
final File fileToUpload = new File(mImagePath);
    Ion.with(ChangeProfilePictureActivity.this)
            .load("POST",ServerConfig.IMAGE_UPLOAD_URL)
            .uploadProgressHandler(new ProgressCallback() {
                @Override
                public void onProgress(long uploaded, long total) {
                }
            })
             .setMultipartFile("image", "image/jpeg", fileToUpload)
             .asString()
            .setCallback(new FutureCallback<String>() {
                @Override
                public void onCompleted(Exception e, String result) {
                    dismisDialog();
                    if (result != null) {
                        //Upload Success
                    } else {
                       //Upload Failed
                    }
}
            });
}
Finally your MainActivity class look like this:
MainActivity.java
public class MainActivity extends Activity {
    private Uri fileUri;
    private Button btnCapturePicture;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnCapturePicture = (Button) findViewById(R.id.btn_take_image);
        btnCapturePicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 captureImage();
            }
        });

 
        // Check wheater or not device support camera
        if (!isDeviceSupportCamera()) {
            Toast.makeText(getApplicationContext(),
                    "device doesn't support camera",
                    Toast.LENGTH_LONG).show();
             finish();
        }
    }
 
    /**
     * check device has camera hardware or not
     * */
    private boolean isDeviceSupportCamera() {
        if (getApplicationContext().getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA)) {
             return true;
        } else {
             return false;
        }
    }
 
  
    private void captureImage() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        fileUri = getOutputMediaFileUri(1);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
         startActivityForResult(intent,1001);
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable("file_uri", fileUri);
    }
 
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
         fileUri = savedInstanceState.getParcelable("file_uri");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
         if (requestCode == 1001) {
            if (resultCode == RESULT_OK) {
               uploadImage(fileUri.getPath());
               
            } else if (resultCode == RESULT_CANCELED) {
                 Toast.makeText(getApplicationContext(),
                        "User cancelled image capture", Toast.LENGTH_SHORT)
                        .show();
            
            } else {
                 Toast.makeText(getApplicationContext(),
                        "Error capturing image", Toast.LENGTH_SHORT)
                        .show();
            }
        
        }
    }

    void uploadImage(String mImagePath) {
        if (!NetworkUtil.getConnectivityStatusString(this)) {
            Toast.makeText(this, "no internet",        Toast.LENGTH_SHORT).show();
            return;
        }

        final File fileToUpload = new File(mImagePath);
        Ion.with(ChangeProfilePictureActivity.this)
                .load("POST", ServerConfig.IP + ServerConfig.BASE_URL +    ServerConfig.IMAGE_UPLOAD)
                .uploadProgressHandler(new ProgressCallback() {
                    @Override
                    public void onProgress(long uploaded, long total) {
                    }
                })
                .setMultipartFile("image", "image/jpeg", fileToUpload)
                .setMultipartParameter("email", preference.getEmail())
                .asString()
                .setCallback(new FutureCallback<String>() {
                    @Override
                    public void onCompleted(Exception e, String result) {
                        dismisDialog();
                        if (result != null) {
                            //Upload Success
                        } else {
                            //Upload Failed
                        }

                    }
                });
    }



    public Uri getOutputMediaFileUri(int type) {
        return Uri.fromFile(getOutputMediaFile(type));
    }
    private static File getOutputMediaFile(int type) {
 
         File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                ServerConfig.IMAGE_DIRECTORY_NAME);
 
         if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d(TAG, "Oops! Failed create "
                        + ServerConfig.IMAGE_DIRECTORY_NAME + " directory");
                return null;
            }
        }
 
         String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "IMG_" + timeStamp + ".jpg");
        }else {
            return null;
        }
 
        return mediaFile;
    }
}
Its almost done.Run the sample and upload image.

Wednesday, 24 January 2018

Similar key functional from Oracle Forms 6i to Oracle Forms 10G

For keys change to forms10g from forms6i

open [installation folder]\Forms\fmrweb.res
this file is use for keys configuration of oracle forms10g

open [installation folder]\Forms\fmrpcweb.res
this file defines all keys which is use in forms6i.

put values from fmrpcweb.res file and paste in fmrweb.res file but
first rename both files.





Oracle Forms 10G Web Configuration (formsweb.cfg) Some changes for jre environment.

Compatible jre patch for Oracle Forms 10G Click to download patch

After successfully installation of java jre 6.

1)
open [installation folder]\Forms\Server\formsweb.cfg

find the below old values and change to new values.

a)
OLD LINE:      baseHTMLjinitiator=basejini.htm
Replace From   baseHTMLjinitiator=basejpi.htm

b)
OLD LINE:      jpi_download_page=http://java.sun.com/products/archive/j2se/1.4.2_06/index.html
Replace From   jpi_download_page=http://www.oracle.com/technetwork/java/javase/downloads/index.html

c)
OLD LINE:      jpi_classid=clsid:CAFEEFAC-0014-0002-0006-ABCDEFFEDCBA
Replace From   jpi_classid=clsid:CAFEEFAC-0016-0000-FFFF-ABCDEFFEDCBA

d)
OLD LINE:      jpi_codebase=http://java.sun.com/products/plugin/autodl/jinstall-1_4_2-windows-i586.cab#Version=1,4,2,06
Replace From   jpi_codebase=http://java.sun.com/update/1.6.0/jinstall-6-windows-i586.cab#Version=1,6,0


this changes is forms10g run separatly.
open [installation folder]\Forms\Server\formsweb.cfg
find separateFrame=false

# Forms applet parameter
# Actual Value
# separateFrame=false
# New Value
separateFrame=true

for form Running:
http://mypc:8889/forms/frmservlet?form=d:\form1st.fmx
http://mypc:8889/forms/frmservlet?form=d:\OfficeData\Forms10g\TestSoft1\

Default Value of Menu Module in Forms10g Property.
DEFAULT&SMARTBAR