Sunday, December 16, 2012

andEngine tutorial refferences

andEngine gl2 splash screen

Download: http://www.mediafire.com/?ar2w8zg4giigpxo


package matim.development;

import org.andengine.engine.camera.Camera;
import org.andengine.engine.handler.timer.ITimerCallback;
import org.andengine.engine.handler.timer.TimerHandler;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.FillResolutionPolicy;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.background.Background;
import org.andengine.entity.sprite.Sprite;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.util.GLState;
import org.andengine.ui.activity.BaseGameActivity;

import android.util.Log;
import android.view.Display;

/**
 * @author Matim Development
 * @version 1.0.0
 * <br><br>
 * https://sites.google.com/site/matimdevelopment/
 */
public class SplashTemplate extends BaseGameActivity
{
private int CAMERA_WIDTH ;
private int CAMERA_HEIGHT;

private Camera camera;
private Scene splashScene;
private Scene mainScene;

    private BitmapTextureAtlas splashTextureAtlas;
    private ITextureRegion splashTextureRegion;
    private Sprite splash;
   
    Display mDisplay;
   
private enum SceneType
{
SPLASH,
MAIN,
OPTIONS,
WORLD_SELECTION,
LEVEL_SELECTION,
CONTROLLER
}

private SceneType currentScene = SceneType.SPLASH;

@Override
public EngineOptions onCreateEngineOptions()
{
Log.d("-------onCreateEngineOptions()---------", " ");
mDisplay = getWindowManager().getDefaultDisplay();

CAMERA_HEIGHT = mDisplay.getHeight();
CAMERA_WIDTH = mDisplay.getWidth();

camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.PORTRAIT_FIXED, new FillResolutionPolicy(), camera);
return engineOptions;
}

@Override
public void onCreateResources(OnCreateResourcesCallback pOnCreateResourcesCallback) throws Exception
{
Log.d("-------onCreateResources()---------", " ");
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
        splashTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 256, 256, TextureOptions.DEFAULT);
        splashTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(splashTextureAtlas, this, "splash.png", 0, 0);
        splashTextureAtlas.load();
     
        pOnCreateResourcesCallback.onCreateResourcesFinished();
}

@Override
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback) throws Exception
{
Log.d("-------onCreateScene()---------", " ");
initSplashScene();
        pOnCreateSceneCallback.onCreateSceneFinished(this.splashScene);
}

@Override
public void onPopulateScene(Scene pScene, OnPopulateSceneCallback pOnPopulateSceneCallback) throws Exception
{
Log.d("-------onPopulateScene()---------", " ");
mEngine.registerUpdateHandler(new TimerHandler(5f, new ITimerCallback()
{
            public void onTimePassed(final TimerHandler pTimerHandler)
            {
                mEngine.unregisterUpdateHandler(pTimerHandler);
                loadResources();
                loadScenes();        
                splash.detachSelf();
                mEngine.setScene(mainScene);
                currentScene = SceneType.MAIN;
            }
}));
 
pOnPopulateSceneCallback.onPopulateSceneFinished();
}


public void loadResources()
{
Log.d("-------loadResources()()---------", " ");
// Load your game resources here!
}

private void loadScenes()
{
Log.d("-------loadScenes()---------", " ");
// load your game here, you scenes
mainScene = new Scene();
mainScene.setBackground(new Background(50, 50, 50));
}

// ===========================================================
// INITIALIZIE
// ===========================================================

private void initSplashScene()
{
Log.d("-------initSplashScene()---------", " ");
    splashScene = new Scene();
    splash = new Sprite(0, 0, splashTextureRegion, mEngine.getVertexBufferObjectManager())
    {
    @Override
            protected void preDraw(GLState pGLState, Camera pCamera)
    {
                super.preDraw(pGLState, pCamera);
                pGLState.enableDither();
            }
    };
   
    splash.setScale(1.5f);
    splash.setPosition((CAMERA_WIDTH - splash.getWidth()) * 0.5f, (CAMERA_HEIGHT - splash.getHeight()) * 0.5f);
    splashScene.attachChild(splash);
}
}

Tuesday, November 20, 2012

scroll view example


package com.example.scrollexample;

import android.app.Activity;
import android.content.res.Resources;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ScrollView;

