CS175
Chris Pollett
Oct. 6, 2014
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { setContentView(R.layout.main_portrait); } else { setContentView(R.layout.main_landscape); } //other code of onCreate }
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ImageView android:id ="@+id/my_photo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/myphoto" /> <TextView android:id="@+id/textView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="50" /> <SeekBar android:id="@+id/seekBar" android:layout_width="wrap_content" android:layout_height="wrap_content" style="@android:style/Widget.ProgressBar.Horizontal" android:max="100" android:layout_marginRight="5dp" /> <!-- Dummy LinearLayout to prevent EditText from immediately hogging focus --> <LinearLayout android:focusable="true" android:focusableInTouchMode="true" android:layout_width="0px" android:layout_height="0px" /> <EditText android:id="@+id/editText" android:layout_width="200px" android:layout_height="wrap_content" android:inputType="number" > </EditText> <CheckBox android:id="@+id/checkBox" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Disable Edit Text" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Toast Me" /> </LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ImageView android:id ="@+id/my_photo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/myphoto" /> <!-- notice the outer layout is horizontal and then we have a vertical one next to the image, this shows we are doing something different than the portrait layout case --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/textView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="50" /> <SeekBar android:id="@+id/seekBar" android:layout_width="wrap_content" android:layout_height="wrap_content" style="@android:style/Widget.ProgressBar.Horizontal" android:max="100" android:layout_marginRight="5dp" /> <!-- Dummy LinearLayout to prevent EditText from immediately hogging focus --> <LinearLayout android:focusable="true" android:focusableInTouchMode="true" android:layout_width="0px" android:layout_height="0px" /> <EditText android:id="@+id/editText" android:layout_width="200px" android:layout_height="wrap_content" android:inputType="number" > </EditText> <CheckBox android:id="@+id/checkBox" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Disable Edit Text" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Toast Me" /> </LinearLayout> </LinearLayout>
package org.pollett.rotationcontrols; import android.app.Activity; import android.content.res.Configuration; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.widget.CheckBox; import android.widget.EditText; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import android.widget.Toast; public class RotationActivity extends Activity implements OnKeyListener, OnClickListener, OnSeekBarChangeListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Here is where we detect orientation and switch between them if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { setContentView(R.layout.portrait_layout); } else { setContentView(R.layout.landscape_layout); } //Set programmatically the initial value of the TextView TextView textView = (TextView) this.findViewById( R.id.textView ); textView.setText("25"); /* To implement SeekBarChangeListener you have to implement three methods: onProgressChanged, onStartTrackingTouch, and onStopTrackingTouch We only care about the first */ SeekBar seekBar = (SeekBar) this.findViewById(R.id.seekBar); seekBar.setOnSeekBarChangeListener(this); seekBar.setProgress(25); //our key listener is used to get the keyboard to go away EditText editText = (EditText) this.findViewById( R.id.editText ); editText.setOnKeyListener(this); //Set up a listener to handle when the CheckBox is checked/unchecked CheckBox checkBox = (CheckBox)this.findViewById( R.id.checkBox ); checkBox.setOnClickListener(this); View clickMeButton = this.findViewById( R.id.button ); /* Clicking on the button displays a toast message. These messages can be useful for debugging. */ clickMeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText( getApplicationContext(), "This is an Informational Toast Message", Toast.LENGTH_LONG).show(); } }); } @Override /** The code below is used to get rid of the keyboard when entered clicked */ public boolean onKey(View v, int keyCode, KeyEvent event) { // If the event is a key-down event on the "enter" button if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { return true; } return false; } @Override /** Handles changes to the CheckBox. If checked we disable the EditText area; otherwise, we enable it @param v - view that event is coming from */ public void onClick(View v) { EditText editText = (EditText) this.findViewById( R.id.editText ); CheckBox checkBox = (CheckBox)this.findViewById( R.id.checkBox ); if(checkBox.isChecked()) { editText.setEnabled(false); TextView textView = (TextView) this.findViewById( R.id.textView ); textView.setText(editText.getText()); int num = Integer.parseInt(editText.getText().toString()); if(num > 100) { num = 100; } else if (num < 0) { num = 0; } SeekBar seekBar= (SeekBar) this.findViewById( R.id.seekBar) ; seekBar.setProgress(num); } else { editText.setEnabled(true); } } @Override /** Here where we handle SeekBar events. Changes to the SeekBar are converted to a number and displayed in the TextView */ public void onProgressChanged (SeekBar seekBar, int progress, boolean fromUser) { TextView textView = (TextView) this.findViewById( R.id.textView ); textView.setText("" + progress); } @Override public void onStartTrackingTouch (SeekBar seekBar) { } @Override public void onStopTrackingTouch (SeekBar seekBar) { } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
Since we are using a different activity name than the default, I thought I'd include this so that people remember they would need to modify it:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.pollett.rotationcontrols" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="20" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".RotationActivity" 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>
Which of the following is true?
Log.i("Hw1", "Main ViewCreated");
SharedPreferences myPref = getSharedPreferences("MY_APP_PREFS", Context.MODE_WORLD_WRITEABLE + Context.MODE_WORLD_READABLE); Log.i("My_Activity", "Old Some_Key" + myPref.getString("Some_Key","Key did not exist") ); //second arg is returned if key did not exist Editor myPrefEditor = myPref.edit(); myPrefEditor.putString("Some_Key", "Some Value"); myPrefEditor.commit();
~/Library/Application Support/iPhoneSimulator/User/
Window > Show View > Other... > Android > File Explorer.
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES); //look for Documents directories in user home folder //YES means expand tilde directories NSString *documentsDirectory = [paths objectAtIndex:0]; //Will only be one such dir so same //For temporary dir could have done //NSString *tempPath = NSTemporaryDirectory NSString *filename = [documentsDirectory stringByAppendingPathComponent:@"theFile.txt"]; if([[NSFileManager defaultManager] fileExistsAtPath:filename]) { NSArray *readArray = [[NSArray alloc] initWithContentsOfFile:filename]; NSLog(@"I read from the file: %@", [readArray objectAtIndex:0]); [readArray release]; } NSMutableArray *storeArray = [[NSMutableArray alloc] init]; [storeArray addObject:@"Some interesting Data"]; [storeArray writeToFile:filename atomically:YES ]; // writing such an array stores the data as XML much like a plist NSLog(@"I wrote some data"); [storeArray release];
File testFile = new File("data/data/org.pollett/files/filename.txt"); //another useful directory is /sdcard for the sd card in the device //if it exists. res/raw is also a useful directory for resource files FileInputStream fis = null; if(testFile.exists()) { try { fis = this.openFileInput("filename.txt"); byte[] reader = new byte[fis.available()]; while(fis.read(reader) != -1){} Log.i("AndroidPersistence", "I just read:\n" + new String(reader) ); } catch (IOException ie) { Log.e("AndroidPersistence", "File Read Error"); } finally { if(fis !=null) { try {fis.close();} catch(Exception e) {} } } }
FileOutputStream fos = null; try { fos = this.openFileOutput("filename.txt", Context.MODE_PRIVATE); fos.write("hi there\n".getBytes()); Log.i("AndroidPersistence", "I just wrote stuff\n"); } catch (IOException ie) { Log.e("AndroidPersistence", "File Write Error"); } finally { if(fos !=null) { try {fos.close();} catch(Exception e) {} } }
CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY, NAME TEXT, AGE INTEGER)
DROP TABLE IF EXISTS MY_TABLE
INSERT OR REPLACE INTO EMPLOYEE (ID, NAME, AGE) VALUES (5, 'Bob', 30)
DELETE FROM tablename WHERE condAn example condition might be age: > 25
SELECT col_name1, col_name2, ..., col_name_n /*to empahsize what table do: table_name.col_name */ FROM table_name_1, table_name_2, ..., table_name_m WHERE condan example condition might be: EMPLOYEE.ID = PROJECT.directorID AND PROJECT.budget = 1000000
sqlite3 *database; int result = sqlite3_open("/path/to/database", &database);
char *cStringPath = [someStringObj UTF8String];
sqlite3_close(database);
char *errorMsg; const char *createSQL ="CREATE TABLE IF NOT EXISTS PEOPLE (ID INTEGER PRIMARY KEY, HOBBY TEXT)"; int result = sqlite3_exec(database, createSQL, NULL, NULL, &errorMsg);
NSString *query = @"SELECT * FROM PEOPLE"; sqlite3_stmt *statement; int result = sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil); //could check if result is SQLITE_OK while(sqlite3_step(statement) == SQLITE_ROW){ // for the current row let's get out some columns int id = sqlite3_column_int(statement, 0); //0th column's data char *hobby = (char*)sqlite3_column_text(statement, 1); // do something with the data for this row } sqlite3_finalize(statement);
import android.database.sqlite.*; import android.database.*; import android.content.*; import android.util.*;
dbOpenHelper = new DBOpenHelper(this, "My_Database", 3); db = dbOpenHelper.getWritableDatabase(); //insert into database db.execSQL("INSERT OR REPLACE INTO PEOPLE VALUES (5, 'test')"); db.close(); dbOpenHelper = new DBOpenHelper(this, "My_Database", 3); db = dbOpenHelper.getReadableDatabase(); Cursor c = db.rawQuery("SELECT * FROM PEOPLE", null); for(int i=0; i< c.getCount(); i++) { c.moveToNext(); Log.i("SqliteAndroid", "Id="+c.getInt(0)); Log.i("SqliteAndroid", "Hobby="+c.getString(1)); } db.close();
private static class DBOpenHelper extends SQLiteOpenHelper { public DBOpenHelper(Context context, String dbName, int version ) { // third argument id to a cursor factory -- we don't care about super(context, dbName, null, version); } @Override public void onCreate(SQLiteDatabase db) { try { db.execSQL("CREATE TABLE IF NOT EXISTS PEOPLE (ID INTEGER PRIMARY KEY, HOBBY TEXT)"); } catch(SQLException e) { Log.e("SqliteAndroid", "DBOpenHelper", e); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS PEOPLE"); this.onCreate(db); } }