ようやっとX220でWindows10を本格稼働させ始めました。
いつもはThinkVantageのユーティリティを入れてトラックポイントやバッテリーなどを使うのですが、Windows10を半クリーンインストールしたところ、特にその辺を入れなくてもそれっぽく動いているようなのでそのまま使ってみています。
タッチパッドの使い勝手はちょっと違和感があったのでマウスの調整を見ていたところWindows8.1っぽくなったのでその辺を...
1. 設定 -> マウスとタッチパッド -> その他のマウスオプション
2. マウスのプロパティに"ThinkPad"がある!のでそのタブをクリックして"設定"ボタン
3. Synapticsコントロールパネル(!)が開くので"スクロール"タブを選択
4. "1本指エッジスクロール"の中の"カイラル円形スクロール"をチェック > これでくるくるスクロールができるようになる
5. が、速度が遅いので、上のほうの"スクロール速度"を最速の1つ前くらいに
これで使いやすくなりました...が、この辺までwindows updateでinstallされるのか!?、あるいは今回のインストールの特性上(8.1を入れてから明示的にクリーンインストールしたような)一部残っているのか...と思ったが、USBメモリからクリーンインストールしたので前者で判別して入れてくれているのか...
昨年のGシリーズのスパイウェア騒動以来、良いイメージが無いのでMSからの配信の方が安心出来そうですね(それも大元はメーカー製のものなのだけど)
2016年4月21日木曜日
2016年4月20日水曜日
Android Studio 2.0 install
解説サイトを参考にしてinstallしました。
- installはadminで実施
- 起動は一般ユーザ
で大丈夫の模様
haxがinstallされなかったようなのでSDK managerから実施
初回のエミュレータ起動時に"haxがinstallされていない"と出たのでメッセージ下のinstallをクリックすると"install done"と表示される(のに相変わらずinstallされていない表示)
そのまま進めるとlogでは"hax enable"と出ているので大丈夫の模様
defaultの状態ではSDKは最新版(mashmallow対応)のようだが、minimum SDKではkitkat等も指定できるので、とりあえず変更せずに様子見する事にする
emulater imageはmashmallowで入っているが、"Nexus Sでmashmallow"なVirtual Deviceを作成してとりあえずビルド -> 実行できる事が確認できている
(DLに時間がかかるので様子見してからKitKatやlollipopのemulaterのemulaterを入れようかなと...)
とりあえずしばらくこれで使ってみます。
- installはadminで実施
- 起動は一般ユーザ
で大丈夫の模様
haxがinstallされなかったようなのでSDK managerから実施
初回のエミュレータ起動時に"haxがinstallされていない"と出たのでメッセージ下のinstallをクリックすると"install done"と表示される(のに相変わらずinstallされていない表示)
そのまま進めるとlogでは"hax enable"と出ているので大丈夫の模様
defaultの状態ではSDKは最新版(mashmallow対応)のようだが、minimum SDKではkitkat等も指定できるので、とりあえず変更せずに様子見する事にする
emulater imageはmashmallowで入っているが、"Nexus Sでmashmallow"なVirtual Deviceを作成してとりあえずビルド -> 実行できる事が確認できている
(DLに時間がかかるので様子見してからKitKatやlollipopのemulaterのemulaterを入れようかなと...)
とりあえずしばらくこれで使ってみます。
2016年4月10日日曜日
ストレージにファイルを保存する(内部ストレージ)
外部ストレージに保存する場合はmanifest fileへの記載が必要みたいだけど、内部ストレージなら不要のようだ
1. activity_main.xml (前回の使いまわし)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText_dataText"
android:layout_weight="1.04"
android:text="good morning" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="@+id/button_save"
android:onClick="onButtonSaveClick" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load"
android:id="@+id/button_load"
android:onClick="onButtonLoadClick" />
</LinearLayout>
<!-- 読み込み用 -->
<TextView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:id="@+id/labelList"
/>
</LinearLayout>
2. MainActivity.java
package com.example.training.filelocaloperation;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class MainActivity extends Activity {
TextView tv;
String LOCAL_FILE = "test.text";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.editText_dataText);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onButtonSaveClick(View v){
String text = tv.getText().toString();
Toast.makeText(MainActivity.this, new StringBuilder().append("Saveクリックした").append(text).toString(), Toast.LENGTH_SHORT).show();
OutputStream out;
try {
// out = openFileOutput(LOCAL_FILE,MODE_APPEND); // 追記
out = openFileOutput(LOCAL_FILE, Context.MODE_PRIVATE); // 上書き
PrintWriter writer = new PrintWriter(new OutputStreamWriter(out,"UTF-8"));
writer.append(text);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
// tv.setText("Saveクリック");
}
public void onButtonLoadClick(View v){
Toast.makeText(MainActivity.this, "Loadクリックした", Toast.LENGTH_SHORT).show();
// tv.setText("Loadクリック");
StringBuilder text = new StringBuilder();
InputStream inputStream;
String lineBuffer = null;
try {
inputStream = openFileInput(LOCAL_FILE);
BufferedReader reader= new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
while( (lineBuffer = reader.readLine()) != null ){
text.append(lineBuffer);
Log.d("FileAccess", lineBuffer);
}
} catch (IOException e) {
e.printStackTrace();
}
TextView lblList = (TextView)this.findViewById(R.id.labelList);
lblList.setText(text);
}
}
1. activity_main.xml (前回の使いまわし)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText_dataText"
android:layout_weight="1.04"
android:text="good morning" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="@+id/button_save"
android:onClick="onButtonSaveClick" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load"
android:id="@+id/button_load"
android:onClick="onButtonLoadClick" />
</LinearLayout>
<!-- 読み込み用 -->
<TextView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:id="@+id/labelList"
/>
</LinearLayout>
2. MainActivity.java
package com.example.training.filelocaloperation;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class MainActivity extends Activity {
TextView tv;
String LOCAL_FILE = "test.text";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.editText_dataText);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onButtonSaveClick(View v){
String text = tv.getText().toString();
Toast.makeText(MainActivity.this, new StringBuilder().append("Saveクリックした").append(text).toString(), Toast.LENGTH_SHORT).show();
OutputStream out;
try {
// out = openFileOutput(LOCAL_FILE,MODE_APPEND); // 追記
out = openFileOutput(LOCAL_FILE, Context.MODE_PRIVATE); // 上書き
PrintWriter writer = new PrintWriter(new OutputStreamWriter(out,"UTF-8"));
writer.append(text);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
// tv.setText("Saveクリック");
}
public void onButtonLoadClick(View v){
Toast.makeText(MainActivity.this, "Loadクリックした", Toast.LENGTH_SHORT).show();
// tv.setText("Loadクリック");
StringBuilder text = new StringBuilder();
InputStream inputStream;
String lineBuffer = null;
try {
inputStream = openFileInput(LOCAL_FILE);
BufferedReader reader= new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
while( (lineBuffer = reader.readLine()) != null ){
text.append(lineBuffer);
Log.d("FileAccess", lineBuffer);
}
} catch (IOException e) {
e.printStackTrace();
}
TextView lblList = (TextView)this.findViewById(R.id.labelList);
lblList.setText(text);
}
}
Sqliteを使ってみる(queryによる読み出し追加)
保存したデータを読み取ってみます
結果は、listで表示します
1.activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText_dataText"
android:layout_weight="1.04"
android:text="good morning" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="@+id/button_save"
android:onClick="onButtonSaveClick" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load"
android:id="@+id/button_load"
android:onClick="onButtonLoadClick" />
</LinearLayout>
<!-- 読み込み用 -->
<TextView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:id="@+id/labelList"
/>
</LinearLayout>
2. FeedReadeerContract.java クラスを新規作成
package com.example.training.sqldatasave;
import android.provider.BaseColumns;
/**
* Created by on 2016/04/02.
*/
public final class FeedReaderContract {
// To prevent someone from accidentally instantiating the contract class,
// give it an empty constructor.
public FeedReaderContract() {}
/* Inner class that defines the table contents */
public static abstract class FeedEntry implements BaseColumns {
public static final String TABLE_NAME = "entry";
public static final String COLUMN_NAME_ENTRY_ID = "entryid";
public static final String COLUMN_NAME_TITLE = "title";
public static final String COLUMN_NAME_CONTENT = "content";
}
}
3. FeedReaderDbHelper.javaを新規作成
package com.example.training.sqldatasave;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.example.training.sqldatasave.FeedReaderContract.FeedEntry;
/**
* Created by 2016/04/02.
*/
public class FeedReaderDbHelper extends SQLiteOpenHelper {
private static final String TEXT_TYPE = " TEXT";
private static final String COMMA_SEP = ",";
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + FeedEntry.TABLE_NAME + " (" +
FeedEntry._ID + " INTEGER PRIMARY KEY," +
FeedEntry.COLUMN_NAME_ENTRY_ID + TEXT_TYPE + COMMA_SEP +
FeedEntry.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP +
FeedEntry.COLUMN_NAME_CONTENT + TEXT_TYPE +
" )";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + FeedEntry.TABLE_NAME;
// If you change the database schema, you must increment the database version.
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "FeedReader.db";
public FeedReaderDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
public void insertDb(SQLiteDatabase db, int id, String title, String content){
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_ENTRY_ID, id);
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
values.put(FeedEntry.COLUMN_NAME_CONTENT, content);
// Insert the new row, returning the primary key value of the new row
long newRowId;
newRowId = db.insert(
FeedEntry.TABLE_NAME,
null, //FeedEntry.COLUMN_NAME_NULLABLE, // "COLUMN_NAME_NULLABLE"は認識されないみたい
values);
if(newRowId < 0){
Log.e("sample", "insertDbでエラー発生");
}
}
}
4. MainActivity.javaはこんな感じに
package com.example.training.sqldatasave;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteAbortException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.example.training.sqldatasave.FeedReaderContract.FeedEntry;
public class MainActivity extends Activity {
TextView tv;
/*
DatabaseHelper mDbHelper;
SQLiteDatabase mDb;
*/
FeedReaderDbHelper feedReaderDbHelper;
SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.editText_dataText);
// mDbHelper = new DatabaseHelper(this);
// mDb = mDbHelper.getWritableDatabase();
feedReaderDbHelper = new FeedReaderDbHelper(this);
db = feedReaderDbHelper.getWritableDatabase();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onButtonSaveClick(View v){
Toast.makeText(MainActivity.this, "Saveクリックした", Toast.LENGTH_SHORT).show();
// mDbHelper.insert(mDb, 1, tv.getText().toString(), 0);
feedReaderDbHelper.insertDb(db, 1, "title1", tv.getText().toString());
tv.setText("Saveクリック");
}
public void onButtonLoadClick(View v){
Toast.makeText(MainActivity.this, "Loadクリックした", Toast.LENGTH_SHORT).show();
tv.setText("Loadクリック");
StringBuilder text = new StringBuilder();
SQLiteDatabase db = feedReaderDbHelper.getReadableDatabase();
try {
Cursor cursor = db.query(FeedEntry.TABLE_NAME, // table
new String[]{FeedEntry.COLUMN_NAME_ENTRY_ID, FeedEntry.COLUMN_NAME_TITLE, FeedEntry.COLUMN_NAME_CONTENT}, // cols
null, // selection
null, // selection args
null, // group by
null, // having
"_id DESC" // "_id ASC" // order by(_idをDESCで降順指定) );
cursor.moveToFirst();
do {
text.append("," + cursor.getString(1));
text.append("," + cursor.getString(2));
// text.append("," + cursor.getString(3));
text.append("\n");
} while (cursor.moveToNext());
} catch (SQLiteAbortException e){
Toast.makeText(MainActivity.this, "SQL Exception発生", Toast.LENGTH_SHORT).show();
} finally {
}
TextView lblList = (TextView)this.findViewById(R.id.labelList);
lblList.setText(text);
}
}
結果は、listで表示します
1.activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText_dataText"
android:layout_weight="1.04"
android:text="good morning" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="@+id/button_save"
android:onClick="onButtonSaveClick" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load"
android:id="@+id/button_load"
android:onClick="onButtonLoadClick" />
</LinearLayout>
<!-- 読み込み用 -->
<TextView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:id="@+id/labelList"
/>
</LinearLayout>
2. FeedReadeerContract.java クラスを新規作成
package com.example.training.sqldatasave;
import android.provider.BaseColumns;
/**
* Created by on 2016/04/02.
*/
public final class FeedReaderContract {
// To prevent someone from accidentally instantiating the contract class,
// give it an empty constructor.
public FeedReaderContract() {}
/* Inner class that defines the table contents */
public static abstract class FeedEntry implements BaseColumns {
public static final String TABLE_NAME = "entry";
public static final String COLUMN_NAME_ENTRY_ID = "entryid";
public static final String COLUMN_NAME_TITLE = "title";
public static final String COLUMN_NAME_CONTENT = "content";
}
}
3. FeedReaderDbHelper.javaを新規作成
package com.example.training.sqldatasave;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.example.training.sqldatasave.FeedReaderContract.FeedEntry;
/**
* Created by 2016/04/02.
*/
public class FeedReaderDbHelper extends SQLiteOpenHelper {
private static final String TEXT_TYPE = " TEXT";
private static final String COMMA_SEP = ",";
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + FeedEntry.TABLE_NAME + " (" +
FeedEntry._ID + " INTEGER PRIMARY KEY," +
FeedEntry.COLUMN_NAME_ENTRY_ID + TEXT_TYPE + COMMA_SEP +
FeedEntry.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP +
FeedEntry.COLUMN_NAME_CONTENT + TEXT_TYPE +
" )";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + FeedEntry.TABLE_NAME;
// If you change the database schema, you must increment the database version.
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "FeedReader.db";
public FeedReaderDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
public void insertDb(SQLiteDatabase db, int id, String title, String content){
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_ENTRY_ID, id);
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
values.put(FeedEntry.COLUMN_NAME_CONTENT, content);
// Insert the new row, returning the primary key value of the new row
long newRowId;
newRowId = db.insert(
FeedEntry.TABLE_NAME,
null, //FeedEntry.COLUMN_NAME_NULLABLE, // "COLUMN_NAME_NULLABLE"は認識されないみたい
values);
if(newRowId < 0){
Log.e("sample", "insertDbでエラー発生");
}
}
}
4. MainActivity.javaはこんな感じに
package com.example.training.sqldatasave;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteAbortException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.example.training.sqldatasave.FeedReaderContract.FeedEntry;
public class MainActivity extends Activity {
TextView tv;
/*
DatabaseHelper mDbHelper;
SQLiteDatabase mDb;
*/
FeedReaderDbHelper feedReaderDbHelper;
SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.editText_dataText);
// mDbHelper = new DatabaseHelper(this);
// mDb = mDbHelper.getWritableDatabase();
feedReaderDbHelper = new FeedReaderDbHelper(this);
db = feedReaderDbHelper.getWritableDatabase();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onButtonSaveClick(View v){
Toast.makeText(MainActivity.this, "Saveクリックした", Toast.LENGTH_SHORT).show();
// mDbHelper.insert(mDb, 1, tv.getText().toString(), 0);
feedReaderDbHelper.insertDb(db, 1, "title1", tv.getText().toString());
tv.setText("Saveクリック");
}
public void onButtonLoadClick(View v){
Toast.makeText(MainActivity.this, "Loadクリックした", Toast.LENGTH_SHORT).show();
tv.setText("Loadクリック");
StringBuilder text = new StringBuilder();
SQLiteDatabase db = feedReaderDbHelper.getReadableDatabase();
try {
Cursor cursor = db.query(FeedEntry.TABLE_NAME, // table
new String[]{FeedEntry.COLUMN_NAME_ENTRY_ID, FeedEntry.COLUMN_NAME_TITLE, FeedEntry.COLUMN_NAME_CONTENT}, // cols
null, // selection
null, // selection args
null, // group by
null, // having
"_id DESC" // "_id ASC" // order by(_idをDESCで降順指定) );
cursor.moveToFirst();
do {
text.append("," + cursor.getString(1));
text.append("," + cursor.getString(2));
// text.append("," + cursor.getString(3));
text.append("\n");
} while (cursor.moveToNext());
} catch (SQLiteAbortException e){
Toast.makeText(MainActivity.this, "SQL Exception発生", Toast.LENGTH_SHORT).show();
} finally {
}
TextView lblList = (TextView)this.findViewById(R.id.labelList);
lblList.setText(text);
}
}
2016年4月4日月曜日
Sqliteを使ってみる
developerの情報からコーディングしてみます。
1. activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText_dataText"
android:layout_weight="1.04" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="@+id/button_save"
android:onClick="onButtonSaveClick" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load"
android:id="@+id/button_load"
android:onClick="onButtonLoadClick" />
</LinearLayout>
</LinearLayout>
2. FeedReadeerContract.java クラスを新規作成
package com.example.training.sqldatasave;
import android.provider.BaseColumns;
/**
* Created by on 2016/04/02.
*/
public final class FeedReaderContract {
// To prevent someone from accidentally instantiating the contract class,
// give it an empty constructor.
public FeedReaderContract() {}
/* Inner class that defines the table contents */
public static abstract class FeedEntry implements BaseColumns {
public static final String TABLE_NAME = "entry";
public static final String COLUMN_NAME_ENTRY_ID = "entryid";
public static final String COLUMN_NAME_TITLE = "title";
public static final String COLUMN_NAME_CONTENT = "content";
}
}
3. FeedReaderDbHelper.javaを新規作成
package com.example.training.sqldatasave;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.example.training.sqldatasave.FeedReaderContract.FeedEntry;
/**
* Created by 2016/04/02.
*/
public class FeedReaderDbHelper extends SQLiteOpenHelper {
private static final String TEXT_TYPE = " TEXT";
private static final String COMMA_SEP = ",";
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + FeedEntry.TABLE_NAME + " (" +
FeedEntry._ID + " INTEGER PRIMARY KEY," +
FeedEntry.COLUMN_NAME_ENTRY_ID + TEXT_TYPE + COMMA_SEP +
FeedEntry.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP +
FeedEntry.COLUMN_NAME_CONTENT + TEXT_TYPE +
" )";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + FeedEntry.TABLE_NAME;
// If you change the database schema, you must increment the database version.
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "FeedReader.db";
public FeedReaderDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
public void insertDb(SQLiteDatabase db, int id, String title, String content){
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_ENTRY_ID, id);
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
values.put(FeedEntry.COLUMN_NAME_CONTENT, content);
// Insert the new row, returning the primary key value of the new row
long newRowId;
newRowId = db.insert(
FeedEntry.TABLE_NAME,
null, //FeedEntry.COLUMN_NAME_NULLABLE, // "COLUMN_NAME_NULLABLE"は認識されないみたい
values);
if(newRowId < 0){
Log.e("sample", "insertDbでエラー発生");
}
}
}
4. MainActivity.javaはこんな感じに
package com.example.training.sqldatasave;
import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView tv;
/*
DatabaseHelper mDbHelper;
SQLiteDatabase mDb;
*/
FeedReaderDbHelper feedReaderDbHelper;
SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.editText_dataText);
// mDbHelper = new DatabaseHelper(this);
// mDb = mDbHelper.getWritableDatabase();
feedReaderDbHelper = new FeedReaderDbHelper(this);
db = feedReaderDbHelper.getWritableDatabase();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onButtonSaveClick(View v){
Toast.makeText(MainActivity.this, "Saveクリックした", Toast.LENGTH_SHORT).show();
feedReaderDbHelper.insertDb(db, 1, "title1", tv.getText().toString());
tv.setText("Saveクリック");
}
// 使わないけど一応
public void onButtonLoadClick(View v){
Toast.makeText(MainActivity.this, "Loadクリックした", Toast.LENGTH_SHORT).show();
tv.setText("Loadクリック");
}
}
1. activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText_dataText"
android:layout_weight="1.04" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="@+id/button_save"
android:onClick="onButtonSaveClick" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load"
android:id="@+id/button_load"
android:onClick="onButtonLoadClick" />
</LinearLayout>
</LinearLayout>
2. FeedReadeerContract.java クラスを新規作成
package com.example.training.sqldatasave;
import android.provider.BaseColumns;
/**
* Created by on 2016/04/02.
*/
public final class FeedReaderContract {
// To prevent someone from accidentally instantiating the contract class,
// give it an empty constructor.
public FeedReaderContract() {}
/* Inner class that defines the table contents */
public static abstract class FeedEntry implements BaseColumns {
public static final String TABLE_NAME = "entry";
public static final String COLUMN_NAME_ENTRY_ID = "entryid";
public static final String COLUMN_NAME_TITLE = "title";
public static final String COLUMN_NAME_CONTENT = "content";
}
}
3. FeedReaderDbHelper.javaを新規作成
package com.example.training.sqldatasave;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.example.training.sqldatasave.FeedReaderContract.FeedEntry;
/**
* Created by 2016/04/02.
*/
public class FeedReaderDbHelper extends SQLiteOpenHelper {
private static final String TEXT_TYPE = " TEXT";
private static final String COMMA_SEP = ",";
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + FeedEntry.TABLE_NAME + " (" +
FeedEntry._ID + " INTEGER PRIMARY KEY," +
FeedEntry.COLUMN_NAME_ENTRY_ID + TEXT_TYPE + COMMA_SEP +
FeedEntry.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP +
FeedEntry.COLUMN_NAME_CONTENT + TEXT_TYPE +
" )";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + FeedEntry.TABLE_NAME;
// If you change the database schema, you must increment the database version.
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "FeedReader.db";
public FeedReaderDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
public void insertDb(SQLiteDatabase db, int id, String title, String content){
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_ENTRY_ID, id);
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
values.put(FeedEntry.COLUMN_NAME_CONTENT, content);
// Insert the new row, returning the primary key value of the new row
long newRowId;
newRowId = db.insert(
FeedEntry.TABLE_NAME,
null, //FeedEntry.COLUMN_NAME_NULLABLE, // "COLUMN_NAME_NULLABLE"は認識されないみたい
values);
if(newRowId < 0){
Log.e("sample", "insertDbでエラー発生");
}
}
}
4. MainActivity.javaはこんな感じに
package com.example.training.sqldatasave;
import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView tv;
/*
DatabaseHelper mDbHelper;
SQLiteDatabase mDb;
*/
FeedReaderDbHelper feedReaderDbHelper;
SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.editText_dataText);
// mDbHelper = new DatabaseHelper(this);
// mDb = mDbHelper.getWritableDatabase();
feedReaderDbHelper = new FeedReaderDbHelper(this);
db = feedReaderDbHelper.getWritableDatabase();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onButtonSaveClick(View v){
Toast.makeText(MainActivity.this, "Saveクリックした", Toast.LENGTH_SHORT).show();
feedReaderDbHelper.insertDb(db, 1, "title1", tv.getText().toString());
tv.setText("Saveクリック");
}
// 使わないけど一応
public void onButtonLoadClick(View v){
Toast.makeText(MainActivity.this, "Loadクリックした", Toast.LENGTH_SHORT).show();
tv.setText("Loadクリック");
}
}
登録:
投稿 (Atom)