public class MainActivity extends Activity
{

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

ImageView iv = (ImageView) findViewById(R.id.imageView1);

ScrollView sv = (ScrollView) findViewById(R.id.scrollView1);
sv.setHorizontalScrollBarEnabled(true);
Resources res = getResources();
BitmapDrawable bitmap = (BitmapDrawable) res.
    getDrawable(R.drawable.bts_silom_line_map);
int imgW = bitmap.getIntrinsicWidth();
int imgH = bitmap.getIntrinsicHeight();

iv.setImageDrawable(bitmap);

ViewGroup.LayoutParams params = (ViewGroup.LayoutParams) iv.getLayoutParams();
params.width = imgW;
params.height = imgH;

  }
}

//////////////////////////////////////////////////////////////////////////////////


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <HorizontalScrollView
        android:id="@+id/horizontalScrollView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
<ScrollView
       android:id="@+id/scrollView1"
       android:layout_width="match_parent"
       android:layout_height="wrap_content" >
<ImageView
       android:id="@+id/imageView1"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"/>
   </ScrollView>
    </HorizontalScrollView>
</LinearLayout>

Download:
http://www.mediafire.com/?ge1jql7g7s96mmb

Monday, November 19, 2012

nice SlidingDrawer layout


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

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
         />

    <SlidingDrawer
        android:id="@+id/drawer"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:content="@+id/content"
        android:handle="@+id/handle"
        android:orientation="horizontal" >

        <ImageView
            android:id="@id/handle"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:src="@drawable/next_button" />

        <LinearLayout
            android:id="@id/content"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="#55000000"
            android:orientation="vertical"
            android:padding="10dp" >

            <Button
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text=" - Button - " />

            <Button
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text=" - Button - " />

            <Button
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text=" - Button - " />

            <Button
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text=" - Button - " />

            <Button
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text=" - Button - " />

            <Button
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text=" - Button - " />
        </LinearLayout>
    </SlidingDrawer>

</FrameLayout>

get back Logcat

window => show view => Logcat

Saturday, November 17, 2012

android database raw query


package home.database;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.util.Log;

public class CRUDonDB  {

private final String SAMPLE_DB_NAME = "shoppingDb";
private final String SAMPLE_TABLE_NAME = "item_info";
Context context;
SQLiteDatabase sampleDB = null;
ArrayList<String> results = new ArrayList<String>();

public CRUDonDB(Context _context)
{
context = _context;

try
{
sampleDB = context.openOrCreateDatabase(SAMPLE_DB_NAME, context.MODE_WORLD_WRITEABLE,
null);

sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " + SAMPLE_TABLE_NAME
+ " (stationId VARCHAR, stationName VARCHAR,"
+ " shoppingMallName VARCHAR,productName VARCHAR,"
+ " purchased INT(3),UNIQUE(shoppingMallName, productName) ) ;");

Log.d("---------database created-----------", " ");

}
catch (SQLiteException se)
{
Log.e(getClass().getSimpleName(),
"Could not create or Open the database");
Log.d("---------catch-----------", " ");
}
finally
{
Log.d("---------finally-----------", " ");
// if (sampleDB != null)
// sampleDB.execSQL("DELETE FROM " + SAMPLE_TABLE_NAME);
//sampleDB.close();
}
}

public void insert_item_into_db(String etItemOne, String etItemTwo,String etItemThree,String etItemFour)
{
if( !etItemOne.equals("") )
{
try
{
sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAME
+ " Values ('s3','silom','nondon','"+etItemOne+"','0');");

Log.d("---------insert_item_into_db()-----------", etItemOne.toString() );
}
catch(SQLException e)
{
Log.d("----------SQLException------------", " ");
}
}

if( !etItemTwo.equals("") )
{
try
{
sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAME
+ " Values ('s3','silom','nondon','"+etItemTwo+"','0');");

Log.d("---------insert_item_into_db()-----------", etItemTwo.toString() );
}
catch(SQLException e)
{
Log.d("----------SQLException------------", " ");
}

}

if( !etItemThree.equals("") )
{
try
{
sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAME
+ " Values ('s3','silom','nondon','"+etItemThree+"','0');");

Log.d("---------insert_item_into_db()-----------", etItemThree.toString() );
}
catch(SQLException e)
{
Log.d("----------SQLException------------", " ");
}
}

