Pages

Thursday, 15 March 2012

Custom Content Provider


This will be useful for creating the own content provider. Follow the steps which has given below to create your own custom adapter. I thought that content provider and sqlite database are different. But what i thought is totally worng. The database can access only from that particular application. If you are creating the content provider which means creating URI for each row for the database. So from other application you can access tha database using the content provider URI. So both are inter related . You will understand if you follow the code.
Mimeprovider.java
package com.Androitanz.Provider;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;

/**
 * The provider creation,fetching and displaying
 *
 * @author Anitha
 *
 */
public class MimeProvider extends ContentProvider {
      /**
       * The instance sqlitedatabase
       */
      private SQLiteDatabase sqlDB;
      /**
       * The instance for DatabaseHelper
       */
      private DatabaseHelper dbHelper;
      /**
       * Database name for MIME app
       */
      private static final String DATABASE_NAME = "Friends.db";
      /**
       * Database version that we are using
       */

      private static final int DATABASE_VERSION = 1;
      /**
       * The table name using to store the information
       */

      private static final String TABLE_NAME = "Friends";

      private static final String TAG = "AndrointanZProvider";

      /**
       *
       * @author Lukshanu
       *
       */
      public static class ProviderDetails implements BaseColumns {
            public static final String AUTHORITY = "com.Androitanz.Provider.MimeProvider";

            // BaseColumn contains _id.

            public final static Uri CONTENT_URI = Uri
                        .parse("content://com.Androitanz.Provider.MimeProvider");

            // Table column
            public static final String FRIENDS_NAME = "FRIENDS_NAME";
      }

      private static class DatabaseHelper extends SQLiteOpenHelper {

            DatabaseHelper(Context context) {
                  super(context, DATABASE_NAME, null, DATABASE_VERSION);
            }

            @Override
            public void onCreate(SQLiteDatabase db) {
                  // create table to store user names
                  db.execSQL("Create table "
                              + TABLE_NAME
                              + "( _id INTEGER PRIMARY KEY AUTOINCREMENT, FRIENDS_NAME TEXT);");
            }

            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                  db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
                  onCreate(db);
            }
      }

      @Override
      public int delete(Uri uri, String selection, String[] selectionArgs) {
            // TODO Auto-generated method stub

            return 0;
      }

      @Override
      public String getType(Uri uri) {
            // TODO Auto-generated method stub
            return null;
      }

      @Override
      public Uri insert(Uri uri, ContentValues contentValues) {
            // get database to insert records
            sqlDB = dbHelper.getWritableDatabase();
            // insert record in user table and get the row number of recently
            long rowId = sqlDB.insert(TABLE_NAME, "", contentValues);
            if (rowId > 0) {
                  Uri rowUri = ContentUris.appendId(
                              ProviderDetails.CONTENT_URI.buildUpon(), rowId).build();
                  getContext().getContentResolver().notifyChange(rowUri, null);
                  return rowUri;
            }
            throw new SQLException("Failed to insert row into " + uri);
      }

      @Override
      public boolean onCreate() {
            dbHelper = new DatabaseHelper(getContext());
            return (dbHelper == null) ? false : true;
      }

      @Override
      public Cursor query(Uri uri, String[] projection, String selection,
                  String[] selectionArgs, String sortOrder) {
            SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
            SQLiteDatabase db = dbHelper.getReadableDatabase();
            qb.setTables(TABLE_NAME);
            Cursor c = qb.query(db, projection, selection, null, null, null,
                        sortOrder);
            c.setNotificationUri(getContext().getContentResolver(), uri);
            return c;
      }

      @Override
      public int update(Uri uri, ContentValues values, String selection,
                  String[] selectionArgs) {
            // TODO Auto-generated method stub
            return 0;
      }

}
The Activity to get the inputs and to store it in the content provider.
ContentDisplay.java
package com.Androitanz.Activity;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.Androitanz.Provider.MimeProvider.ProviderDetails;

/**
 * The Screen to fetch the name to store it in the provider and database
 *
 * @author Anitha
 *
 */
public class ContentDisplay extends Activity {
      private EditText mContactNameEditText;
      private TextView mContactsText;
      private Button mContactSaveButton;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            // Obtain handles to UI objects
            mContactNameEditText = (EditText) findViewById(R.id.contactNameEditText);
            mContactSaveButton = (Button) findViewById(R.id.contactSaveButton);
            mContactsText = (TextView) findViewById(R.id.contactEntryText);
            mContactSaveButton.setOnClickListener(new View.OnClickListener() {

                  @Override
                  public void onClick(View v) {
                        String name = mContactNameEditText.getText().toString();
                        insertRecord(name);
                        mContactsText.append("\n" + name);
                  }
            });

