Tuesday, 3 February 2015

Working With Gif In Android loading from local folder

Step1:
Create a Project named as “Gifin Android”
Paste Following code in to your main activity java file

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.example.gifexamplehd.AnimatedGifImageView.TYPE;

public class MainActivity extends FragmentActivity  {

                private AnimatedGifImageView animatedGifImageView;
                boolean switchMe = false;

                @Override
                protected void onCreate(Bundle savedInstanceState) {
                                super.onCreate(savedInstanceState);
                                setContentView(R.layout.activity_main);
                                animatedGifImageView = ((AnimatedGifImageView) findViewById(R.id.animatedGifImageView));
                                animatedGifImageView.setAnimatedGif(R.raw.illusion, TYPE.FIT_CENTER);
                                //((Button) findViewById(R.id.button1)).setOnClickListener(this);
                                //switchMe = true;
                }



}

Step 2:

 Paste Following Code into your AnimatedGifView java File

package com.example.gifexamplehd;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;

public class AnimatedGifImageView extends ImageView {
public static enum TYPE {
FIT_CENTER, STREACH_TO_FIT, AS_IS
};

public AnimatedGifImageView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}

public AnimatedGifImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}

public AnimatedGifImageView(Context context) {
super(context);
}

boolean animatedGifImage = false;
private InputStream is = null;
private Movie mMovie = null;
private long mMovieStart = 0;
private TYPE mType = TYPE.FIT_CENTER;

@SuppressLint("NewApi") public void setAnimatedGif(int rawResourceId, TYPE streachType) {
setImageBitmap(null);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
mType = streachType;
animatedGifImage = true;
is = getContext().getResources().openRawResource(rawResourceId);
try {
mMovie = Movie.decodeStream(is);
} catch (Exception e) {
e.printStackTrace();
byte[] array = streamToBytes(is);
mMovie = Movie.decodeByteArray(array, 0, array.length);
}
p = new Paint();
}

@SuppressLint("NewApi") public void setAnimatedGif(String filePath, TYPE streachType)
throws FileNotFoundException {
setImageBitmap(null);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
mType = streachType;
animatedGifImage = true;
InputStream is;
try {
mMovie = Movie.decodeFile(filePath);
} catch (Exception e) {
e.printStackTrace();
is = new FileInputStream(filePath);
byte[] array = streamToBytes(is);
mMovie = Movie.decodeByteArray(array, 0, array.length);
}
p = new Paint();
}

@SuppressLint("NewApi") public void setAnimatedGif(byte[] byteArray, TYPE streachType)
throws FileNotFoundException {
setImageBitmap(null);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
mType = streachType;
animatedGifImage = true;

try {
mMovie = Movie.decodeByteArray(byteArray, 0, byteArray.length);
} catch (Exception e) {
e.printStackTrace();
}
p = new Paint();
}

@Override
public void setImageResource(int resId) {
animatedGifImage = false;
super.setImageResource(resId);
}

@Override
public void setImageURI(Uri uri) {
animatedGifImage = false;
super.setImageURI(uri);
}

@Override
public void setImageDrawable(Drawable drawable) {
animatedGifImage = false;
super.setImageDrawable(drawable);
}

Paint p;
private float mScaleH = 1f, mScaleW = 1f;
private int mMeasuredMovieWidth;
private int mMeasuredMovieHeight;
private float mLeft;
private float mTop;

private static byte[] streamToBytes(InputStream is) {
ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int len;
try {
while ((len = is.read(buffer)) >= 0) {
os.write(buffer, 0, len);
}
} catch (java.io.IOException e) {
}
return os.toByteArray();
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mMovie != null) {
int movieWidth = mMovie.width();
int movieHeight = mMovie.height();
/*
* Calculate horizontal scaling
*/
int measureModeWidth = MeasureSpec.getMode(widthMeasureSpec);
float scaleW = 1f, scaleH = 1f;
if (measureModeWidth != MeasureSpec.UNSPECIFIED) {
int maximumWidth = MeasureSpec.getSize(widthMeasureSpec);
if (movieWidth > maximumWidth) {
scaleW = (float) movieWidth / (float) maximumWidth;
} else {
scaleW = (float) maximumWidth / (float) movieWidth;
}
}

/*
* calculate vertical scaling
*/
int measureModeHeight = MeasureSpec.getMode(heightMeasureSpec);

if (measureModeHeight != MeasureSpec.UNSPECIFIED) {
int maximumHeight = MeasureSpec.getSize(heightMeasureSpec);
if (movieHeight > maximumHeight) {
scaleH = (float) movieHeight / (float) maximumHeight;
} else {
scaleH = (float) maximumHeight / (float) movieHeight;
}
}

/*
* calculate overall scale
*/
switch (mType) {
case FIT_CENTER:
mScaleH = mScaleW = Math.min(scaleH, scaleW);
break;
case AS_IS:
mScaleH = mScaleW = 1f;
break;
case STREACH_TO_FIT:
mScaleH = scaleH;
mScaleW = scaleW;
break;
}

mMeasuredMovieWidth = (int) (movieWidth * mScaleW);
mMeasuredMovieHeight = (int) (movieHeight * mScaleH);

setMeasuredDimension(mMeasuredMovieWidth, mMeasuredMovieHeight);

} else {
setMeasuredDimension(getSuggestedMinimumWidth(),
getSuggestedMinimumHeight());
}
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
mLeft = (getWidth() - mMeasuredMovieWidth) / 2f;
mTop = (getHeight() - mMeasuredMovieHeight) / 2f;
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (animatedGifImage) {
long now = android.os.SystemClock.uptimeMillis();
if (mMovieStart == 0) { // first time
mMovieStart = now;
}
if (mMovie != null) {
p.setAntiAlias(true);
int dur = mMovie.duration();
if (dur == 0) {
dur = 1000;
}
int relTime = (int) ((now - mMovieStart) % dur);
mMovie.setTime(relTime);
canvas.save(Canvas.MATRIX_SAVE_FLAG);
canvas.scale(mScaleW, mScaleH);
mMovie.draw(canvas, mLeft / mScaleW, mTop / mScaleH);
canvas.restore();
invalidate();
}
}

}

}


