Monday, 10 August 2015

Using Image loader efficiently-android

In your application Use this


import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.BitmapDisplayer;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;

import android.app.Application;

public class SMBROfficial extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        
        
        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
      . showImageOnLoading(R.drawable.deafult_loading
              .showImageForEmptyUri(R.drawable.deafult_loading
      .showImageForEmptyUri(R.drawable.deafult_loading)
      .displayer(new FadeInBitmapDisplayer(1500))
              .cacheOnDisc(true)
              .build();


        // Create global configuration and initialize ImageLoader with this configuration
    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.threadPriority(Thread.NORM_PRIORITY - 2)
.memoryCacheSize(2 * 1024 * 1024) // 2 Mb
.denyCacheImageMultipleSizesInMemory()
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.memoryCache(new LruMemoryCache(2 * 1024 * 1024))
.memoryCacheSize(2 * 1024 * 1024)
.memoryCacheSizePercentage(13) // default
.discCacheSize(50 * 1024 * 1024)
.discCacheFileCount(100)
.tasksProcessingOrder(QueueProcessingType.FIFO)
        .defaultDisplayImageOptions(defaultOptions) // default
.writeDebugLogs()
.build();
        ImageLoader.getInstance().init(config);
    }

}



and in you adpters and activities


just Intialize it  and use it

 ImageLoader imageLoader = ImageLoader.getInstance();


 imageLoader.displayImage("YOUR URL", holder.IMAGEVIEW);


Auto adjust TextView android

Auto adjust Text view  for android applications


public class AutoAdjustTextview extends TextView{

// Minimum text size for this text view
public static final float MIN_TEXT_SIZE = 20;

// Our ellipse string
private static final String mEllipsis = "...";

// Flag for text and/or size changes to force a resize
private boolean mNeedsResize = false;

// Text size that is set from code. This acts as a starting point for resizing
private float mTextSize;

// Temporary upper bounds on the starting text size
private float mMaxTextSize = 0;

// Lower bounds for text size
private float mMinTextSize = MIN_TEXT_SIZE;

// Text view line spacing multiplier
private float mSpacingMult = 1.0f;

// Text view additional line spacing
private float mSpacingAdd = 0.0f;

// Add ellipsis to text that overflows at the smallest text size
private boolean mAddEllipsis = true;

// Default constructor override
public SizeAdjustingTextView(Context context) {
this(context, null);
}

// Default constructor when inflating from XML file
public SizeAdjustingTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}

// Default constructor override
public SizeAdjustingTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mTextSize = getTextSize();
}

@Override
protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) {
mNeedsResize = true;
// Since this view may be reused, it is good to reset the text size
resetTextSize();
}

@Override
public void setText(CharSequence text, BufferType type) {
super.setText(text, type);
resizeText();
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
if (w != oldw || h != oldh) {
mNeedsResize = true;
}
}


@Override
public void setTextSize(float size) {
super.setTextSize(size);
mTextSize = getTextSize();
}

@Override
public void setTextSize(int unit, float size) {
super.setTextSize(unit, size);
mTextSize = getTextSize();
}

@Override
public void setLineSpacing(float add, float mult) {
super.setLineSpacing(add, mult);
mSpacingMult = mult;
mSpacingAdd = add;
}

public void setMaxTextSize(float maxTextSize) {
mMaxTextSize = maxTextSize;
requestLayout();
invalidate();
}

public float getMaxTextSize() {
return mMaxTextSize;
}

public void setMinTextSize(float minTextSize) {
mMinTextSize = minTextSize;
requestLayout();
invalidate();
}

public float getMinTextSize() {
return mMinTextSize;
}

public void setAddEllipsis(boolean addEllipsis) {
mAddEllipsis = addEllipsis;
}

public boolean getAddEllipsis() {
return mAddEllipsis;
}

public void resetTextSize() {
if(mTextSize > 0) {
super.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
mMaxTextSize = mTextSize;
}
}

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
if(changed || mNeedsResize) {
int widthLimit = (right - left) - getCompoundPaddingLeft() - getCompoundPaddingRight();
int heightLimit = (bottom - top) - getCompoundPaddingBottom() - getCompoundPaddingTop();
resizeText(widthLimit, heightLimit);
}
super.onLayout(changed, left, top, right, bottom);
}


public void resizeText() {
int heightLimit = getHeight() - getPaddingBottom() - getPaddingTop();
int widthLimit = getWidth() - getPaddingLeft() - getPaddingRight();
resizeText(widthLimit, heightLimit);
}

public void resizeText(int width, int height) {
CharSequence text = getText();
if(text == null || text.length() == 0 || height <= 0 || width <= 0 || mTextSize == 0) {
return;
}
float newTextSize = findNewTextSize(width, height, text);
changeTextSize(newTextSize);
mNeedsResize = false;
}

private void changeTextSize(float newTextSize) {
setTextSize(TypedValue.COMPLEX_UNIT_PX,newTextSize);
setLineSpacing(mSpacingAdd, mSpacingMult);
}