if( !etItemFour.equals("") )
{
try
{
sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAME
+ " Values ('s3','silom','nondon','"+etItemFour+"','0');");

Log.d("---------insert_item_into_db()-----------", etItemFour.toString() );
}
catch(SQLException e)
{
Log.d("----------SQLException------------", " ");
}
}


}

public Cursor select_item_from_db()
{
Cursor cursor = sampleDB.rawQuery("SELECT * FROM "
+ SAMPLE_TABLE_NAME , null);

/*if (cursor != null) {
if (c.moveToFirst()) {
do {
String firstName = cursor.getString(cursor
.getColumnIndex("FirstName"));
int age = cursor.getInt(cursor.getColumnIndex("Age"));

Log.d("---------firstName"+firstName+"-----------", " ");

results.add("" + firstName + ",Age: " + age);
} while (cursor.moveToNext());
}
}
*/
Log.d("---------select_item_from_db()-----------", " ");

return cursor;
}

public void update_purchased_info(String productName)
{
try
{
sampleDB.execSQL("update " + SAMPLE_TABLE_NAME
+ " set purchased=1 where productName='"+productName+"'");

Log.d("----------update success------------", " ");
}
catch(SQLException e)
{
Log.d("----------update SQLException="+e.getStackTrace().toString()+"------------", " ");
}

}

public void delete_item_info(String productName)
{
try
{
sampleDB.execSQL("delete from " + SAMPLE_TABLE_NAME
+ " where productName='"+productName+"'");

Log.d("----------delete success------------", " ");
}
catch(SQLException e)
{
Log.d("----------update SQLException="+e.getStackTrace().toString()+"------------", " ");
}

}

public void close_db()
{
sampleDB.close();
}

}

android simple alert dialog


package com.example.alertdialogtest;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends Activity {

AlertDialog.Builder builder;

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

showDialog();

AlertDialog alert = builder.create();
alert.show();

}

void showDialog() {
//final CharSequence[] items = { "Red", "Green", "Blue" };
final CharSequence[] items = getResources().getStringArray(R.array.countries_array);
builder = new AlertDialog.Builder(this);
builder.setTitle("Set text color");

builder.setItems(items, new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int selectItem) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this,
items[selectItem],
Toast.LENGTH_SHORT).show();
}
});

}

}

////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="countries_array">
        
        <item name="bangladesh">bangladesh</item>
        <item name="usa">usa</item>
        <item name="russia">russia</item>
        <item name="england">england</item>
        
    </string-array>
</resources>

Download:
http://www.mediafire.com/?pp0fyijhpm5ks52

Tuesday, September 4, 2012

show image from url


package firstdroid.tutorial.gridview;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class BannerImageLoader
{
    Bitmap getImageBitmap(String url)
    {
       Bitmap bm = null;
     
       try
       {
           URL aURL = new URL(url);
           URLConnection conn = aURL.openConnection();
           conn.connect();
           InputStream is = conn.getInputStream();
           BufferedInputStream bis = new BufferedInputStream(is);
           bm = BitmapFactory.decodeStream(bis);
           bis.close();
           is.close();
      }
      catch (IOException e)
      {
          Log.d("---------Error getting bitmap------------", " ");
      }
     
      return bm;
   }  
}

Wednesday, July 25, 2012

grid vew in ListView

download: http://www.mediafire.com/?us2oa4vcvav726a

main.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:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
 
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text=" " />

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
    </ListView>

</LinearLayout>


list_item.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:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:text="a" />
 
    <GridView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/myGrid"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@color/Black"
        android:columnWidth="60dp"
        android:gravity="center"
        android:horizontalSpacing="5dp"
        android:numColumns="auto_fit"
        android:padding="1dp"
        android:stretchMode="columnWidth"
        android:verticalSpacing="5dp" >
    </GridView>

 
</LinearLayout>


grid_item.xml
-------------------------

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="5dp"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/grid_item_image"
        android:layout_width="50px"
        android:layout_height="50px"
        android:layout_marginRight="10px"
        android:src="@drawable/ic_launcher" >
    </ImageView>

    <TextView
        android:id="@+id/grid_item_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@+id/label"
        android:layout_marginTop="5px"
        android:textSize="15px" >
    </TextView>

</LinearLayout>


values/country.xml
---------------------------------

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="countries_array">
       
        <item name="bangladesh">bangladesh</item>
        <item name="usa">usa</item>
        <item name="russia">russia</item>
        <item name="england">england</item>
        <item name="japan">japan</item>
        <item name="korea">korea</item>
        <item name="china">china</item>
       
    </string-array>