Step 3:
 Paste Following code in to Your xml layout file


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.gifexamplehd.MainActivity" >

    <com.example.gifexamplehd.AnimatedGifImageView
        android:id="@+id/animatedGifImageView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@+id/button1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1" />

</RelativeLayout>

Done

Do not Forget To paste any gif file into Your Raw folder

AutoComplete using custom layout for drop down

Steps will be same like my previous post

just some will increase

For Autocomplete visit that post

http://androidprogrammingsolutions.blogspot.com/2015/02/autocomplete-using-json-and-mysql.html

Just Add a layout file named as:

search_layout 

Paste following code into your xml file

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/text1"
    style="?android:attr/dropDownItemStyle"
    android:layout_width="fill_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:background="#ffffff"
    android:singleLine="true"
    android:textAppearance="?android:attr/textAppearanceLargeInverse"

    android:textColor="#000000" />


 And in Suggestion Adapter where your define layout define this layout file

Code for Your Suggestion Adapter


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

import android.app.Activity;
import android.widget.ArrayAdapter;
import android.widget.Filter;

public class SuggestionAdapter extends ArrayAdapter<String> {

protected static final String TAG = "SuggestionAdapter";
private List<String> suggestions;

public SuggestionAdapter(Activity context, String nameFilter) {
 
//Here i changed Layout file
super(context, R.layout.search_layout);
suggestions = new ArrayList<String>();
}

@Override
public int getCount() {
return suggestions.size();
}

@Override
public String getItem(int index) {
return suggestions.get(index);
}

@Override
public Filter getFilter() {
Filter myFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
JsonParse jp = new JsonParse();
if (constraint != null) {
// A class that queries a web API, parses the data and
// returns an ArrayList<GoEuroGetSet>
List<SuggestGetSet> new_suggestions = jp
.getParseJsonWCF(constraint.toString());
suggestions.clear();
for (int i = 0; i < new_suggestions.size(); i++) {
suggestions.add(new_suggestions.get(i).getName());
}

// Now assign the values and count to the FilterResults
// object
filterResults.values = suggestions;
filterResults.count = suggestions.size();
}
return filterResults;
}

@Override
protected void publishResults(CharSequence contraint,
FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return myFilter;
}

}

AutoComplete Using Json And Mysql

Step  1 :
Make an android project named “AutoComplete”.
Step  2 :
Paste the following code in MainActivity.java file.

import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
SuggestionAdapterNew adapter;
TextView txt;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_new);
txt = (TextView) findViewById(R.id.textView1);

}

/** Callback function */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
/** Create an option menu from res/menu/items.xml */
getMenuInflater().inflate(R.menu.items, menu);

/** Get the action view of the menu item whose id is search */
View v = (View) menu.findItem(R.id.search).getActionView();

final AutoCompleteTextView acTextView = (AutoCompleteTextView) v
.findViewById(R.id.autoComplete);
acTextView.setAdapter(new SuggestionAdapter(this, acTextView.getText()
.toString()));
final String search = "";
ImageButton img = (ImageButton) v.findViewById(R.id.imageButton1);
img.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String search = acTextView.getText().toString().trim();
Toast.makeText(getApplicationContext(), "Abc" + search,
Toast.LENGTH_SHORT).show();
txt.setText(search);
}
});

return super.onCreateOptionsMenu(menu);
}
}
Step 2 :
Paste the following code in activity_main_new.xml file.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="TextView" />

</RelativeLayout>
Step 3 :
Paste the following code in activity_main_new.xml file.
It will be the layout for your Action bar Search View

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <AutoCompleteTextView
        android:id="@+id/autoComplete"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentTop="true"
        android:layout_toLeftOf="@+id/imageButton1"
        android:ems="10"
        android:hint="Search Videos"
        android:popupBackground="#ffffff" >

        <requestFocus />
    </AutoCompleteTextView>

    <ImageButton
        android:id="@+id/imageButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/autoComplete"
        android:layout_alignParentRight="true"
        android:background="@null"
        android:layout_alignParentTop="true"
        android:src="@drawable/ic_action_search" />


