Saturday, 22 June 2013

Localization Example in Android

LocalActivity.java
package com.local;

import java.util.Locale;

import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class LocalActivity extends Activity {
    /** Called when the activity is first created. */
Button mButton;
TextView mTextView;
String language ="";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mButton=(Button)findViewById(R.id.button);
        mTextView=(TextView)findViewById(R.id.txt);
     
        mButton.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

       Locale locale = null;
       if (language.equalsIgnoreCase("en")) {
           locale = new Locale("en");
       } else if (language.equalsIgnoreCase("es")) {
           locale = new Locale("es");
       }
       Locale.setDefault(locale);
       Configuration config = new Configuration();
       config.locale = locale;
       getBaseContext().getResources().updateConfiguration(config, null);
       mTextView.setText(getString(R.string.app_name));
//        mButton.setText(getString(R.string.app_name));
}
});
       
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu , menu);
        return true;
    }
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.english:
            language="en";
              break;
              case R.id.spanish:
             language="es";
             break;
        default:
              return super.onOptionsItemSelected(item);
        }
        return true;
}
}
In values folder string.xml
string.xml files
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Application Name</string>
</resources>
-----------------------------------------------------------------
in values-es folder string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, LocalActivity!</string>
    <string name="app_name">nombre de la aplicación</string>
</resources>

in Device select menu option for change language.



Saturday, 25 May 2013

Database Connection in Android


package com.android.database;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

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

public class DatabaseConnectionAPI extends SQLiteOpenHelper{

//The Android's default system path of your application database.
private final static String DB_PATH = "/data/data/com.android.database/databases/";

private final static String DB_NAME = "demo.sqlite";

private final Context myContext;

private static SQLiteDatabase db;

/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* @param context
*/
public DatabaseConnectionAPI(Context context)
{

super(context, DB_NAME, null, 1);
this.myContext = context;
}

/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException
{

boolean dbExist = checkDataBase();

if(dbExist)
{
//do nothing - database already exist
}
else
{

//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();

try
{
copyDataBase();
}
catch (IOException e)
{

throw new Error("Error copying database");
}
}
}

/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){

SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}

/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException{

//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);

// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;

//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);

//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[2048];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}

//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();

}

public void openDataBase() throws SQLException{
try
{
db.close();
}
catch(Exception e)
{
System.out.println("no database connected to close");
}
//Open the database
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

}

@Override
public synchronized void close() {
if(db != null)
db.close();
super.close();
}

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}
/**
* Use this function to set the value of a particular column
*
* @param columnName The column name whose value is to be changed
* @param newColumnValue The value to be replaced in the column
* @param whereColumnName The column name to be compared with the where clause
* @param whereColumnValue The value to be compared in the where clause
*/
void onUpdateSet(String columnName, String newColumnValue, String[] whereColumnName, String[] whereColumnValue){
String expanded_ColumnNames = new String(whereColumnName[0]);
String expanded_ColumnValues = new String(whereColumnValue[0]);
for(int i=1;i {
expanded_ColumnNames = expanded_ColumnNames+","+whereColumnName[i];
expanded_ColumnValues = expanded_ColumnValues+","+whereColumnValue[i];
}
try
{
openDataBase();
db.execSQL("update recipe set \""+columnName+"\" = \""+newColumnValue+"\" where \""+expanded_ColumnNames+"\" = \""+expanded_ColumnValues+"\"");
}
catch(Exception e)
{
System.out.println("Update couldnt complete "+e);
}

}

/**
* Query the given table, returning a Cursor over the result set.
*
* @param table The table name to compile the query against.
* @param columns A list of which columns to return. Passing null will return all columns,
* which is discouraged to prevent reading data from storage that isn't going to be used.
* @param selection A filter declaring which rows to return, formatted
* as an SQL WHERE clause (excluding the WHERE itself). Passing null
* will return all rows for the given table.
* @param selectionArgs You may include ?s in selection, which will be
* replaced by the values from selectionArgs, in order that they appear
* in the selection. The values will be bound as Strings.
* @param groupBy A filter declaring how to group rows, formatted as an
* SQL GROUP BY clause (excluding the GROUP BY itself). Passing null
* will cause the rows to not be grouped.
* @param having A filter declare which row groups to include in the
* cursor, if row grouping is being used, formatted as an SQL HAVING
* clause (excluding the HAVING itself). Passing null will cause all
* row groups to be included, and is required when row grouping is
* not being used.
* @param orderBy How to order the rows, formatted as an SQL
* ORDER BY clause (excluding the ORDER BY itself). Passing
* null will use the default sort order, which may be unordered.
* @return A Cursor object, which is positioned before the first entry
*/
Cursor onQueryGetCursor(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
{
Cursor query = null;
try
{
openDataBase();
query = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
System.out.println("@@@@@ Query is :"+query);
}
catch(Exception e)
{
System.out.println("Query couldnt complete "+e);
}
return query;
}
/**
* Use this method to search a particular String in the provided field.
*
*
* @param columns The array of columns to be returned
* @param table The table name
* @param whereColumn The where clause specifying a particular columns
* @param keyword The keyword which is to be searched
*
* @return The cursor containing the result of the query
*/
Cursor onSearchGetCursor(String[] columns, String table, String[] whereColumn, String keyword)
{
String expColumns = new String(columns[0]);
Cursor rawquery=null;
for(int i=1;i expColumns = expColumns+","+columns[i];
try
{
openDataBase();
rawquery = db.rawQuery("SELECT "+expColumns+" from "+table+" where "+whereColumn[0]+" like \"%"+keyword+"%\" or "+whereColumn[1]+" like \"%"+keyword+"%\" or "+whereColumn[2]+" like \"%"+keyword+"%\"", null);
}
catch(Exception e)
{
System.out.println("Raw Query couldnt complete "+e);
}
return rawquery;
}
}

Sunday, 31 March 2013

Add Dynamic Data in Listview With SimpleAdapter and BaseAdapter in Android

NewMainClass.java


public class NewMainClass extends Activity
{
Button mButton;
ListView mListView;

public static BaseAdapter mAdapter;
public ArrayList<GetProductDetail>temp_GetProductDetails;
GetProductDetail mProductDetail;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newmain);
mButton=(Button)findViewById(R.id.btn);
mListView=(ListView)findViewById(R.id.list);
mAdapter=new baseAdapter(NewSecondActivity.mGetProductDetails);
   mListView.setAdapter(mAdapter);

   mButton.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Intent mIntent=new Intent(getApplicationContext(), NewSecondActivity.class);
startActivity(mIntent);
}
});
     
   mListView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> a, View v, int position, long id) {
        Toast.makeText(NewMainClass.this, "You have chosen: " + " " + position, Toast.LENGTH_LONG).show();
        }
        });
 
}