</resources>




MainActivity.java
----------------------------------

package home.ListViewBaseAdapter;

import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

public class MainActivity extends ListActivity
{
    String[] countries;
    int c=0;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
   
        countries = getResources().getStringArray(R.array.countries_array);
   
        //Toast.makeText(this,"Main class",Toast.LENGTH_LONG).show();
        Log.d("------------main class-----------", "start");
        setListAdapter(new MyListAdapter(this,android.R.layout.simple_list_item_1,R.id.textView1,countries));

        //Toast.makeText(this,"end of Main class",Toast.LENGTH_LONG).show();
        Log.d("------------main class-----------", "end");
   
        ListView listView = getListView();//getListView() from ListActivity //public class ListView
   
        listView.setTextFilterEnabled(true);

   
   
    }
}


MyListAdapter.java
---------------------------------

package home.ListViewBaseAdapter;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MyListAdapter extends ArrayAdapter<String> {
    Context context;

    Integer resource, textViewResourceId;

    String[] strings;
 
    GridView myGrid;
    ImageView imageViewCityImage;
    ImageAdapter imageAdapter;
 
    static final String[] MOBILE_OS = new String[] { "Android", "iOS",
        "Windows", "Blackberry" };

    int c = 0;

    public MyListAdapter(Context _context, int _resource, int _textViewResourceId,
            String[] _strings) {
        super(_context, _resource, _textViewResourceId, _strings);

        context = _context;
        resource = _resource;
        textViewResourceId = _textViewResourceId;
        strings = _strings;

        // Toast.makeText(Main.this,"getView() row="+c,Toast.LENGTH_LONG).show();

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        c++;
        // Toast.makeText(Main.this,"getView() c="+c,Toast.LENGTH_LONG).show();
        Log.d("------------getView()-----------c=" + c, "c=" + c);
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View row = inflater.inflate(R.layout.list_item, parent, false);

        String[] items = context.getResources().getStringArray(
                R.array.countries_array);

        TextView tv = (TextView) row.findViewById(R.id.textView1);
        myGrid=(GridView) row.findViewById(R.id.myGrid);

        tv.setText(items[position]);
     
     
        myGrid.setAdapter(imageAdapter=new ImageAdapter(context, MOBILE_OS) );

        tv.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                Toast.makeText(context.getApplicationContext(),
                        ((TextView) v).getText(), Toast.LENGTH_SHORT).show();
            }
        });

        Log.d("------------row=-----------" + row, "row=" + row);

        return row;
    }

}






ImageAdapter.java
---------------------------------------

package home.ListViewBaseAdapter;

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

public class ImageAdapter extends BaseAdapter
{
    private Context context;
    private final String[] mobileValues;

    public ImageAdapter(Context context, String[] mobileValues)
    {
        this.context = context;
        this.mobileValues = mobileValues;
    }

    public View getView(int position, View convertView, ViewGroup parent)
    {

        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View gridView;

        if (convertView == null) {

            gridView = new View(context);

            // get layout from mobile.xml
            gridView = inflater.inflate(R.layout.grid_item, null);

            // set value into textview
            TextView textView = (TextView) gridView
                    .findViewById(R.id.grid_item_label);
            textView.setText(mobileValues[position]);

            // set image based on selected text
            ImageView imageView = (ImageView) gridView
                    .findViewById(R.id.grid_item_image);

            String mobile = mobileValues[position];

            if (mobile.equals("Windows")) {
                imageView.setImageResource(R.drawable.windows_logo);
            } else if (mobile.equals("iOS")) {
                imageView.setImageResource(R.drawable.ios_logo);
            } else if (mobile.equals("Blackberry")) {
                imageView.setImageResource(R.drawable.blackberry_logo);
            } else {
                imageView.setImageResource(R.drawable.android_logo);
            }

        } else {
            gridView = (View) convertView;
        }

        return gridView;
    }

    @Override
    public int getCount() {
        return mobileValues.length;
    }

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

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

}







Thursday, July 12, 2012

show data from mysql in android

download: http://www.mediafire.com/?e498o8m1em423bk


index.php
--------------------------

<?php
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }


mysql_select_db("Deal", $con);