            displayRecords();
      }

      private void insertRecord(String userName) {
            ContentValues values = new ContentValues();
            values.put(ProviderDetails.FRIENDS_NAME, userName);
            getContentResolver().insert(ProviderDetails.CONTENT_URI, values);
      }

      private void displayRecords() {
            // An array specifying which columns to return.
            String columns[] = new String[] { ProviderDetails._ID,
                        ProviderDetails.FRIENDS_NAME };
            Uri myUri = ProviderDetails.CONTENT_URI;
            Cursor cur = managedQuery(myUri, columns, // Which columns to return
                        null, // WHERE clause; which rows to return(all rows)
                        null, // WHERE clause selection arguments (none)
                        null // Order-by clause (ascending by name)
            );
            if (cur.moveToFirst()) {
                  String id = null;
                  String userName = null;
                  do {
                        // Get the field values
                        id = cur.getString(cur.getColumnIndex(ProviderDetails._ID));
                        userName = cur.getString(cur
                                    .getColumnIndex(ProviderDetails.FRIENDS_NAME));
                        Toast.makeText(this, id + " " + userName, Toast.LENGTH_LONG)
                                    .show();
                  } while (cur.moveToNext());
            }
      }
}

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

        <TableRow>
            <TextView android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:text="contactNameLabel"/>
        </TableRow>
        <TableRow>
            <EditText android:id="@+id/contactNameEditText"
                      android:layout_height="wrap_content"
                      android:layout_width="wrap_content"
                      android:layout_weight="1"/>
        </TableRow>
        <TableRow>
            <Button android:layout_height="wrap_content"
                    android:text="save"
                    android:id="@+id/contactSaveButton"
                    android:layout_width="fill_parent"
                    android:layout_weight="1"/>
        </TableRow>
        <TableRow>
              <TextView android:text="@+id/contactEntryText"
                    android:id="@+id/contactEntryText"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"/>
             </TableRow>

    </TableLayout>
</ScrollView>
The things need to be mentioned in the manifest file are as follows. The provider tag should come within the application tag
<provider
    android:authorities="com.Androitanz.Provider.MimeProvider"
    android:multiprocess="true"
    android:name="com.Androitanz.Provider.MimeProvider"></provider>

Sunday, 11 December 2011

Make a Call in ANDROID

Here I am gonna share the make a call in android.Well i have assumed that you know some basics in android.

1Step: Give  the user permission in Manifest.xml
<user-permissions android:name="android.permission.CALL_PHONE"/>
2 Step: In your activity on create method create an instance for intent with the action of call.then parse your URI with the phone number. then start your activity. Here the code comes.

Intent intent=new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:999999999"));
startActivity(intent);

Tuesday, 15 November 2011

Blackberry conversion form jad file


Conversion jad to Cod file
I have got chance to work in the J2ME application. My work was to convert that application to blackberry application format. I have searched for that in many websites. But I found only few solution related to that. The solution which I got in the website was not working. Then I finally found one solution, very rare it is. I want to share it here. It will be useful at least for one person.
The following are the steps to be followed to convert the jad file of J2ME to cod file of  J2ME application which is for the blackberry in windows
1.         Download the Blackberry JDE.
2.         Install the blackberry JDE.exe (check for the folder C: program files->research in motion->blackeberry(version))
3.         Copy the J2ME jar and jad in Blackberry_projectname  folder and save it in any drive or desktop.
4.         Open JDE of blackberry . Click start --> All programs --> Research In Motion --> JDE
5.         Now Blackberry JDE is opened. click File --> New --> You will be having 3 tabs (Files , Projects , Work space) --> Workspace
6.         click browse and choose the location of Blackberry_projectName.
7.         Give the workspace name as projectname and click ok.
8.         So now projectname.jdw has generated. Right click on that projectname.jdw-> create new project in projectname .Choose the project name as projectname and click ok.
9.         Right click on the projectname-> propreties (You will be having 5 tabs General, Application,Resources, Compile ,Build) ->Application .
10.       Choose project type as MIDlet and projectname for the Name of the main MIDlet class .
11.       Right click on the projectname and build project
12.       projectname.cod will be there in the location of Blackberry_projectname.The another method to follow the conversion of jad file to cod file.
1.      So now you will have blackberry JDE in your system.
2.      Open the command prompt.
3.      Choose the path  as C:Program files/research In Motion/BlackBerry JDE 4.2.1/bin.
4.      Copy your jad file and jar file and paste it in the Program files/research In Motion/BlackBerry JDE 4.2.1/bin.
5.      Then give the command as rapc import= “C:Program Files/Research In Motion/Blackberry JDE 4.2.1/lib/net_rim_api.jar” codename=midletname-midlet jad=J2MEjadfilename.jad  J2MEjarfilename.jar
6.      Now the cod file will be generated in the Program files/research In Motion/BlackBerry JDE 4.2.1/bin path

                


Format your code


Well this will tell you to format the program automatically. As a developer everyone should follow the code with the neat format. Or else it won’t be nice to view. As a beginner I didn’t know this shortcut to format. Later I found the shortcut and method to format automatically for the program. I just want to share it here. It’s mainly for beginners .
Shorcut Way :
Press ESC in keyboard. On the right side of your monitor you can The option of Format .  Then press Enter . Its the shortcut. If you cant able to find Format  options on the right side then go for the following method.
Windows-> preferences -> Java (left side)->Editor ->Save action->perform the selected options on save (Tick the check box)->Format Source code (Tick the check box) -> Format all lines (Tick the check box)
Click apply and Ok.
Now your code will be formatted automatically. You can get the neat format of your codeJ