@Override
protected void onResume() {
super.onResume();
System.out.println("Class Size "+NewSecondActivity.mGetProductDetails.size());
for (int i = 0; i <NewSecondActivity.mGetProductDetails.size(); i++)
{
String s=NewSecondActivity.mGetProductDetails.get(i).getPrice();
System.out.println("Price "+s);

}
}

public class baseAdapter extends BaseAdapter
{
ViewHolder holder ;

public baseAdapter(ArrayList<GetProductDetail> mGetProductDetails)
{
temp_GetProductDetails=mGetProductDetails;
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return temp_GetProductDetails.size();
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
mProductDetail = temp_GetProductDetails.get(position);

holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.newrow, null);
holder.mTextViewAmount=(TextView)convertView.findViewById(R.id.amount);
holder.mTextViewPrice=(TextView)convertView.findViewById(R.id.rate);
holder.mTextViewProduct=(TextView)convertView.findViewById(R.id.productname);
holder.mTextViewQty=(TextView)convertView.findViewById(R.id.qty);

holder.mTextViewAmount.setText(mProductDetail.getAmount());
holder.mTextViewPrice.setText(mProductDetail.getPrice());
holder.mTextViewProduct.setText(mProductDetail.getProduct());
holder.mTextViewQty.setText(mProductDetail.getQty());

return convertView;
}

}

public class ViewHolder
{
TextView mTextViewProduct;
TextView mTextViewPrice;
TextView mTextViewQty;
TextView mTextViewAmount;
}
 
}


NewSecondActivity.java

public class NewSecondActivity extends Activity{

EditText mEditTextProductName;
EditText mEditTextQty;
EditText mEditTextPrice;
EditText mEditTextAmount;
Button mButtonSend;
public static ArrayList<GetProductDetail>mGetProductDetails=new ArrayList<GetProductDetail>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);
mEditTextProductName=(EditText)findViewById(R.id.editText1);
mEditTextQty=(EditText)findViewById(R.id.editText2);
mEditTextPrice=(EditText)findViewById(R.id.editText3);
mEditTextAmount=(EditText)findViewById(R.id.editText4);

mButtonSend=(Button)findViewById(R.id.button1);
mButtonSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
GetProductDetail mProductDetail=new GetProductDetail();
mProductDetail.product=mEditTextProductName.getText().toString();
mProductDetail.qty=mEditTextQty.getText().toString();
mProductDetail.price=mEditTextPrice.getText().toString();
mProductDetail.amount=mEditTextAmount.getText().toString();
mGetProductDetails.add(mProductDetail);