$result = mysql_query("SELECT * FROM city");


while($row = mysql_fetch_assoc($result))


  $output[]=$row;


print(json_encode($output)) ;
mysql_close($con);
?


City.java
---------------------
package com.androidtutorialbd.blogspot;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.net.ParseException;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class City extends Activity 
{
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {

        super.onCreate(savedInstanceState);

        String result = null;
        InputStream is = null;
        StringBuilder sb = null;
        ArrayList nameValuePairs = new ArrayList();
        List r = new ArrayList();
        String city_name;
        Integer city_id;

        try 
        {

            // http post
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://192.168.1.244/sessionExample/");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        } 
        catch (Exception e) 
        {
            Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
                    .show();
        }
        

        // Convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "UTF-8"));

            sb = new StringBuilder();

            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            is.close();

            result = sb.toString();
        } 
        catch (Exception e) 
        {
            Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
                    .show();
        }
        // END Convert response to string
        
        
        try 
        {
            JSONArray jArray = new JSONArray(result);
            JSONObject json_data = null;
            for (int i = 0; i < jArray.length(); i++) 
            {
                json_data = jArray.getJSONObject(i);
                //r.add(json_data.getString("CITY_NAME"));
                
                city_id=json_data.getInt("CITY_ID");
                city_name=json_data.getString("CITY_NAME");
                
                //Log.d("-----"+json_data.getString("CITY_NAME")+"------", " " );
                Log.d("-------"+"city_id="+city_id.toString()+" "+"CITY_NAME="+city_name+"-------", " ");
            }
            /*setListAdapter(new ArrayAdapter(this,
                    android.R.layout.simple_expandable_list_item_1, r)); */
        }
        catch (JSONException e1)
        {
            Toast.makeText(getBaseContext(), e1.toString(), Toast.LENGTH_LONG)
                    .show();
        } 
        catch (ParseException e1)
        {
            Toast.makeText(getBaseContext(), e1.toString(), Toast.LENGTH_LONG)
                    .show();
        }

    }
}





AndroidManifest.xml
------------------------------

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidtutorialbd.blogspot"
    android:versionCode="1"
    android:versionName="1.0" >


    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>


    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".City"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />


                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>


</manifest>

Wednesday, June 20, 2012

change background color in openGL in android


package home.backGroundColorChange;

import java.util.Random;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.app.Activity;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;


public class ClearActivity extends Activity
{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mGLView = new ClearGLSurfaceView(this);
       
        setContentView(mGLView);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mGLView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mGLView.onResume();
    }

    private GLSurfaceView mGLView;
}


class ClearGLSurfaceView extends GLSurfaceView
{
    ClearRenderer mRenderer;
   
    public ClearGLSurfaceView(Context context)
    {
        super(context);
        mRenderer = new ClearRenderer();
        setRenderer(mRenderer);
    }

    public boolean onTouchEvent(final MotionEvent event)
    {
        final Float blue_color=this.genarate_random_number();
        queueEvent(new Runnable()
                                {
                                    public void run()
                                    {
                                        mRenderer.setColor(event.getX() / getWidth(),
                                                event.getY() / getHeight(), blue_color);
                                    }
                                }  
                 );
       
        Log.d("getWidth="+getWidth()+" "+"getHeight="+getHeight()+"event.getX="+event.getX()+" "+"event.getY="+event.getY()+" ","blueColor="+blue_color);
            return true;
    }
   
    public float genarate_random_number()
    {
        Random rand = new Random();
       
       
        float pick = rand.nextFloat();
       
        return pick;
    }

}


class ClearRenderer implements GLSurfaceView.Renderer
{
    private float mRed;
    private float mGreen;
    private float mBlue;
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        // Do nothing special.
    }

    public void onSurfaceChanged(GL10 gl, int w, int h) {
        gl.glViewport(0, 0, w, h);
    }

    public void onDrawFrame(GL10 gl) {
        gl.glClearColor(mRed, mGreen, mBlue, 0.0f);
        gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
    }

    public void setColor(float r, float g, float b)
    {
        mRed = r;
        mGreen = g;
        mBlue = b;
    }

}

generate random number in java / android


 import java.util.Random;
 public class RandomTest
 {

  public static void main(String[] args)
 {
    Random rand = new Random();

    for(int i=0;i<10;i++)
  {
      float pick = rand.nextFloat(); // random between 0.0 to 1.0
      System.out.println(pick);
  }
  }

  Random rand = new Random();
 }


