1)create a packege it.sephiroth.android.library.imagezoom
*1 Add java file named IDisposable.java
=======================
package it.sephiroth.android.library.imagezoom;
public interface IDisposable {
void dispose();
}
=================================================
*2 ImageViewTouch.java
package it.sephiroth.android.library.imagezoom;
import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.ViewConfiguration;
public class ImageViewTouch extends ImageViewTouchBase {
static final float MIN_ZOOM = 0.9f;
protected ScaleGestureDetector mScaleDetector;
protected GestureDetector mGestureDetector;
protected int mTouchSlop;
protected float mCurrentScaleFactor;
protected float mScaleFactor;
protected int mDoubleTapDirection;
protected GestureListener mGestureListener;
protected ScaleListener mScaleListener;
public ImageViewTouch( Context context, AttributeSet attrs )
{
super( context, attrs );
}
@Override
protected void init()
{
super.init();
mTouchSlop = ViewConfiguration.getTouchSlop();
mGestureListener = new GestureListener();
mScaleListener = new ScaleListener();
mScaleDetector = new ScaleGestureDetector( getContext(), mScaleListener );
mGestureDetector = new GestureDetector( getContext(), mGestureListener, null, true );
mCurrentScaleFactor = 1f;
mDoubleTapDirection = 1;
}
@Override
public void setImageRotateBitmapReset( RotateBitmap bitmap, boolean reset )
{
super.setImageRotateBitmapReset( bitmap, reset );
mScaleFactor = getMaxZoom() / 3;
}
@Override
public boolean onTouchEvent( MotionEvent event )
{
mScaleDetector.onTouchEvent( event );
if ( !mScaleDetector.isInProgress() ) mGestureDetector.onTouchEvent( event );
int action = event.getAction();
switch ( action & MotionEvent.ACTION_MASK ) {
case MotionEvent.ACTION_UP:
if ( getScale() < 1f ) {
zoomTo( 1f, 50 );
}
break;
}
return true;
}
@Override
protected void onZoom( float scale )
{
super.onZoom( scale );
if ( !mScaleDetector.isInProgress() ) mCurrentScaleFactor = scale;
}
protected float onDoubleTapPost( float scale, float maxZoom )
{
if ( mDoubleTapDirection == 1 ) {
if ( ( scale + ( mScaleFactor * 2 ) ) <= maxZoom ) {
return scale + mScaleFactor;
} else {
mDoubleTapDirection = -1;
return maxZoom;
}
} else {
mDoubleTapDirection = 1;
return 1f;
}
}
class GestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onDoubleTap( MotionEvent e )
{
// float scale = getScale();
// float targetScale = scale;
// targetScale = onDoubleTapPost( scale, getMaxZoom() );
// targetScale = Math.min( getMaxZoom(), Math.max( targetScale, MIN_ZOOM ) );
// mCurrentScaleFactor = targetScale;
// zoomTo( targetScale, e.getX(), e.getY(), 200 );
// invalidate();
return super.onDoubleTap( e );
}
@Override
public boolean onScroll( MotionEvent e1, MotionEvent e2, float distanceX, float distanceY )
{
if ( e1 == null || e2 == null ) return false;
if ( e1.getPointerCount() > 1 || e2.getPointerCount() > 1 ) return false;
if ( mScaleDetector.isInProgress() ) return false;
if ( getScale() == 1f ) return false;
scrollBy( -distanceX, -distanceY );
invalidate();
return super.onScroll( e1, e2, distanceX, distanceY );
}
@Override
public boolean onFling( MotionEvent e1, MotionEvent e2, float velocityX, float velocityY )
{
if ( e1.getPointerCount() > 1 || e2.getPointerCount() > 1 ) return false;
if ( mScaleDetector.isInProgress() ) return false;
float diffX = e2.getX() - e1.getX();
float diffY = e2.getY() - e1.getY();
if ( Math.abs( velocityX ) > 800 || Math.abs( velocityY ) > 800 ) {
scrollBy( diffX / 2, diffY / 2, 300 );
invalidate();
}
return super.onFling( e1, e2, velocityX, velocityY );
}
}
class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@SuppressWarnings( "unused" )
@Override
public boolean onScale( ScaleGestureDetector detector )
{
float span = detector.getCurrentSpan() - detector.getPreviousSpan();
float targetScale = mCurrentScaleFactor * detector.getScaleFactor();
if ( true ) {
targetScale = Math.min( getMaxZoom(), Math.max( targetScale, MIN_ZOOM ) );
zoomTo( targetScale, detector.getFocusX(), detector.getFocusY() );
mCurrentScaleFactor = Math.min( getMaxZoom(), Math.max( targetScale, MIN_ZOOM ) );
mDoubleTapDirection = 1;
invalidate();
return true;
}
return false;
}
}
}
*3 ImageViewTouchBase.java
==================
package it.sephiroth.android.library.imagezoom;
import it.sephiroth.android.library.imagezoom.easing.Cubic;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;
public class ImageViewTouchBase extends ImageView implements IDisposable {
public interface OnBitmapChangedListener {
void onBitmapChanged( Bitmap bitmap );
};
protected enum Command {
Center, Move, Zoom, Layout, Reset,
};
public static final String LOG_TAG = "image";
protected Matrix mBaseMatrix = new Matrix();
protected Matrix mSuppMatrix = new Matrix();
protected Handler mHandler = new Handler();
protected Runnable mOnLayoutRunnable = null;
protected float mMaxZoom;
protected final Matrix mDisplayMatrix = new Matrix();
protected final float[] mMatrixValues = new float[9];
protected int mThisWidth = -1, mThisHeight = -1;
final protected RotateBitmap mBitmapDisplayed = new RotateBitmap( null, 0 );
final protected float MAX_ZOOM = 2.0f;
private OnBitmapChangedListener mListener;
public ImageViewTouchBase( Context context )
{
super( context );
init();
}
public ImageViewTouchBase( Context context, AttributeSet attrs )
{
super( context, attrs );
init();
}
public void setOnBitmapChangedListener( OnBitmapChangedListener listener ) {
mListener = listener;
}
protected void init()
{
setScaleType( ImageView.ScaleType.MATRIX );
}
public void clear()
{
setImageBitmapReset( null, true );
}
@Override
protected void onLayout( boolean changed, int left, int top, int right, int bottom )
{
super.onLayout( changed, left, top, right, bottom );
mThisWidth = right - left;
mThisHeight = bottom - top;
Runnable r = mOnLayoutRunnable;
if ( r != null ) {
mOnLayoutRunnable = null;
r.run();
}
if ( mBitmapDisplayed.getBitmap() != null ) {
getProperBaseMatrix( mBitmapDisplayed, mBaseMatrix );
setImageMatrix( Command.Layout, getImageViewMatrix() );
}
}
public void setImageBitmapReset( final Bitmap bitmap, final boolean reset )
{
setImageRotateBitmapReset( new RotateBitmap( bitmap, 0 ), reset );
}
public void setImageBitmapReset( final Bitmap bitmap, final int rotation, final boolean reset )
{
setImageRotateBitmapReset( new RotateBitmap( bitmap, rotation ), reset );
}
public void setImageRotateBitmapReset( final RotateBitmap bitmap, final boolean reset )
{
Log.d( LOG_TAG, "setImageRotateBitmapReset" );
final int viewWidth = getWidth();
if ( viewWidth <= 0 ) {
mOnLayoutRunnable = new Runnable() {
public void run()
{
setImageBitmapReset( bitmap.getBitmap(), bitmap.getRotation(), reset );
}
};
return;
}
if ( bitmap.getBitmap() != null ) {
getProperBaseMatrix( bitmap, mBaseMatrix );
setImageBitmap( bitmap.getBitmap(), bitmap.getRotation() );
} else {
mBaseMatrix.reset();
setImageBitmap( null );
}
if ( reset ) {
mSuppMatrix.reset();
}
setImageMatrix( Command.Reset, getImageViewMatrix() );
mMaxZoom = maxZoom();
if( mListener != null ) {
mListener.onBitmapChanged( bitmap.getBitmap() );
}
}
protected float maxZoom()
{
if ( mBitmapDisplayed.getBitmap() == null ) { return 1F; }
float fw = (float)mBitmapDisplayed.getWidth() / (float)mThisWidth;
float fh = (float)mBitmapDisplayed.getHeight() / (float)mThisHeight;
float max = Math.max( fw, fh ) * 4;
return max;
}
public RotateBitmap getDisplayBitmap()
{
return mBitmapDisplayed;
}
public float getMaxZoom()
{
return mMaxZoom;
}
@Override
public void setImageBitmap( Bitmap bitmap )
{
setImageBitmap( bitmap, 0 );
}
/**
* This is the ultimate method called when a new bitmap is set
* @param bitmap
* @param rotation
*/
protected void setImageBitmap( Bitmap bitmap, int rotation )
{
super.setImageBitmap( bitmap );
Drawable d = getDrawable();
if ( d != null ) {
d.setDither( true );
}
mBitmapDisplayed.setBitmap( bitmap );
mBitmapDisplayed.setRotation( rotation );
}
protected Matrix getImageViewMatrix()
{
mDisplayMatrix.set( mBaseMatrix );
mDisplayMatrix.postConcat( mSuppMatrix );
return mDisplayMatrix;
}
/**
* Setup the base matrix so that the image is centered and scaled properly.
*
* @param bitmap
* @param matrix
*/
protected void getProperBaseMatrix( RotateBitmap bitmap, Matrix matrix )
{
float viewWidth = getWidth();
float viewHeight = getHeight();
float w = bitmap.getWidth();
float h = bitmap.getHeight();
matrix.reset();
float widthScale = Math.min( viewWidth / w, MAX_ZOOM );
float heightScale = Math.min( viewHeight / h, MAX_ZOOM );
float scale = Math.min( widthScale, heightScale );
matrix.postConcat( bitmap.getRotateMatrix() );
matrix.postScale( scale, scale );
matrix.postTranslate( ( viewWidth - w * scale ) / MAX_ZOOM, ( viewHeight - h * scale ) / MAX_ZOOM );
}
protected float getValue( Matrix matrix, int whichValue )
{
matrix.getValues( mMatrixValues );
return mMatrixValues[whichValue];
}
protected RectF getBitmapRect()
{
if ( mBitmapDisplayed.getBitmap() == null ) return null;
Matrix m = getImageViewMatrix();
RectF rect = new RectF( 0, 0, mBitmapDisplayed.getBitmap().getWidth(), mBitmapDisplayed.getBitmap().getHeight() );
m.mapRect( rect );
return rect;
}
protected float getScale( Matrix matrix )
{
return getValue( matrix, Matrix.MSCALE_X );
}
public float getScale()
{
return getScale( mSuppMatrix );
}
protected void center( boolean horizontal, boolean vertical )
{
if ( mBitmapDisplayed.getBitmap() == null ) return;
RectF rect = getCenter( horizontal, vertical );
if ( rect.left != 0 || rect.top != 0 ) {
postTranslate( rect.left, rect.top );
}
}
protected void setImageMatrix( Command command, Matrix matrix )
{
setImageMatrix( matrix );
}
protected RectF getCenter( boolean horizontal, boolean vertical )
{
if ( mBitmapDisplayed.getBitmap() == null ) return new RectF( 0, 0, 0, 0 );
RectF rect = getBitmapRect();
float height = rect.height();
float width = rect.width();
float deltaX = 0, deltaY = 0;
if ( vertical ) {
int viewHeight = getHeight();
if ( height < viewHeight ) {
deltaY = ( viewHeight - height ) / 2 - rect.top;
} else if ( rect.top > 0 ) {
deltaY = -rect.top;
} else if ( rect.bottom < viewHeight ) {
deltaY = getHeight() - rect.bottom;
}
}
if ( horizontal ) {
int viewWidth = getWidth();
if ( width < viewWidth ) {
deltaX = ( viewWidth - width ) / 2 - rect.left;
} else if ( rect.left > 0 ) {
deltaX = -rect.left;
} else if ( rect.right < viewWidth ) {
deltaX = viewWidth - rect.right;
}
}
return new RectF( deltaX, deltaY, 0, 0 );
}
protected void postTranslate( float deltaX, float deltaY )
{
mSuppMatrix.postTranslate( deltaX, deltaY );
setImageMatrix( Command.Move, getImageViewMatrix() );
}
protected void postScale( float scale, float centerX, float centerY )
{
mSuppMatrix.postScale( scale, scale, centerX, centerY );
setImageMatrix( Command.Zoom, getImageViewMatrix() );
}
protected void zoomTo( float scale )
{
float cx = getWidth() / 2F;
float cy = getHeight() / 2F;
zoomTo( scale, cx, cy );
}
public void zoomTo( float scale, float durationMs )
{
float cx = getWidth() / 2F;
float cy = getHeight() / 2F;
zoomTo( scale, cx, cy, durationMs );
}
protected void zoomTo( float scale, float centerX, float centerY )
{
if ( scale > mMaxZoom ) scale = mMaxZoom;
float oldScale = getScale();
float deltaScale = scale / oldScale;
postScale( deltaScale, centerX, centerY );
onZoom( getScale() );
center( true, true );
}
protected void onZoom( float scale )
{
}
public void scrollBy( float x, float y )
{
panBy( x, y );
}
protected void panBy( float dx, float dy )
{
RectF rect = getBitmapRect();
RectF srect = new RectF( dx, dy, 0, 0 );
updateRect( rect, srect );
postTranslate( srect.left, srect.top );
center( true, true );
}
protected void updateRect( RectF bitmapRect, RectF scrollRect )
{
float width = getWidth();
float height = getHeight();
if( bitmapRect != null){
if ( bitmapRect.top >= 0 && bitmapRect.bottom <= height ) scrollRect.top = 0;
if ( bitmapRect.left >= 0 && bitmapRect.right <= width ) scrollRect.left = 0;
if ( bitmapRect.top + scrollRect.top >= 0 && bitmapRect.bottom > height ) scrollRect.top = (int)( 0 - bitmapRect.top );
if ( bitmapRect.bottom + scrollRect.top <= ( height - 0 ) && bitmapRect.top < 0 ) scrollRect.top = (int)( ( height - 0 ) - bitmapRect.bottom );
if ( bitmapRect.left + scrollRect.left >= 0 ) scrollRect.left = (int)( 0 - bitmapRect.left );
if ( bitmapRect.right + scrollRect.left <= ( width - 0 ) ) scrollRect.left = (int)( ( width - 0 ) - bitmapRect.right );
}
// Log.d( LOG_TAG, "scrollRect(2): " + scrollRect.toString() );
}
protected void scrollBy( float distanceX, float distanceY, final float durationMs )
{
final float dx = distanceX;
final float dy = distanceY;
final long startTime = System.currentTimeMillis();
mHandler.post( new Runnable() {
float old_x = 0;
float old_y = 0;
public void run()
{
long now = System.currentTimeMillis();
float currentMs = Math.min( durationMs, now - startTime );
float x = Cubic.easeOut( currentMs, 0, dx, durationMs );
float y = Cubic.easeOut( currentMs, 0, dy, durationMs );
panBy( ( x - old_x ), ( y - old_y ) );
old_x = x;
old_y = y;
if ( currentMs < durationMs ) {
mHandler.post( this );
} else {
RectF centerRect = getCenter( true, true );
if ( centerRect.left != 0 || centerRect.top != 0 ) scrollBy( centerRect.left, centerRect.top );
}
}
} );
}
protected void zoomTo( float scale, final float centerX, final float centerY, final float durationMs )
{
// Log.d( LOG_TAG, "zoomTo: " + scale + ", " + centerX + ": " + centerY );
final long startTime = System.currentTimeMillis();
final float incrementPerMs = ( scale - getScale() ) / durationMs;
final float oldScale = getScale();
mHandler.post( new Runnable() {
public void run()
{
long now = System.currentTimeMillis();
float currentMs = Math.min( durationMs, now - startTime );
float target = oldScale + ( incrementPerMs * currentMs );
zoomTo( target, centerX, centerY );
if ( currentMs < durationMs ) {
mHandler.post( this );
} else {
// if ( getScale() < 1f ) {}
}
}
} );
}
public void dispose()
{
if ( mBitmapDisplayed.getBitmap() != null ) {
if ( !mBitmapDisplayed.getBitmap().isRecycled() ) {
mBitmapDisplayed.getBitmap().recycle();
}
}
clear();
System.gc();
}
}
*4 RotateBitmap.java
===============
package it.sephiroth.android.library.imagezoom;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.RectF;
public class RotateBitmap {
public static final String TAG = "RotateBitmap";
private Bitmap mBitmap;
private int mRotation;
private int mWidth;
private int mHeight;
private int mBitmapWidth;
private int mBitmapHeight;
public RotateBitmap( Bitmap bitmap, int rotation )
{
mRotation = rotation % 360;
setBitmap( bitmap );
}
public void setRotation( int rotation )
{
mRotation = rotation;
invalidate();
}
public int getRotation()
{
return mRotation % 360;
}
public Bitmap getBitmap()
{
return mBitmap;
}
public void setBitmap( Bitmap bitmap )
{
mBitmap = bitmap;
if ( mBitmap != null ) {
mBitmapWidth = bitmap.getWidth();
mBitmapHeight = bitmap.getHeight();
invalidate();
}
}
private void invalidate()
{
Matrix matrix = new Matrix();
int cx = mBitmapWidth / 2;
int cy = mBitmapHeight / 2;
matrix.preTranslate( -cx, -cy );
matrix.postRotate( mRotation );
matrix.postTranslate( cx, cx );
RectF rect = new RectF( 0, 0, mBitmapWidth, mBitmapHeight );
matrix.mapRect( rect );
mWidth = (int)rect.width();
mHeight = (int)rect.height();
}
public Matrix getRotateMatrix()
{
Matrix matrix = new Matrix();
if ( mRotation != 0 ) {
int cx = mBitmapWidth / 2;
int cy = mBitmapHeight / 2;
matrix.preTranslate( -cx, -cy );
matrix.postRotate( mRotation );
matrix.postTranslate( mWidth / 2, mHeight / 2 );
}
return matrix;
}
public int getHeight()
{
return mHeight;
}
public int getWidth()
{
return mWidth;
}
public void recycle()
{
if ( mBitmap != null ) {
mBitmap.recycle();
mBitmap = null;
}
}
}
2)Create second packege named it.sephiroth.android.library.imagezoom.easing
1* Cubic.java
===========
package it.sephiroth.android.library.imagezoom.easing;
public class Cubic {
public static float easeOut( float time, float start, float end, float duration )
{
return end * ( ( time = time / duration - 1 ) * time * time + 1 ) + start;
}
}
3)_create package named com.mrs.example;
*1 ProdukteActivity.java
===============
package com.ovte.appsolution;
import it.sephiroth.android.library.imagezoom.ImageViewTouch;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class ProdukteActivity extends Activity{
private WebView mWebViewProdukte =null;
public String strDiscription = null,strImageLink=null,strProdukteImage=null;
private ImageView imgProdukte;
private MemoryCache mMemoryCache=null;
private ZoomImage mZoomImage=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.xprodukteactivity);
mMemoryCache=new MemoryCache();
imgProdukte = (ImageView)findViewById(R.id.imgProdukte);
mWebViewProdukte = (WebView)findViewById(R.id.webview_produkte);
mWebViewProdukte.getSettings().setJavaScriptEnabled(true);
mWebViewProdukte.getSettings().setSupportZoom(true);
mWebViewProdukte.setBackgroundColor(Color.TRANSPARENT);
if(GlobalClass.CheckNetwork(this)){
new GetProdukteData().execute();
}
}
//This class is used for zoom image
private class ZoomImage extends AsyncTask<String, String, Bitmap>
{
private ProcessDialog mProcessDialog=null;
@Override
protected void onPreExecute() {
mProcessDialog=new ProcessDialog(ProdukteActivity.this, "",Constant.LOADING);
super.onPreExecute();
}
@Override
protected Bitmap doInBackground(String... params) {
return GlobalClass.GETHTTPConnectionBitmap(URL, getApplicationContext());
}
@Override
protected void onPostExecute(final Bitmap mBitmap) {
mProcessDialog.dismiss();
mZoomImage=null;
if(mBitmap!=null){
System.out.println("mBitmap==="+mBitmap);
final Dialog mDialog = new Dialog(ProdukteActivity.this);
mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mDialog.setContentView(R.layout.xzoomimage);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
mDialog.setCancelable(true);
mDialog.setCanceledOnTouchOutside(false);
Button btnCancel = (Button)mDialog.findViewById(R.id.btnCancel);
btnCancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mDialog.dismiss();
}
});
final ImageViewTouch mImageViewTouch = (ImageViewTouch)mDialog.findViewById(R.id.imgTouchLageplan);
mImageViewTouch.post(new Runnable() {
public void run() {
if(mBitmap!=null)
{
mImageViewTouch.setImageBitmapReset(mBitmap, 0, true);
}
}
});
mDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
mImageViewTouch.dispose();
if(mBitmap!=null){
if(!mBitmap.isRecycled())
{
mBitmap.recycle();
System.gc();
}
}
}
});
mDialog.show();
}
super.onPostExecute(mBitmap);
}
}
//********************************************************************************************************************************
//This function is used for get produkte data
private final class GetProdukteData extends AsyncTask<String,JSONObject,JSONObject>{
private ProcessDialog mProcessDialog = null;
@Override
protected void onPreExecute() {
mProcessDialog = new ProcessDialog(ProdukteActivity.this, "Produkte", Constant.LOADING);
super.onPreExecute();
}
@Override
protected JSONObject doInBackground(String... params) {
if(GlobalClass.CheckNetworkNoMessage(ProdukteActivity.this)){
String strURL = getResources().getString(R.string.Produkte_URL);
try {
return new JSONObject(GlobalClass.GETHTTPConnection(strURL));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
else{
return null;
}
}
@Override
protected void onPostExecute(JSONObject mJsonObject) {
mProcessDialog.dismiss();
super.onPostExecute(mJsonObject);
if(mJsonObject!=null){
try {
strImageLink=mJsonObject.getString("download_link");
JSONArray subJArray = mJsonObject.getJSONArray("Data_array");
for(int i=0; i<subJArray.length();i++){
JSONObject JProdukteDescription = subJArray.getJSONObject(0);
strDiscription = JProdukteDescription.getString("description");
strProdukteImage = JProdukteDescription.getString("image_url");
System.out.println("ImageLink === "+(strImageLink+strProdukteImage));
}
WebSettings settings = mWebViewProdukte.getSettings();
settings.setDefaultTextEncodingName("utf-8");
strDiscription = "<font color = '#FFFFFF'>"+strDiscription+"</font>";
String Discription = webViewLoadData(strDiscription);
mWebViewProdukte.loadData(Discription, "text/html", "utf-8");
URL=strImageLink + strProdukteImage;
mMemoryCache.put(String.valueOf(URL.hashCode()),GlobalClass.ImageShrink(GlobalClass.GETHTTPConnectionBitmap((strImageLink + strProdukteImage),getApplicationContext()), Constant.SCREEN_WIDTH, Constant.SCREEN_WIDTH));
// mMemoryCache.put(String.valueOf(URL.hashCode()),BitmapImageUtil.loadFrom((strImageLink + strProdukteImage), ProdukteActivity.this, R.drawable.imgdefaultbigimage));
imgProdukte.setImageBitmap(mMemoryCache.get(String.valueOf(URL.hashCode())));
imgProdukte.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(GlobalClass.CheckNetwork(ProdukteActivity.this) && URL!=null){
System.out.println("URL===="+URL);
if(mZoomImage==null){
mZoomImage=new ZoomImage();
mZoomImage.execute("Zoom Image");
}
}
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
else{
Toast.makeText(ProdukteActivity.this,Constant.NETWORK_NOT_AVAILABLE,Toast.LENGTH_SHORT).show();
}
}
}
@Override
protected void onResume(){
Log.i("App Solution","Product Resume");
super.onResume();
}
@Override
protected void onPause() {
Log.i("App Solution","Product Pause");
super.onPause();
}
private String URL=null;
@Override
protected void onDestroy() {
if(mMemoryCache!=null && URL!=null){
if(mMemoryCache.get(String.valueOf(URL.hashCode()))!=null){
if(!mMemoryCache.get(String.valueOf(URL.hashCode())).isRecycled()){
mMemoryCache.get(String.valueOf(URL.hashCode())).recycle();
}
}
}
mMemoryCache.clear();
System.gc();
Log.i("App Solution","Product Destroy");
super.onDestroy();
}
//****************************************************************************************************************************
public static String webViewLoadData(String strDiscription) {
StringBuilder buf = new StringBuilder(strDiscription.length());
for (char c : strDiscription.toCharArray()) {
switch (c) {
case 'ä':
buf.append("ä");
break;
case 'ö':
buf.append("ö");
break;
case 'Ü':
buf.append("Ü");
break;
case '´':
buf.append("´");
break;
case 'è':
buf.append("è");
break;
case 'é':
buf.append("é");
break;
case 'Ö':
buf.append("Ö");
break;
case '#':
buf.append("%23");
break;
case '%':
buf.append("%25");
break;
case '\'':
buf.append("%27");
break;
case '?':
buf.append("%3f");
break;
case 'ü':
buf.append("ü");
break;
case '¤':
buf.append("â");
break;
case '€':
buf.append("€");
break;
case '–':
buf.append("–");
break;
default:
buf.append(c);
break;
}
}
String strTemp = buf.toString();
System.out.println(" Decode :"+strTemp);
return strTemp;
}
}
2)GlobalClass.java
==============
package com.ovte.appsolution;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.protocol.HTTP;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.text.format.DateFormat;
import android.util.Log;
import android.widget.Toast;
public class GlobalClass {
public static final String strTAG = "ServerConnection";
public static String LoginMessage = "";
/**
* This method use for check Network Connectivity
*/
public static boolean CheckNetwork(Context mContext) {
ConnectivityManager connectivity = (ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netinfo = connectivity.getActiveNetworkInfo();
if (netinfo != null) {
if (netinfo.isConnected() == true) {
return true;
} else {
return false;
}
} else {
Toast.makeText(mContext, Constant.NETWORK_NOT_AVAILABLE,
Toast.LENGTH_LONG).show();
return false;
}
}
/**
* This method use for check Network Connectivity withot message
*/
public static boolean CheckNetworkNoMessage(Context mContext) {
ConnectivityManager connectivity = (ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netinfo = connectivity.getActiveNetworkInfo();
if (netinfo != null) {
if (netinfo.isConnected() == true) {
return true;
} else {
return false;
}
} else {
return false;
}
}
// ************************************************************************************************************************
//************************************************************************************************************************
/**This method use for email validation check
*/
public static boolean isEmailValid(String email)
{
int lastDotIndex = 0;
String regExpn = "[A-Z0-9a-z][A-Z0-9a-z._%+-]*@[A-Za-z0-9][A-Za-z0-9.-]*\\.[A-Za-z]{2,6}";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(regExpn,Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if(matcher.matches()){
lastDotIndex = email.lastIndexOf(".");
String substr = email.substring(lastDotIndex, email.length());
String[] domains = {".aero", ".asia", ".biz", ".cat", ".com", ".coop", ".edu", ".gov", ".info", ".int", ".jobs", ".mil", ".mobi", ".museum", ".name", ".net", ".org", ".pro", ".tel", ".travel", ".ac", ".ad", ".ae", ".af", ".ag", ".ai", ".al", ".am", ".an", ".ao", ".aq", ".ar", ".as", ".at", ".au", ".aw", ".ax", ".az", ".ba", ".bb", ".bd", ".be", ".bf", ".bg", ".bh", ".bi", ".bj", ".bm", ".bn", ".bo", ".br", ".bs", ".bt", ".bv", ".bw", ".by", ".bz", ".ca", ".cc", ".cd", ".cf", ".cg", ".ch", ".ci", ".ck", ".cl", ".cm", ".cn", ".co", ".cr", ".cu", ".cv", ".cx", ".cy", ".cz", ".de", ".dj", ".dk", ".dm", ".do", ".dz", ".ec", ".ee", ".eg", ".er", ".es", ".et", ".eu", ".fi", ".fj", ".fk", ".fm", ".fo", ".fr", ".ga", ".gb", ".gd", ".ge", ".gf", ".gg", ".gh", ".gi", ".gl", ".gm", ".gn", ".gp", ".gq", ".gr", ".gs", ".gt", ".gu", ".gw", ".gy", ".hk", ".hm", ".hn", ".hr", ".ht", ".hu", ".id", ".ie", " No", ".il", ".im", ".in", ".io", ".iq", ".ir", ".is", ".it", ".je", ".jm", ".jo", ".jp", ".ke", ".kg", ".kh", ".ki", ".km", ".kn", ".kp", ".kr", ".kw", ".ky", ".kz", ".la", ".lb", ".lc", ".li", ".lk", ".lr", ".ls", ".lt", ".lu", ".lv", ".ly", ".ma", ".mc", ".md", ".me", ".mg", ".mh", ".mk", ".ml", ".mm", ".mn", ".mo", ".mp", ".mq", ".mr", ".ms", ".mt", ".mu", ".mv", ".mw", ".mx", ".my", ".mz", ".na", ".nc", ".ne", ".nf", ".ng", ".ni", ".nl", ".no", ".np", ".nr", ".nu", ".nz", ".om", ".pa", ".pe", ".pf", ".pg", ".ph", ".pk", ".pl", ".pm", ".pn", ".pr", ".ps", ".pt", ".pw", ".py", ".qa", ".re", ".ro", ".rs", ".ru", ".rw", ".sa", ".sb", ".sc", ".sd", ".se", ".sg", ".sh", ".si", ".sj", ".sk", ".sl", ".sm", ".sn", ".so", ".sr", ".st", ".su", ".sv", ".sy", ".sz", ".tc", ".td", ".tf", ".tg", ".th", ".tj", ".tk", ".tl", ".tm", ".tn", ".to", ".tp", ".tr", ".tt", ".tv", ".tw", ".tz", ".ua", ".ug", ".uk", ".us", ".uy", ".uz", ".va", ".vc", ".ve", ".vg", ".vi", ".vn", ".vu", ".wf", ".ws", ".ye", ".yt", ".za", ".zm", ".zw"};
for(int i = 0 ; i < domains.length ; i ++ ){
if(substr.trim().equals(domains[i])){
return true;
}
}
}
return false;
}
// this function use for Date format example like DD-MM-YYYY to MM-DD-YYYY
// change
public static String DateFormatChange(String StrDate, String FromPattern,
String ToPattern) {
try {
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(
FromPattern);
Date mDate = mSimpleDateFormat.parse(StrDate);
return (String) DateFormat.format(ToPattern, mDate).toString();
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
// this function use for GetDateDay
public static int GetDateDay(String StrDate, String FromPattern) {
try {
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(
FromPattern);
Date mDate = mSimpleDateFormat.parse(StrDate);
return Integer.parseInt(DateFormat.format("dd", mDate).toString());
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
// this function use for GetDateMonth
public static int GetDateMonth(String StrDate, String FromPattern) {
try {
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(
FromPattern);
Date mDate = mSimpleDateFormat.parse(StrDate);
return Integer.parseInt(DateFormat.format("MM", mDate).toString());
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
// this function use for image large to small make
public static Bitmap ImageShrink(Bitmap bitmapPreScale, int newWidth,
int newHeight) {
try {
if (bitmapPreScale != null) {
int oldWidth = bitmapPreScale.getWidth();
int oldHeight = bitmapPreScale.getHeight();
// calculate the scale
float scaleWidth = ((float) newWidth) / oldWidth;
float scaleHeight = ((float) newHeight) / oldHeight;
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
return Bitmap.createBitmap(bitmapPreScale, 0, 0, oldWidth,
oldHeight, matrix, true);
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(bitmapPreScale!=null){
if(!bitmapPreScale.isRecycled()){
bitmapPreScale.recycle();
}
}
System.gc();
}
}
// this function use for GetDateYear
public static int GetDateYear(String StrDate, String FromPattern) {
try {
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(
FromPattern);
Date mDate = mSimpleDateFormat.parse(StrDate);
return Integer
.parseInt(DateFormat.format("yyyy", mDate).toString());
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
// ******************************************************************************************************************
// For multizoom image
public static Bitmap DownloadImagePost(String strUrl) {
Bitmap mBitmap = null;
InputStream mInputStream = null;
try {
mInputStream = OpenHttpConnectionPost(strUrl);
if (mInputStream != null) {
// Log.e(strTAG,"Error File Not Found");
mBitmap = BitmapFactory.decodeStream(mInputStream);
mInputStream.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e(strTAG, "Error in DownloadImage InputStream");
}
return mBitmap;
}
// ********************************************************************************************************************
// For get webservice data
public static InputStream OpenHttpConnectionPost(String strUrl)
throws IOException {
InputStream mInputStream = null;
int intResponse = -1;
URL mURL = new URL(strUrl);
URLConnection mURLConnection = mURL.openConnection();
if (!(mURLConnection instanceof HttpURLConnection)) {
Log.e(strTAG, "Error in HTTP connection Not Connect");
throw new IOException("Not an HTTP connection");
}
try {
HttpURLConnection mHttpURLConnection = (HttpURLConnection) mURLConnection;
mHttpURLConnection.setAllowUserInteraction(false);
mHttpURLConnection.setInstanceFollowRedirects(true);
mHttpURLConnection.setRequestMethod("POST");
mHttpURLConnection.connect();
intResponse = mHttpURLConnection.getResponseCode();
if (intResponse == HttpURLConnection.HTTP_OK) {
mInputStream = mHttpURLConnection.getInputStream();
}
} catch (Exception e) {
Log.e(strTAG, "Error in Error connecting");
throw new IOException("Error connecting");
}
return mInputStream;
}
/**
* This method use for GETHTTPConnection to Server
*/
public static String GETHTTPConnection(String strUrl) {
HttpURLConnection mHttpURLConnection = null;
int intResponse = -1;
try {
URL mURL = new URL(strUrl);
URLConnection mURLConnection = mURL.openConnection();
if (!(mURLConnection instanceof HttpURLConnection)) {
Log.e(Constant.TAG, "Error in HTTP connection Not Connect");
throw new IOException("Not an HTTP connection");
}
mHttpURLConnection = (HttpURLConnection) mURLConnection;
mHttpURLConnection.setRequestMethod("GET");
mHttpURLConnection.setUseCaches(false);
mHttpURLConnection.setDoInput(true);
mHttpURLConnection.setDoOutput(true);
mHttpURLConnection.setInstanceFollowRedirects(true);
mHttpURLConnection.connect();
intResponse = mHttpURLConnection.getResponseCode();
if (intResponse == HttpURLConnection.HTTP_OK) {
return InputStreamToString(mHttpURLConnection.getInputStream());
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (mHttpURLConnection != null) {
mHttpURLConnection.disconnect();
}
}
}
/**
* This method use for GETHTTPConnection to Server get Bitmap
*/
public static Bitmap GETHTTPConnectionBitmap(String strUrl,Context context) {
HttpURLConnection mHttpURLConnection = null;
int intResponse = -1;
try {
URL mURL = new URL(strUrl);
URLConnection mURLConnection = mURL.openConnection();
if (!(mURLConnection instanceof HttpURLConnection)) {
Log.e(Constant.TAG, "Error in HTTP connection Not Connect");
throw new IOException("Not an HTTP connection");
}
mHttpURLConnection = (HttpURLConnection) mURLConnection;
mHttpURLConnection.setRequestMethod("GET");
mHttpURLConnection.setUseCaches(false);
mHttpURLConnection.setDoInput(true);
mHttpURLConnection.setDoOutput(true);
mHttpURLConnection.setInstanceFollowRedirects(true);
mHttpURLConnection.connect();
intResponse = mHttpURLConnection.getResponseCode();
if (intResponse == HttpURLConnection.HTTP_OK) {
return BitmapFactory.decodeStream(mHttpURLConnection.getInputStream());
} else {
return BitmapFactory.decodeResource(context.getResources(),R.drawable.imgdefaultbigimage);
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (mHttpURLConnection != null) {
mHttpURLConnection.disconnect();
}
}
}
/**
* This method use for POSTHTTPConnection to Server
*/
public static String POSTHTTPConnection(String strUrl, String[] Key, String[] Value) {
HttpURLConnection mHttpURLConnection = null;
int intResponse = -1;
try {
URL mURL = new URL(strUrl);
URLConnection mURLConnection = mURL.openConnection();
if (!(mURLConnection instanceof HttpURLConnection)) {
Log.e(Constant.TAG, "Error in HTTP connection Not Connect");
throw new IOException("Not an HTTP connection");
}
mHttpURLConnection = (HttpURLConnection) mURLConnection;
mHttpURLConnection.setRequestMethod("POST");
mHttpURLConnection.setUseCaches(false);
mHttpURLConnection.setDoInput(true);
mHttpURLConnection.setDoOutput(true);
mHttpURLConnection.setInstanceFollowRedirects(true);
/** This comment code use if encode request UTF_8 format */
/*
* String Query = String.format("version=%s",
* URLEncoder.encode("android", HTTP.UTF_8));
* mHttpURLConnection.setRequestProperty("Accept-Charset",
* HTTP.UTF_8);
* mHttpURLConnection.setRequestProperty("Content-Type",
* "application/x-www-form-urlencoded;charset=" + HTTP.UTF_8);
* output.write(Query.getBytes(HTTP.UTF_8));
*/
// /**This code use for post request*/
StringBuffer Query = new StringBuffer();
if (Key != null || Value != null) {
for (int i = 0; i < Key.length; i++) {
Query.append(String.format("%s=%s", Key[i], Value[i])
.toString().trim());
if (i >= 0 && i < (Key.length - 1) && Key.length > 1) {
Query.append("&");
}
}
}
OutputStream mOutputStream = null;
try {
mOutputStream = mHttpURLConnection.getOutputStream();
Log.i("Request = ", Query.toString());
mOutputStream.write(Query.toString().getBytes());
} finally {
if (mOutputStream != null)
try {
mOutputStream.close();
} catch (IOException logOrIgnore) {
}
}
mHttpURLConnection.connect();
intResponse = mHttpURLConnection.getResponseCode();
if (intResponse == HttpURLConnection.HTTP_OK) {
return InputStreamToString(mHttpURLConnection.getInputStream());
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (mHttpURLConnection != null) {
mHttpURLConnection.disconnect();
}
}
}
/**
* This method use for convert InputStream To String
*/
private static String InputStreamToString(InputStream mInputStream) {
String strLine = null;
// convert response in to the string.
try {
if (mInputStream != null) {
BufferedReader mBufferedReader = new BufferedReader(
new InputStreamReader(mInputStream, HTTP.UTF_8), 8);
StringBuilder mStringBuilder = new StringBuilder();
while ((strLine = mBufferedReader.readLine()) != null) {
mStringBuilder.append(strLine);
}
mInputStream.close();
return mStringBuilder.toString();
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
3)constant.java
==============
package com.ovte.appsolution;
public class Constant {
public static String TAG = "AppSolution";
public static int SCREEN_WIDTH = 240;
public static int SCREEN_HEIGHT = 320;
public static int SCREEN_WIDTH_PRODUCT_ZOOM = 240;
public static int SCREEN_HEIGHT_PRODUCT_ZOOM = 480;
//This is for tabtext
public static final String HOME_TAB_TEXT = "Home";
public static final String UNTERNEHMEN_TAB_TEXT = "Unternehmen";
public static final String INVEST_TAB_TEXT = "Invest";
public static final String PRODUKTE_TAB_TEXT = "Produkte";
public static final String MEHR_TAB_TEXT = "Mehr";
public static final String WhiteColor="#FFFFFF";
public static final String TransperantColor="#000000";
//Process Dialog Message
public static final String LOADING = "Loading...";
//Network connectivity message
public static final String NETWORK_NOT_AVAILABLE = "keine Netzwerkverbindung";
public static final String EMAIL_SENT_SUCCESSFULLY = "E-Mail erfolgreich gesendet";
public static final String CONNECTIVITY_NOT_MESSAGE = "Internet Connectivity ist nicht verfügbar";
public static final String EMAIL_ID_NOT_VALID_MESSAGE = "Bitte geben Sie eine gültige E-Mail Adresse ein.";
public static final String COMPULSARY_FIELD_MESSAGE ="Bitte füllen Sie alle mit * gekennzeichnetenFelder aus.";
//App Anfrenge & info constant
public static final String KEY_ACTION ="action";
public static final String VALUE_INFO ="info";
public static final String VALUE_APP_ANFRAGE = "appanfrage";
public static final String KEY_FIRST_NAME = "vorname";
public static final String KEY_LAST_NAME = "nachname";
public static final String KEY_FIRMA = "firma";
public static final String KEY_STREET = "strasse";
public static final String KEY_ZIPCODE = "zipcode";
public static final String KEY_LAND = "land";
public static final String KEY_TELEPHONE = "telefonnummer";
public static final String KEY_E_MAIL = "email";
public static final String KEY_MASSAGE = "ihre_nachricht_an_uns";
public static final String KEY_CALLBACK = "callback";
public static final String KEY_CATEGORIES = "categories";
public static final String APP_ANFRAGE = "APP-ANFRAGE";
public static final String INFO = "INFO";
public static final String App_ANFRAGE_INFO = "app_anfrage_info";
public static final String SUCCESS = "success";
public static final String OK = "ok";
public static final String MSG = "msg";
//For referenzen activity
public static final String KEY_VERSION = "version";
public static final String VALUE_ANDROID = "android";
//For Product Intent
public static final String PRODUCT_IMAGE_INTENT = "product_image";
//For Email Message
public static final String EMAIL_MESSAGE_INTENT= "EmailMessage";
public static final int SCALE_WIDTH = 94;
public static final int SCALE_HEIGHT = 156;
}
create xml file naed product_activity.xml
==========================
<?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:background="@drawable/imgapp_bg"
android:orientation="vertical" >
<LinearLayout android:orientation="vertical"
android:background="@drawable/app_header"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</LinearLayout>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:text="@string/Produkte_title"
android:layout_marginLeft="15dip"
android:layout_marginRight="15dip"
android:textSize="22dip"
android:textColor="@color/White"
android:layout_marginTop="10dip"/>
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/line"
android:layout_marginLeft="15dip"
android:layout_marginRight="15dip"/>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="17dip"
android:layout_marginRight="17dip"
android:layout_marginTop="5dip"
android:layout_marginBottom="10dip">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<View
android:id="@+id/viewfocus"
android:layout_width="0dip"
android:layout_height="0dip"
android:focusable="true"
android:focusableInTouchMode="true"/>
<WebView
android:id="@+id/webview_produkte"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<ImageView
android:id="@+id/imgProdukte"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
2)zoom image.xml
=============
<?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:background="@drawable/imgapp_bg"
android:orientation="vertical" >
<LinearLayout
android:orientation="vertical"
android:background="@drawable/app_header"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/btnCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dip"
android:gravity="center"
android:layout_gravity="right"
android:background="@drawable/close_icon" />
</LinearLayout>
<it.sephiroth.android.library.imagezoom.ImageViewTouch
android:id="@+id/imgTouchLageplan"
android:scaleType="fitCenter"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:layout_marginBottom="10dip"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
in manifest
============
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
No comments:
Post a Comment