NewMainClass.mAdapter.notifyDataSetChanged();
finish();
}
});
}

}

GetProductDetail.java

public class GetProductDetail {

String product="";
String qty="";
String price="";
String amount="";
public String getProduct() {
return product;
}
public void setProduct(String product) {
this.product = product;
}
public String getQty() {
return qty;
}
public void setQty(String qty) {
this.qty = qty;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}


Click below link  for download project.
https://sites.google.com/site/nepstareblogspotin/http-nepstare-blogspot-in/DemoArraylist.rar?attredirects=0&d=1

Searching Text in Listview


TextswitcherdemoActivity.java


public class TextswitcherdemoActivity extends Activity {

 ArrayAdapter<String> dataAdapter = null;

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

  //Generate list View from ArrayList
  displayListView();

 }

 private void displayListView() {

  //Array list of countries
  List<String> countryList = new ArrayList<String>();
  countryList.add("Aruba");
  countryList.add("Anguilla");
  countryList.add("Netherlands Antilles");
  countryList.add("Antigua and Barbuda");
  countryList.add("Bahamas");
  countryList.add("Belize");
  countryList.add("Bermuda");
  countryList.add("Barbados");
  countryList.add("Canada");
  countryList.add("Costa Rica");
  countryList.add("Cuba");
  countryList.add("Cayman Islands");
  countryList.add("Dominica");
  countryList.add("Dominican Republic");
  countryList.add("Guadeloupe");
  countryList.add("Grenada");
  countryList.add("Greenland");
  countryList.add("Guatemala");
  countryList.add("Honduras");
  countryList.add("Haiti");
  countryList.add("Jamaica");

  //create an ArrayAdaptar from the String Array
  dataAdapter = new ArrayAdapter<String>(this,
    R.layout.country_list, countryList);
  ListView listView = (ListView) findViewById(R.id.listView1);
  // Assign adapter to ListView
  listView.setAdapter(dataAdapter);

  //enables filtering for the contents of the given ListView
  listView.setTextFilterEnabled(true);

  listView.setOnItemClickListener(new OnItemClickListener() {
   public void onItemClick(AdapterView<?> parent, View view,
     int position, long id) {
    // When clicked, show a toast with the TextView text
    Toast.makeText(getApplicationContext(),
     ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
   }
  });

  EditText myFilter = (EditText) findViewById(R.id.myFilter);
  myFilter.addTextChangedListener(new TextWatcher() {

  public void afterTextChanged(Editable s) {
  }

  public void beforeTextChanged(CharSequence s, int start, int count, int after) {
  }

  public void onTextChanged(CharSequence s, int start, int before, int count) {
   dataAdapter.getFilter().filter(s.toString());
  }
  });
 }  
}


Click below link for download project
https://sites.google.com/site/httpnepstareblogspotin/http-nepstare-blogspot-in/Textswitcherdemo.rar?attredirects=0&d=1

Friday, 1 March 2013

Listview with Checkbox

PlanetsActivity .java

public class PlanetsActivity extends Activity {
 
  private ListView mainListView ;
  private Planet[] planets ;
  private ArrayAdapter<Planet> listAdapter ;
 
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
   
    // Find the ListView resource.
    mainListView = (ListView) findViewById( R.id.mainListView );
   
