Sunday, April 6, 2014

Eclipse ADT (Build v22.2.1 for Mac OS) Pointers

When you create a new app from scratch (file->new->Android Application Project) and select the defaults, it automatically opens the java file (from the src folder) for editing, and the main xml file (from the res->layout folder) for editing. The xml file has two panes, text and graphical layout. Start with the graphical layout to drag and drop objects like fields and buttons onto your UI. Then edit the xml text and the java file to handle events with the objects. The YouTube tutorials on this, called "Android: project 1(v1)", up to (v6), by "Lecture Snippets" are very efficient and provide simple java code for this. The YouTube tutorial "Android Basic SQLite Database" by "profgustin" gives some basic SQLite code, which I have enhanced below to interact with a field from Lecture Snippets. The main thing not to forget is: although SQLite is "built-in" to the Android Developer Tools SDK, the new app cannot use the classes until they are imported in the java code AND attached to the build path. I found that typing SQLiteDatabase in the java code, and either hovering over it or double clicking on it brought up a dialog box that allowed me to both make the import statement in the code, and add the android.jar file as a Source Attachment in the Java Build Path (this is otherwise found by right-clicking the project file in the navigator pane-> Properties->Java Build Class->Android. I use the Cursor class to manipulate SQL data, so I also had to import android.database.Cursor; as well. I think import android.database.*; may also work. package com.example.foo2; import android.os.Bundle; import android.app.Activity; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.view.*; import android.widget.*; public class MainActivity extends Activity { Button btn1; EditText etxt1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SQLiteDatabase db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null); db.execSQL("CREATE TABLE IF NOT EXISTS MyTable (field1 VARCHAR, field2 VARCHAR, field3 VARCHAR);"); db.execSQL("INSERT INTO MyTable VALUES('red','green','blue');"); Cursor c = db.rawQuery("SELECT field1 FROM MyTable", null); c.moveToFirst(); final String MyString = c.getString(c.getColumnIndex("field1")); db.close(); btn1=(Button)findViewById(R.id.button1); etxt1=(EditText)findViewById(R.id.editText1); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etxt1.setText(MyString); } }); }