private float findNewTextSize(int width, int height, CharSequence text) {
TextPaint textPaint = new TextPaint(getPaint());

float targetTextSize = textPaint.getTextSize();

int textHeight = getTextHeight(text, textPaint, width, targetTextSize);
while(textHeight > height && targetTextSize > mMinTextSize) {
targetTextSize = Math.max(targetTextSize - 1, mMinTextSize);
textHeight = getTextHeight(text, textPaint, width, targetTextSize);
}
return targetTextSize;
}

private int getTextHeight(CharSequence source, TextPaint paint, int width, float textSize) {
paint.setTextSize(textSize);
StaticLayout layout = new StaticLayout(source, paint, width, Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, true);
return layout.getHeight();
}

}





Playing video from url along with save instance of screen orientation- android

Playing video from url along with save instance of screen orientation


Enjoy!!!!!!!!


public class VideoviewActivity extends Activity {
//sharathyadhav

private VideoView myVideoView;
private int position = 0;
private ProgressDialog progressDialog;
private MediaController mediaControls;
String Url;

@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getIntent().getExtras();
       
      if(bundle != null){
      Url = bundle.getString("url", "");// or url of your choice since i send from another activity i use this
      }

// set the main layout of the activity
setContentView(R.layout.video);

//set the media controller buttons
if (mediaControls == null) {
mediaControls = new MediaController(VideoviewActivity.this);
}

//initialize the VideoView
myVideoView = (VideoView) findViewById(R.id.view);

// create a progress bar while the video file is loading
progressDialog = new ProgressDialog(VideoviewActivity.this);
// set a title for the progress bar
//progressDialog.setTitle("JavaCodeGeeks Android Video View Example");
// set a message for the progress bar
progressDialog.setMessage("Loading...");
//set the progress bar not cancelable on users' touch
progressDialog.setCancelable(false);
// show the progress bar
progressDialog.show();

try {
//set the media controller in the VideoView
myVideoView.setMediaController(mediaControls);

//set the uri of the video to be played
//myVideoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.kitkat));
myVideoView.setVideoPath(Url);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}

myVideoView.requestFocus();
//we also set an setOnPreparedListener in order to know when the video file is ready for playback
myVideoView.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mediaPlayer) {
// close the progress bar and play the video
progressDialog.dismiss();
//if we have a position on savedInstanceState, the video playback should start from here
myVideoView.seekTo(position);
if (position == 0) {
myVideoView.start();
} else {
//if we come from a resumed activity, video playback will be paused
myVideoView.pause();
}
}
});

}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
//we use onSaveInstanceState in order to store the video playback position for orientation change
savedInstanceState.putInt("Position", myVideoView.getCurrentPosition());
myVideoView.pause();
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//we use onRestoreInstanceState in order to play the video playback from the stored position 
position = savedInstanceState.getInt("Position");
myVideoView.seekTo(position);
}

}




xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:background="@color/black"
    android:layout_height="match_parent"  >
<VideoView 
    android:id="@+id/view"
    android:layout_centerInParent="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
    

</VideoView>
</RelativeLayout>

Thursday, 23 July 2015

Three way android slider like iphone slider (Unlock screen animation)

The below code works with the animation of sliding

check out



Activity.class

//Package name
import android.os.Bundle;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class FirstscreenActivity extends Activity implements OnSeekBarChangeListener,
OnClickListener {
SeekBar sb;
boolean flag = false;
RelativeLayout page_background;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.firstscreenactivity);
Initialization();
sb.setOnSeekBarChangeListener(this);
page_background.setOnClickListener(this);
}

private void Initialization() {
sb = (SeekBar) findViewById(R.id.myseek);
sb.setProgress(50);
page_background = (RelativeLayout) findViewById(R.id.full_page_layout);
//seekbartest.setText("Slide to Unlock");

}

@Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
if (arg1 > 95) {
arg0.setThumb(getResources().getDrawable(R.drawable.splashslider));
}
}

@Override
public void onStartTrackingTouch(SeekBar arg0) {
Log.e("progress baronStartTrackingTouch",""+arg0.getProgress());
}

@SuppressLint("NewApi") @Override
public void onStopTrackingTouch(final SeekBar arg0) {
Log.e("onStopTrackingTouch", "onStopTrackingTouch");
Log.e("progress bar",""+arg0.getProgress());
if (arg0.getProgress() <= 20) {
ValueAnimator anim = ValueAnimator.ofInt(arg0.getProgress(), 0);
anim.setDuration(100);
anim.addUpdateListener(new AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
    int animProgress = (Integer) animation.getAnimatedValue();
    arg0.setProgress(animProgress);
    }
});
anim.start();

}
else if(arg0.getProgress() > 20 && arg0.getProgress()< 50) {
ValueAnimator anim = ValueAnimator.ofInt(arg0.getProgress(), 50);
anim.setDuration(200);
anim.addUpdateListener(new AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
    int animProgress = (Integer) animation.getAnimatedValue();
    arg0.setProgress(animProgress);
    }
});
anim.start();
//arg0.setProgress(50);
}
else if(arg0.getProgress() > 50 && arg0.getProgress()< 80){
ValueAnimator anim = ValueAnimator.ofInt(arg0.getProgress(), 50);
anim.setDuration(200);
anim.addUpdateListener(new AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
    int animProgress = (Integer) animation.getAnimatedValue();
    arg0.setProgress(animProgress);
    }
});
anim.start();
//arg0.setProgress(50);
}else if(arg0.getProgress() >= 80){
ValueAnimator anim = ValueAnimator.ofInt(arg0.getProgress(), 100);
anim.setDuration(100);
anim.addUpdateListener(new AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
    int animProgress = (Integer) animation.getAnimatedValue();
    arg0.setProgress(animProgress);
    }
});
anim.start();
//arg0.setProgress(100);
sb.setVisibility(View.VISIBLE);

}
else{
}
}