////////////////////////////////////////////////////////////


 import java.util.Random;
 public class RandomTest
 {

   public static void main(String[] args)
  {
     Random rand = new Random(20071969);

     for(int i=0;i<10;i++)
   {
       int pick = rand.nextInt(10);
       System.out.println(pick);
   }
   }

   Random rand = new Random();
 }

Thursday, June 14, 2012

android openGL touch events

HelloOpenGLES10.java
---------------------------------------------

package com.example.android.apis.graphics;

import android.app.Activity;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.view.MotionEvent;

public class HelloOpenGLES10 extends Activity
{
    private GLSurfaceView mGLView;
 
 

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        // Create a GLSurfaceView instance and set it
        // as the ContentView for this Activity.
        mGLView = new HelloOpenGLES10SurfaceView(this);
        setContentView(mGLView);
    }
 
    @Override
    protected void onPause()
    {
        super.onPause();
        mGLView.onPause();
    }
 
    @Override
    protected void onResume()
    {
        super.onResume();
        // The following call resumes a paused rendering thread.
        // If you de-allocated graphic objects for onPause()
        // this is a good place to re-allocate them.
        mGLView.onResume();
    }
}

class HelloOpenGLES10SurfaceView extends GLSurfaceView
{
    private final float TOUCH_SCALE_FACTOR = 180.0f / 320;
    private HelloOpenGLES10Renderer mRenderer;
    private float mPreviousX;
    private float mPreviousY;

    public HelloOpenGLES10SurfaceView(Context context){
        super(context);
        // set the mRenderer member
        mRenderer = new HelloOpenGLES10Renderer();
        setRenderer(mRenderer);
     
        // Render the view only when there is a change
        setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
    }
 
    @Override
    public boolean onTouchEvent(MotionEvent e) {
        // MotionEvent reports input details from the touch screen
        // and other input controls. In this case, you are only
        // interested in events where the touch position changed.

        float x = e.getX();
        float y = e.getY();
     
        switch (e.getAction()) {
            case MotionEvent.ACTION_MOVE:
 
                float dx = x - mPreviousX;
                float dy = y - mPreviousY;
 
                // reverse direction of rotation above the mid-line
                if (y > getHeight() / 2) {
                  dx = dx * -1 ;
                }
 
                // reverse direction of rotation to left of the mid-line
                if (x < getWidth() / 2) {
                  dy = dy * -1 ;
                }
           
                mRenderer.mAngle += (dx + dy) * TOUCH_SCALE_FACTOR;
                requestRender();
        }

        mPreviousX = x;
        mPreviousY = y;
        return true;
    }
}



HelloOpenGLES10Renderer.java
-----------------------------------------------------

package com.example.android.apis.graphics;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.opengl.GLSurfaceView;
import android.opengl.GLU;

public class HelloOpenGLES10Renderer implements GLSurfaceView.Renderer {
    private FloatBuffer triangleVB;
    public float mAngle;
 
    public void onSurfaceCreated(GL10 gl, EGLConfig config)
    {
        // Set the background frame color
        gl.glClearColor(0.1f, 0.5f, 0.5f, 1.0f);
     
     // Enable use of vertex arrays
        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    }

    public void onDrawFrame(GL10 gl) {
        // Redraw background color
        gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
     
     // Set GL_MODELVIEW transformation mode
        gl.glMatrixMode(GL10.GL_MODELVIEW);
        gl.glLoadIdentity();                      // reset the matrix to its default state

        // When using GL_MODELVIEW, you must set the camera view
        GLU.gluLookAt(gl, 0, 0, -5, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
     
     // Create a rotation for the triangle
        //long time = SystemClock.uptimeMillis() % 4000L;
        //float angle = 0.090f * ((int) time);
        gl.glRotatef(mAngle, 0.0f, 0.0f, 1.0f);  
     
        // initialize the triangle vertex array
        initShapes();
     
     // Draw the triangle
        gl.glColor4f(0.63671875f, 0.76953125f, 0.22265625f, 0.0f);
        gl.glVertexPointer(3, GL10.GL_FLOAT, 0, triangleVB);
        gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3);
    }

    public void onSurfaceChanged(GL10 gl, int width, int height)
    {
        gl.glViewport(0, 0, width, height);
     
        gl.glViewport(0, 0, width, height);
     
        // make adjustments for screen ratio
        float ratio = (float) width / height;
        gl.glMatrixMode(GL10.GL_PROJECTION);        // set matrix to projection mode
        gl.glLoadIdentity();                        // reset the matrix to its default state
        gl.glFrustumf(-ratio, ratio, -1, 1, 3, 7);  // apply the projection matrix
    }

    private void initShapes()
    {

        float triangleCoords[] = {
                // X, Y, Z
                -0.5f, -0.25f, 0,
                0.5f, -0.25f, 0,
                0.0f, 0.559016994f, 0
                                    };

        // initialize vertex Buffer for triangle
        ByteBuffer vbb = ByteBuffer.allocateDirect(
        // (# of coordinate values * 4 bytes per float)
                triangleCoords.length * 4);
        vbb.order(ByteOrder.nativeOrder());// use the device hardware's native
                                           // byte order
        triangleVB = vbb.asFloatBuffer(); // create a floating point buffer from
                                          // the ByteBuffer
        triangleVB.put(triangleCoords); // add the coordinates to the
                                        // FloatBuffer
        triangleVB.position(0); // set the buffer to read the first coordinate

    }

}

Sunday, April 29, 2012

get accelerometer value


SensorTestActivity.java
--------------------------------
package home.SensorTest;

import java.util.List;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class SensorTestActivity extends Activity implements SensorEventListener
{
    TextView tvXaxis,tvYaxis,tvZaxis;
    List<Sensor> sensors;
    SensorManager sensorManager;
    Sensor accSensor;
   
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initUi();
       
        sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
        // add listener. The listener will be HelloAndroid (this) class
        sensorManager.registerListener(this,
                sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_NORMAL);      
     
    }
   
    public void initUi()
    {
        tvXaxis=(TextView)findViewById(R.id.textViewXaxis);
        tvYaxis=(TextView)findViewById(R.id.textViewYaxis);
        tvZaxis=(TextView)findViewById(R.id.textViewZaxis);
    }
   
 
    public void onAccuracyChanged(Sensor sensor, int accuracy)
    {
    }

   
    public void onSensorChanged(SensorEvent event)
    {
        if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER)
        {
            updateView(event.values[0], event.values[1], event.values[2]);
        }
       
       
    }
   
    public void updateView( Float x, Float y, Float z )
    {
        tvXaxis.setText("x axis = "+x.toString() );
        tvYaxis.setText("y axis ="+y.toString() );
        tvZaxis.setText("z axis ="+z.toString() );
    }
}


main.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:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Sensor Test Activity" />

    <TextView
        android:id="@+id/textViewXaxis"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="x axis"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textViewYaxis"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="y axis"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textViewZaxis"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="z axis"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>


AndroidManifest.xml
------------------------------------------------------

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="home.SensorTest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".SensorTestActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>



get sensor info


SensorTestActivity.java
----------------------------------------------

package home.SensorTest;

import java.util.List;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;

public class SensorTestActivity extends Activity {
    TextView tvXaxis,tvYaxis,tvZaxis;
    List<Sensor> sensors;
    SensorManager sensorManager;
   
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initUi();
       
        sensorManager=(SensorManager) getSystemService(SENSOR_SERVICE);
       
        sensors=sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
       
        tvXaxis.setText( "sensor name : "+sensors.get(0).getName() );
        tvYaxis.setText( "sensor vendor : "+sensors.get(0).getVendor() );
        tvZaxis.setText( "sensor version : "+sensors.get(0).getVersion() );
       
       
    }
   
    public void initUi()
    {
        tvXaxis=(TextView)findViewById(R.id.textViewXaxis);
        tvYaxis=(TextView)findViewById(R.id.textViewYaxis);
        tvZaxis=(TextView)findViewById(R.id.textViewZaxis);
    }
   
    public class MySensorEventListener implements SensorEventListener
    {

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy)
        {
            // TODO Auto-generated method stub
           
        }

        @Override
        public void onSensorChanged(SensorEvent event)
        {
            // TODO Auto-generated method stub
           
        }
       
    }
}




main.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:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Sensor Test Activity" />

    <TextView
        android:id="@+id/textViewXaxis"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="x axis"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textViewYaxis"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="y axis"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textViewZaxis"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="z axis"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>