• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps EditText-> Button-> sqlite database

I'd prefer it if you included your code in here (and tagged it with a
Code:
 tag) instead of having us download the whole project[/QUOTE]


LastAndroid.java
[CODE]package last.Android;

import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;


public class LastAndroid extends TabActivity {
/** Called when the activity is first created. */

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

/** TabHost will have Tabs */
TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);

/** TabSpec used to create a new tab.
* By using TabSpec only we can able to setContent to the tab.
* By using TabSpec setIndicator() we can set name to tab. */

/** tid1 is firstTabSpec Id. Its used to access outside. */
TabSpec firstTabSpec = tabHost.newTabSpec("tid1");
TabSpec secondTabSpec = tabHost.newTabSpec("tid1");

/** TabSpec setIndicator() is used to set name for the tab. */
/** TabSpec setContent() is used to set content for a particular tab. */
firstTabSpec.setIndicator("Enter Data").setContent(new Intent(this,FirstTab.class));
secondTabSpec.setIndicator("Retrieve Data").setContent(new Intent(this,SecondTab.class));

/** Add tabSpec to the TabHost to display. */
tabHost.addTab(firstTabSpec);
tabHost.addTab(secondTabSpec);

}
}
DBHelper.java
Code:
package last.Android;

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.util.Log;


public class DBHelper {

  
    public static final String KEY_BODY = "body";
    public static final String KEY_ROWID = "_id";

    private static final String TAG = "NotesDbAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;

   
    private static final String DATABASE_CREATE =
        "create table notes (_id integer primary key autoincrement, "
        + "title text not null, body text not null);";

    private static final String DATABASE_NAME = "data";
    private static final String DATABASE_TABLE = "notes";
    private static final int DATABASE_VERSION = 2;

    private final Context mCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper {

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

        @Override
        public void onCreate(SQLiteDatabase db) {

            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS notes");
            onCreate(db);
        }
    }

 
    public DBHelper(Context ctx) {
        this.mCtx = ctx;
    }

 
    public DBHelper open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }


   
    public long createNote(String title, String body) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_BODY, body);

        return mDb.insert(DATABASE_TABLE, null, initialValues);
    }

 
    public boolean deleteNote(long rowId) {

        return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }

    public Cursor fetchAllNotes() {

        return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID,
                KEY_BODY}, null, null, null, null, null);
    }

  
    public Cursor fetchNote(long rowId) throws SQLException {

        Cursor mCursor =

            mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID
                    , KEY_BODY}, KEY_ROWID + "=" + rowId, null,
                    null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;

    }

  
    public boolean updateNote(long rowId, String title, String body) {
        ContentValues args = new ContentValues();

        args.put(KEY_BODY, body);

        return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
}
FirstTab.java
Code:
package last.Android;



import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View;
import android.widget.Button;


public class FirstTab extends Activity {
    private EditText mBodyText;
    private Long mRowId;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


         TextView textView = new TextView(this);
         textView.setText("First Tab");
         setContentView(R.layout.tab1);
         
         mBodyText = (EditText) findViewById(R.id.Data);

            Button confirmButton = (Button) findViewById(R.id.Enter_Data);

            mRowId = null;
            Bundle extras = getIntent().getExtras();
            if (extras != null) {
                String body = extras.getString(DBHelper.KEY_BODY);

                
                if (body != null) {
                    mBodyText.setText(body);
                }
            }

            confirmButton.setOnClickListener(new View.OnClickListener() {

                public void onClick(View view) {
                    Bundle bundle = new Bundle();

                    bundle.putString(DBHelper.KEY_BODY, mBodyText.getText().toString());
                    if (mRowId != null) {
                        bundle.putLong(DBHelper.KEY_ROWID, mRowId);
                    }

                    Intent mIntent = new Intent();
                    mIntent.putExtras(bundle);
                    setResult(RESULT_OK, mIntent);
                    finish();
                }

    });
    }
}
SecondTab.java
Code:
package last.Android;




import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;

import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import android.widget.AdapterView.AdapterContextMenuInfo;


public class SecondTab extends ListActivity {
/** Called when the activity is first created. */