@Override
public void onClick(View v) {
//Log.e()
sb.setVisibility(View.VISIBLE);
}

}





The xml file of the above activity:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/full_page_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:background="@drawable/splashbg" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:layout_marginBottom="14dp"
     android:layout_alignParentBottom="true"
        >

        <SeekBar
            android:id="@+id/myseek"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="40dp"
             android:paddingRight="40dp"
            android:background="@android:color/transparent"
            android:clickable="false"
            android:max="100"
            android:progressDrawable="@android:color/transparent"
            android:thumb="@drawable/splashslider" />
       
    </RelativeLayout>

</RelativeLayout>

Sunday, 19 July 2015

Add Special characters like nice curverd quotations in your text



The code is very simple to use


String alteredquote= '\u201D'+ "HELLO WORLD" + '\u201C';


you can find the html entites in the following link

http://www.javascripter.net/faq/mathsymbols.html


and to add color to the quotations



TextView  title = (TextView) findViewById(R.id.textview);
Spannable wordtoSpan = new SpannableString(alteredquote);
wordtoSpan.setSpan(new ForegroundColorSpan(Color.RED), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
wordtoSpan.setSpan(new ForegroundColorSpan(Color.RED),(alteredquote.length() - 1),(alteredquote.length()) , Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
wordtoSpan.setSpan(new RelativeSizeSpan(1.5f), 0, 1,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
wordtoSpan.setSpan(new RelativeSizeSpan(1.5f), (alteredquote.length() - 1), (alteredquote.length()),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);


title.setText(wordtoSpan);


Enjoy!!!!1





Wednesday, 8 July 2015

share pdf from url in android

Now you can share pdf from url ,its quiet easy 


check out the code

1. the async task to be performmed
private class DownloadFile extends AsyncTask<String, Void, Void>{

        @Override
        protected Void doInBackground(String... strings) {
            String fileUrl = strings[0];  //YOUR_URL_PDF.pdf
            String fileName = strings[1];  //ANY_NAME.PDF
            String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
            File folder = new File(extStorageDirectory, "testthreepdf");
            folder.mkdir();

            File pdfFile = new File(folder, fileName);

            try{
                pdfFile.createNewFile();
            }catch (IOException e){
                e.printStackTrace();
            }
            FileDownloader.downloadFile(fileUrl, pdfFile);
            return null;
        }

@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
  File pdfFile = new File(Environment.getExternalStorageDirectory() + "/testthreepdf/" + "ANY_NAME.pdf");  // -> filename = ANY_NAME.pdf
        Uri path = Uri.fromFile(pdfFile);
        Intent pdfIntent = new Intent(Intent.ACTION_SEND);
        pdfIntent.setDataAndType(path, "application/pdf");
        pdfIntent.putExtra(Intent.EXTRA_SUBJECT"subject");
        pdfIntent.putExtra(Intent.EXTRA_TEXT,     "your text");
        pdfIntent.putExtra(Intent.EXTRA_STREAM, path );
        pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        try{
            startActivity(pdfIntent);
        }catch(ActivityNotFoundException e){
            Toast.makeText(MainActivity.this, "Pdf could not be shared", Toast.LENGTH_SHORT).show();
           
          
        }
}
    }



2.call the async task in your share button

 new DownloadFile().execute("YOUR_URL_PDF.pdf", "ANY_NAME.pdf"); 




Thats it !!!!Enjoy

Saturday, 4 July 2015

use snack bar library


use snack bar library
 from

https://github.com/Kennyc1012/SnackBar/tree/master/library/src/main/java/com/kenny/snackbar


public  static void maketoast(Activity c) {
 

new SnackBarItem.Builder(c)
.setMessageResource("No internet connection")
 
.setSnackBarMessageColorResource(R.color.white)
.setSnackBarBackgroundColorResource(R.color.blue)
.setInterpolatorResource(android.R.interpolator.accelerate_decelerate)
.setMessageTypeface(UtilsTyeFace.getHelveticaNeueLTArabicRoman(c))
.setDuration(5000)
.setSnackBarListener(new snackbarlistner())
.show();
}


}






snack bar listner
public class snackbarlistner implements SnackBarListener{

@Override
public void onSnackBarStarted(Object object) {
// TODO Auto-generated method stub
SharedObjects.getInstance().setCustomtoast(true);
}

@Override
public void onSnackBarFinished(Object object, boolean actionPressed) {
// TODO Auto-generated method stub
SharedObjects.getInstance().setCustomtoast(false);
Log.e("calledend","calledend");
}

}