</RelativeLayout>

Step 4:
Paste Following code into your menu file into res-->menu-->

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/search"
        android:actionLayout="@layout/activity_main"
        android:icon="@drawable/ic_action_search"
        android:showAsAction="always|collapseActionView"
        android:title="Search"/>


</menu>

Step 5:
Paste Following Code into Your jsonparse file


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

public class JsonParse {

public JsonParse() {
}



public List<SuggestGetSet> getParseJsonWCF(String sName) {
List<SuggestGetSet> ListData = new ArrayList<SuggestGetSet>();
try {
String temp = sName.replace(" ", "%20");
URL js = new URL(
"10.0.2.2/autocompelete.php?title="
+ temp);
URLConnection jc = js.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(
jc.getInputStream()));
String line = reader.readLine();
JSONObject jsonResponse = new JSONObject(line);
JSONArray jsonArray = jsonResponse.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject r = jsonArray.getJSONObject(i);
ListData.add(new SuggestGetSet(r.getString("id"), r
.getString("name")));
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return ListData;

}

}

Step 6:
Paste Following Code into Suggest get Set file
public class SuggestGetSet {

String id, name;

public SuggestGetSet(String id, String name) {
this.setId(id);
this.setName(name);
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}

Step 7:
 Paste Following Code into "SuggestionAdapter"


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

import android.app.Activity;
import android.widget.ArrayAdapter;
import android.widget.Filter;

public class SuggestionAdapter extends ArrayAdapter<String> {

protected static final String TAG = "SuggestionAdapter";
private List<String> suggestions;

public SuggestionAdapter(Activity context, String nameFilter) {
// super(context, R.layout.search_layout);
super(context, android.R.layout.simple_dropdown_item_1line);
suggestions = new ArrayList<String>();
}

@Override
public int getCount() {
return suggestions.size();
}

@Override
public String getItem(int index) {
return suggestions.get(index);
}

@Override
public Filter getFilter() {
Filter myFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
JsonParse jp = new JsonParse();
if (constraint != null) {
// A class that queries a web API, parses the data and
// returns an ArrayList<GoEuroGetSet>
List<SuggestGetSet> new_suggestions = jp
.getParseJsonWCF(constraint.toString());
suggestions.clear();
for (int i = 0; i < new_suggestions.size(); i++) {
suggestions.add(new_suggestions.get(i).getName());
}

// Now assign the values and count to the FilterResults
// object
filterResults.values = suggestions;
filterResults.count = suggestions.size();
}
return filterResults;
}

@Override
protected void publishResults(CharSequence contraint,
FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return myFilter;
}

}
SERVER SIDE

Now i am showing you php files with databse script and php Script
Step 1:
Create Database:
create table `countries` (
`id` int (255),
`name` varchar (765)

);
Step 2:
Insert some values
Step 3:
for autocomplete use that php file

<?php
include('db.php');
$myresult['results'] = array();
if (isset($_GET['name'])) {
    $country_name = $_GET['name'];
        $query3 = "SELECT *  FROM countries where name like'$country_name%'";
        $result3 = mysql_query($query3)or die(mysql_error());
        while ($row3 = mysql_fetch_assoc($result3)) {
            array_push($myresult['results'], $row3);
        }
    $myarray = array();
    echo json_encode($myresult);
}
?>
Step 4:
Create a databse connection file

<?php
error_reporting(E_ALL ^ E_DEPRECATED);

$host = 'localhost';
$user = 'root';
$password = '';
$database = 'test';
$conn = mysql_connect($host,$user,$password) or die('Server Information is not Correct');
mysql_select_db($database,$conn) or die('Database Information is not correct');

?>

Tada And You Will get Your Desired out Put

Comment for any suggestions.





Monday, 2 February 2015

Android Ring Dialogue Progress

Step  1 :
Make an android project named “RingDialogueProgress”.
Step  2 :
Paste the following code in MainActivity.java file.
package com.example.ringdialogueprogress;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

public class MainActivity extends Activity
{
       ProgressDialog barProgressDialog;
       Handler updateBarHandler;
       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
       }
       public void launchRingDialog(View view)
       {
              final ProgressDialog ringProgressDialog = ProgressDialog.show(MainActivity.this, "Please wait ...", "Downloading Image ...",true);
              ringProgressDialog.setCancelable(true);
              new Thread(new Runnable()
              {
                     @Override
                     public void run()
                     {
                           try
                           {
                                  // Here you should write your time consuming task...
                                  // Let the progress ring for 10 seconds...
                                  Thread.sleep(10000);
                           }
                           catch (Exception e)
                           {

                           }
                           ringProgressDialog.dismiss();
                     }
              }).start();
       }
}

Step 3 :
Paste the following code in activity_main.xml file.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="launchRingDialog"
        android:text="ProgressDialog Ring" />


</LinearLayout>