    // When item is tapped, toggle checked properties of CheckBox and Planet.
    mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override
      public void onItemClick( AdapterView<?> parent, View item,
                               int position, long id) {
        Planet planet = listAdapter.getItem( position );
        planet.toggleChecked();
        PlanetViewHolder viewHolder = (PlanetViewHolder) item.getTag();
        viewHolder.getCheckBox().setChecked( planet.isChecked() );
      }
    });

   
    // Create and populate planets.
    planets = (Planet[]) getLastNonConfigurationInstance() ;
    if ( planets == null ) {
      planets = new Planet[] {
          new Planet("Mercury"), new Planet("Venus"), new Planet("Earth"),
          new Planet("Mars"), new Planet("Jupiter"), new Planet("Saturn"),
          new Planet("Uranus"), new Planet("Neptune"), new Planet("Ceres"),
          new Planet("Pluto"), new Planet("Haumea"), new Planet("Makemake"),
          new Planet("Eris")
      };
    }
    ArrayList<Planet> planetList = new ArrayList<Planet>();
    planetList.addAll( Arrays.asList(planets) );
   
    // Set our custom array adapter as the ListView's adapter.
    listAdapter = new PlanetArrayAdapter(this, planetList);
    mainListView.setAdapter( listAdapter );    
  }
 
  /** Holds planet data. */
  private static class Planet {
    private String name = "" ;
    private boolean checked = false ;
    public Planet() {}
    public Planet( String name ) {
      this.name = name ;
    }
    public Planet( String name, boolean checked ) {
      this.name = name ;
      this.checked = checked ;
    }
    public String getName() {
      return name;
    }
    public void setName(String name) {
      this.name = name;
    }
    public boolean isChecked() {
      return checked;
    }
    public void setChecked(boolean checked) {
      this.checked = checked;
    }
    public String toString() {
      return name ;
    }
    public void toggleChecked() {
      checked = !checked ;
    }
  }
 
  /** Holds child views for one row. */
  private static class PlanetViewHolder {
    private CheckBox checkBox ;
    private TextView textView ;
    public PlanetViewHolder() {}
    public PlanetViewHolder( TextView textView, CheckBox checkBox ) {
      this.checkBox = checkBox ;
      this.textView = textView ;
    }
    public CheckBox getCheckBox() {
      return checkBox;
    }
    public void setCheckBox(CheckBox checkBox) {
      this.checkBox = checkBox;
    }
    public TextView getTextView() {
      return textView;
    }
    public void setTextView(TextView textView) {
      this.textView = textView;
    }  
  }
 
  /** Custom adapter for displaying an array of Planet objects. */
  private static class PlanetArrayAdapter extends ArrayAdapter<Planet> {
   
    private LayoutInflater inflater;
   
    public PlanetArrayAdapter( Context context, List<Planet> planetList ) {
      super( context, R.layout.simplerow, R.id.rowTextView, planetList );
      // Cache the LayoutInflate to avoid asking for a new one each time.
      inflater = LayoutInflater.from(context) ;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      // Planet to display
      Planet planet = (Planet) this.getItem( position );

      // The child views in each row.
      CheckBox checkBox ;
      TextView textView ;
     
      // Create a new row view
      if ( convertView == null ) {
        convertView = inflater.inflate(R.layout.simplerow, null);
       
        // Find the child views.
        textView = (TextView) convertView.findViewById( R.id.rowTextView );
        checkBox = (CheckBox) convertView.findViewById( R.id.CheckBox01 );
       
        // Optimization: Tag the row with it's child views, so we don't have to
        // call findViewById() later when we reuse the row.
        convertView.setTag( new PlanetViewHolder(textView,checkBox) );

        // If CheckBox is toggled, update the planet it is tagged with.
        checkBox.setOnClickListener( new View.OnClickListener() {
          public void onClick(View v) {
            CheckBox cb = (CheckBox) v ;
            Planet planet = (Planet) cb.getTag();
            planet.setChecked( cb.isChecked() );
          }
        });      
      }
      // Reuse existing row view
      else {
        // Because we use a ViewHolder, we avoid having to call findViewById().
        PlanetViewHolder viewHolder = (PlanetViewHolder) convertView.getTag();
        checkBox = viewHolder.getCheckBox() ;
        textView = viewHolder.getTextView() ;
      }

      // Tag the CheckBox with the Planet it is displaying, so that we can
      // access the planet in onClick() when the CheckBox is toggled.
      checkBox.setTag( planet );
     
      // Display planet data
      checkBox.setChecked( planet.isChecked() );
      textView.setText( planet.getName() );    
     
      return convertView;
    }
   
  }
 
  public Object onRetainNonConfigurationInstance() {
    return planets ;
  }
}


Click below link for download project
https://sites.google.com/site/httpnepstareblogspotin/listview-with-checkbox/Planets.zip?attredirects=0&d=1

Friday, 28 December 2012

Get Portion Of String from File Path in Java

import java.nio.file.*

Path fullPath = new File("/home/ubuntu/Documents/DesktopApplicationProject/JewlleryApplication/Jewellery Data/Ring/widget.jpg").toPath()

Path base = new File("/home/ubuntu/Documents/DesktopApplicationProject/JewlleryApplication").toPath()

String relativePath = base.relativize(fullPath).toString()

In Output you Get :

/Jewellery Data/Ring/widget.jpg.

Thursday, 1 November 2012

Marquee Effect Textview in Android


public class TextViewMarquee extends Activity {
    private TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView) this.findViewById(R.id.tv);
        tv.setSelected(true);  // Set focus to the textview
    }
}

In Xml file with Textview:::

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:id="@+id/mywidget"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:lines="1"
        android:ellipsize="marquee"
        android:fadingEdge="horizontal"
        android:marqueeRepeatLimit="marquee_forever"
        android:scrollHorizontally="true"
        android:textColor="#ff4500"
        android:text="Simple application that shows how to use marquee, with a long text" />
</RelativeLayout>