    private static final int ACTIVITY_CREATE=0;
    private static final int ACTIVITY_EDIT=1;

    private static final int INSERT_ID = Menu.FIRST;
    private static final int DELETE_ID = Menu.FIRST + 1;

    private DBHelper mDbHelper;
    private Cursor mNotesCursor;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tab2);
        mDbHelper = new DBHelper(this);
        mDbHelper.open();
        fillData();
        registerForContextMenu(getListView());
    }

    private void fillData() {
        // Get all of the rows from the database and create the item list
        mNotesCursor = mDbHelper.fetchAllNotes();
        startManagingCursor(mNotesCursor);


        // and an array of the fields we want to bind those fields to (in this case just text1)
        int[] to = new int[]{R.id.text1};
        
        String[] from = new String[]{DBHelper.KEY_BODY};

        // Now create a simple cursor adapter and set it to display
        
        SimpleCursorAdapter notes = new SimpleCursorAdapter(this, R.layout.notes_row,
                mNotesCursor,from, to);
        setListAdapter(notes);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, INSERT_ID, 0, R.string.menu_insert);
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
            case INSERT_ID:
                createNote();
                return true;
        }

        return super.onMenuItemSelected(featureId, item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, DELETE_ID, 0, R.string.menu_delete);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case DELETE_ID:
                AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
                mDbHelper.deleteNote(info.id);
                fillData();
                return true;
        }
        return super.onContextItemSelected(item);
    }

    private void createNote() {
        Intent i = new Intent(this, FirstTab.class);
        startActivityForResult(i, ACTIVITY_CREATE);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        Cursor c = mNotesCursor;
        c.moveToPosition(position);
        Intent i = new Intent(this, FirstTab.class);
        i.putExtra(DBHelper.KEY_ROWID, id);
        i.putExtra(DBHelper.KEY_BODY, c.getString(
                c.getColumnIndexOrThrow(DBHelper.KEY_BODY)));
        startActivityForResult(i, ACTIVITY_EDIT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        Bundle extras = intent.getExtras();
        switch(requestCode) {
            case ACTIVITY_CREATE:
                String body = extras.getString(DBHelper.KEY_BODY);
                mDbHelper.createNote(body, body);
                fillData();
                break;
            case ACTIVITY_EDIT:
                Long rowId = extras.getLong(DBHelper.KEY_ROWID);
                if (rowId != null) {
                   
                    String editBody = extras.getString(DBHelper.KEY_BODY);
                    mDbHelper.updateNote(rowId,editBody, editBody);
                }
                fillData();
                break;
        }
    }
}
LAYOUTS
main
Code:
<?xml version="1.0" encoding="utf-8"?>

<TabHost android:layout_width="fill_parent"
android:layout_height="fill_parent" 
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost">

<LinearLayout android:id="@+id/LinearLayout01"
android:orientation="vertical" 
android:layout_height="fill_parent"
android:layout_width="fill_parent">

<TabWidget android:id="@android:id/tabs"
android:layout_height="wrap_content" 
android:layout_width="fill_parent"></TabWidget>

<FrameLayout android:id="@android:id/tabcontent"
android:layout_height="fill_parent" 
android:layout_width="fill_parent"></FrameLayout>
</LinearLayout>

</TabHost>
tab1
Code:
<?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:id="@+id/tab1Layout"
  android:orientation="vertical">
   
  <EditText
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text=""
  android:id="@+id/Data"></EditText>
  
   <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Save"
    android:id="@+id/Enter_Data"></Button>
  
</LinearLayout>
tab2
Code:
<?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">
  
  <Button
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Show Saved Data"
  android:id="@+id/Retrieve_Data"></Button>
  <ListView android:id="@+id/listView1" android:layout_height="match_parent" android:layout_width="wrap_content"></ListView>
</LinearLayout>
notes_row
Code:
<?xml version="1.0" encoding="utf-8"?>
<TextView android:id="@+id/text1" xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
AndroidManifest

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


    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".LastAndroid"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SecondTab" />
        <activity android:name=".FirstTab" />
    </application>
</manifest>
 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones