< Previous                Next >

 

[Android]Sending View to Back or Front

[日本語]

 

I will introduce how to change stacking order of view as below picture.

 

Environment : Android Studio 2.2.1, API 19

 

In the case of Android, remove view from layout and set view to layout again.

Then index is set 0 and view move to back. Index is not set and view move to front.

 

Example

package net.studioks.sample1;

 

import android.app.Activity;

import android.graphics.Color;

import android.graphics.drawable.GradientDrawable;

import android.os.Bundle;

import android.view.Gravity;

import android.view.View;

import android.widget.Button;

import android.widget.RelativeLayout;

import android.widget.TextView;

import static android.support.v7.widget.ListPopupWindow.WRAP_CONTENT;

 

public class sample1 extends Activity implements View.OnClickListener {

  private TextView textView1;

  private TextView textView2;

  private Button button1;

  private Button button2;

  RelativeLayout relativeLayout;

 

  @Override

  public void onCreate(Bundle bundle){

    super.onCreate(bundle);

    relativeLayout = new RelativeLayout(this);

    setContentView(relativeLayout);

 

    textView1 = new TextView(this);

    textView1.setText("Text1");

    GradientDrawable gradient_textView1 = new GradientDrawable();

    gradient_textView1.setColor(Color.BLUE);

    textView1.setBackground(gradient_textView1);

    RelativeLayout.LayoutParams param_textView1 = new RelativeLayout.LayoutParams(300, 300);

    param_textView1.leftMargin = 0;

    param_textView1.topMargin = 0;

    param_textView1.addRule(RelativeLayout.ALIGN_TOP);

    relativeLayout.addView(textView1,param_textView1);

 

    textView2 = new TextView(this);

    textView2.setText("Text2");

    GradientDrawable gradient_textView2 = new GradientDrawable();

    gradient_textView2.setColor(Color.YELLOW);

    textView2.setBackground(gradient_textView2);

    RelativeLayout.LayoutParams param_textView2 = new RelativeLayout.LayoutParams(300, 300);

    param_textView2.leftMargin = 50;

    param_textView2.topMargin = 50;

    param_textView2.addRule(RelativeLayout.ALIGN_TOP);

    relativeLayout.addView(textView2,param_textView2);

 

    button1 = new Button(this);

    button1.setId(1);

    button1.setText("Send Label1 to Back");

    button1.setGravity(Gravity.CENTER);

    button1.setPadding(0,0,0,0);

    button1.setTextColor(Color.WHITE);

    button1.setOnClickListener(this);

    GradientDrawable gradient_button1 = new GradientDrawable();

    gradient_button1.setColor(Color.BLUE);

    button1.setBackground(gradient_button1);

    RelativeLayout.LayoutParams param_button1 = new RelativeLayout.LayoutParams(200, 50);

    param_button1.leftMargin = 0;

    param_button1.topMargin = 400;

    param_button1.addRule(RelativeLayout.ALIGN_TOP);

    relativeLayout.addView(button1,param_button1);

 

    button2 = new Button(this);

    button2.setId(2);

    button2.setGravity(Gravity.CENTER);

    button2.setPadding(0,0,0,0);

    button2.setText("Send Label1 to Front");

    button2.setTextColor(Color.WHITE);

    button2.setOnClickListener(this);

    GradientDrawable gradient_button2 = new GradientDrawable();

    gradient_button2.setColor(Color.RED);

    button2.setBackground(gradient_button2);

    RelativeLayout.LayoutParams param_button2 = new RelativeLayout.LayoutParams(200, 50);

    param_button2.leftMargin = 210;

    param_button2.topMargin = 400;

    param_button2.addRule(RelativeLayout.ALIGN_TOP);

    relativeLayout.addView(button2,param_button2);

  }

 

  public void onClick(View v) {

    switch (v.getId()){

      case 1:

        //To Back

        relativeLayout.removeView(textView1);

        relativeLayout.addView(textView1,0);

        break;

      case 2:

        //To Front

        relativeLayout.removeView(textView1);

        relativeLayout.addView(textView1);

        break;

    }

  }

}

[Andorid]How to capture screen

[日本語]

 

I introduce how to capture screen on Android this time.

 

環境:Android Studio 2.2.1, API 19

 

You can capture screen every views on Android.

At first, use setDrawingCacheEnabled(true) and getDrawingCache, and you can get view's capture.

 

And you must use setDrawingCacheEnabled(false) after getting view's capture.

private View view1;

・・・・・・・・・・・・・・・・・

view1.setDrawingCacheEnabled(true);

Bitmap bmp = Bitmap.createBitmap(view1.getDrawingCache());

view1.setDrawingCacheEnabled(false);

 

Sample code is below.

package net.studioks.sample1;

 

import android.app.Activity;

import android.graphics.Bitmap;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.ImageView;

import android.widget.RelativeLayout;

import android.widget.TextView;

 

public class sample1 extends Activity {

  private TextView textView1;

  private ImageView imageView1;

  private Button button1;

 

  RelativeLayout relativeLayout;

 

  @Override

  public void onCreate(Bundle bundle) {

    super.onCreate(bundle);

    relativeLayout = new RelativeLayout(this);

    setContentView(relativeLayout);

 

    textView1.setText("Test");

    RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(200,100);

    params1.leftMargin = 10;

    params1.topMargin = 0;

    relativeLayout.addView(textView1,params1);

 

    imageView1.setScaleType(ImageView.ScaleType.FIT_XY);

    RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(400,400);

    params2.leftMargin = 10;

    params2.topMargin = 110;

    relativeLayout.addView(imageView1,params2);

 

    button1.setText("Get Image");

    button1.setOnClickListener(new View.OnClickListener() {

      @Override

      public void onClick(View v) {

        textView1.setDrawingCacheEnabled(true);

        Bitmap bmp = Bitmap.createBitmap(textView1.getDrawingCache());

        textView1.setDrawingCacheEnabled(false);

        imageView1.setImageBitmap(bmp);

      }

    });

    RelativeLayout.LayoutParams params3 = new RelativeLayout.LayoutParams(400,400);

    params3.leftMargin = 10;

    params3.topMargin = 515;

    relativeLayout.addView(button1,params3);

  }

}

[iOS]How to capture screen

[日本語]

 

I introduce how to capture screen and make a bitmap image on iOS this time.

 

Environment:Xcode 8.3, Swift 3

 

Sample code is below.

import UIKit

 

class ViewController: UIViewController {

  let label1:UILabel = UILabel()

  let imageView1:UIImageView = UIImageView()

  let button1:UIButton = UIButton()

 

  override func viewDidLoad() {

    super.viewDidLoad()

    // Do any additional setup after loading the view, typically from a nib.

    label1.frame = CGRect(x: 10, y: 20, width: 100, height: 100)

    label1.text = "Label1"

    label1.backgroundColor = UIColor.blue

    self.view.addSubview(label1)

 

    imageView1.frame = CGRect(x: 10, y: 125, width: 300, height: 300)

    imageView1.layer.borderWidth = 0.5

    imageView1.contentMode = .scaleAspectFit

    self.view.addSubview(imageView1)

 

    button1.frame = CGRect(x: 10, y: 430, width: 100, height: 50)

    button1.backgroundColor = UIColor.blue

    button1.layer.cornerRadius = 5

    button1.setTitle("Button1", for: .normal)

    button1.addTarget(self, action: #selector(self.touchUpButton1), for: .touchUpInside)

    self.view.addSubview(button1)

  }

 

  override func didReceiveMemoryWarning() {

    super.didReceiveMemoryWarning()

    // Dispose of any resources that can be recreated.

  }

 

  func touchUpButton1(){

    //Get context

    let rect = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)

    UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)

    let context: CGContext = UIGraphicsGetCurrentContext()!

 

    //Write screen's objects' info at context

    self.view.layer.render(in: context)

 

    //Get UIImage

    let capturedImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()!

 

    //Close context

    UIGraphicsEndImageContext()

    imageView1.image = capturedImage

  }

}

At first, use UIGraphicsBeginImageContextWithOptions, and make context of bitmap for capturing screen.

And write screen's objects' info at context.("self.view.layer.render(in:context)")

 

And use UIGraphicsGetImageFromCurrentImageContext, and get UIImage from context.

At last, use UIGraphicsEndImageContext, and close context.

Journey to Ozu by Iyonadamonogatari

[日本語]

 

I went to Ozu City,Ehime Prefecture,Japan by "Iyonadamonogatari",a sightseeing train of JR Yosan Line.

Iyonadamonogatari has 4 types,Ozu-hen(going to Iyo Ozu Station from Matsuyama Station),Soukai-hen(going to Matsuyama Station from Iyo Ozu Station),Yahatahama-hen(going to Yahatahama Station from Matsuyama Station) and Dogo-hen(going to Matsuyama Station from Yahatahama Station), and all of them goes along Iyonada(the sea of Ehime).

You must buy a green ticket except for a railway-ticket for taking Iyonadamonogatari.

 

Inside of train

 

We can see the view of Iyonada Sea after a while the train leaves from Matsuyama Station.

The train goes along beautiful sea.

 

We can take memorial pictures at Shimonada Station.

 

At last,train goes along Hiji River and arrives at Ozu Station.

 

Now, let's stroll around Ozu City.

At first, I go to Ozu Castle, a symbol of Ozu City.

Castle Tower of Ozu Castle and Hiji River are beautiful.

Ozu Castle has a long history and it was built by Toyofusa Utsunomiya in 1331.

And in Edo Period, Takatora Todo rebuilt Ozu Castle and it was in its present form.

Ozu Castle's Castle Tower was broken in Meiji Period, and it was rebuilt in 2004.

It is faithfully reproduced using documents of Edo Period.

 

It's the view of Ozu City from the top of Castle Tower. It's beautiful. 

 

Next, I went to Garyu Sansou after Ozu Castle.

Garyu Sansou is a mountain villa made by Torajiro Kouchi in Meiji Period and it is as popular as Ozu Castle in Ozu City.

 

Garden of Garyu Sansou has a relaxed atmosphere.

 

This building named "Furoan" is made near Hiji River.

 

This is Garyu Jyaya, a Japanese cafe near Garyu Sansou.

 

We can eat Japanese sweets and a light meal seeing the garden of this cafe.

This is a set of "Suishou" Mochi and dark green tea, famous menu of this cafe.

"Suishou" Mochi is tender and delicious.

("Suishou" means a crystal in Japanese language.)

 

This is "Ohanahan Street" and there are some houses which is made in Edo Period and Meiji Period along this street.

"Ohanahan" is name of drama made by NHK in 1966, and this street has been called "Ohanahan Street" since it was shown in drama.

 

This street is short,but I found myself relieved and comfortable when I walked this street.

[Android]Sqlite Database Programming

[日本語]

 

You can use Sqlite for saving data on Android.

 

Environment: Android Studio 2.2.1, API 19

 

1.Preparation

Make class extended SqLiteOpenHelper and declare database layout.

private final static String DB_NAME = "sample1.db";

private final static String DB_TABLE = "SampleTable";

private final static int DB_VERSION = 1;

 

private class SampleDBHelper extends SQLiteOpenHelper {

  public SampleDBHelper(Context context) {

    super(context, DB_NAME, null, DB_VERSION);

  }

 

  @Override

  public void onCreate(SQLiteDatabase db) {

    db.execSQL("create table if not exists " + DB_TABLE + "(id text primary key,name text,type integer,image BLOB)");

  }

 

  @Override

  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    if (newVersion == 2) {

      db.execSQL("alter table " + DB_TABLE + " add column newField integer default 0");

    }

  }

}

You can define table layout to use "Create Table" in onCreate method.

You can change table layout to use "Alter Table" in onUpgrade method, when application version is up.

 

When you want to save Bitmap data, define BLOB data type.

 

2.How to Insert data

Use getWritableDatabase method of class which is made by SQLiteOpenHelper, and you can get writable SQLiteDatabase class.
When you execute InsertOrThrow method of SQLiteDatabase class, and new data is inserted in Sqlite.

And you'd better not use Insert method of SQLiteDatabase class, because this method don't return Exception class when error occur.

private ImageView imageView1;

private Button buttonInsert;

RelativeLayout relativeLayout;

Context context;

 

@Override

public void onCreate(Bundle bundle) {

  super.onCreate(bundle);

  context = getApplicationContext();

  relativeLayout = new RelativeLayout(context);

  setContentView(relativeLayout);

 

  imageView1 = new ImageView(context);

  Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.drawable.edit);

  imageView1.setImageBitmap(bmp);

  imageView1.setAdjustViewBounds(true);

  RelativeLayout.LayoutParams param1 = new RelativeLayout.LayoutParams(300, 300);

  param1.leftMargin = 10;

  param1.topMargin = 10;

  param1.addRule(RelativeLayout.ALIGN_TOP);

  relativeLayout.addView(imageView1,param1);

 

  buttonInsert = new Button(context);

  buttonInsert.setText("Insert");

  buttonInsert.setOnClickListener(new View.OnClickListener() {

    @Override

    public void onClick(View v) {

      execInsert();

    }

  });

  RelativeLayout.LayoutParams param2 = new RelativeLayout.LayoutParams(300, 150);

  param2.leftMargin = 10;

  param2.topMargin = 320;

  param2.addRule(RelativeLayout.ALIGN_TOP);

  relativeLayout.addView(buttonInsert,param2);

}

 

private void execInsert(){

  try{

    SampleDBHelper dbHelper = new SampleDBHelper(context);

    SQLiteDatabase db = dbHelper.getWritableDatabase();

 

    ContentValues values = new ContentValues();

    values.put("id","0000000001");

    values.put("name","Name-1");

    values.put("type",1);

 

    Bitmap bmp = ((BitmapDrawable)imageView1.getDrawable()).getBitmap();

    if (bmp != null) {

      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

      bmp.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);

      byte[] bytes = byteArrayOutputStream.toByteArray();

      values.put("image", bytes);

    }

    db.insertOrThrow(DB_TABLE,null,values);

  }catch(Exception e){

    Log.e("touchInsertButton",e.toString());

  }

}

Use ContentValues to set field names and values.

If you want to save Bitmap Data, you must change Bitmap to byte data type.

 

3.How to update data.

Use update method of SQLiteDatabase class, you can update data in Sqlite.

private ImageView imageView1;

private Button buttonUpdate;

RelativeLayout relativeLayout;

Context context;

 

@Override

public void onCreate(Bundle bundle) {

  super.onCreate(bundle);

  context = getApplicationContext();

 

  relativeLayout = new RelativeLayout(context);

  setContentView(relativeLayout);

 

  imageView1 = new ImageView(context);

  Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.drawable.edit);

  imageView1.setImageBitmap(bmp);

  imageView1.setAdjustViewBounds(true);

  RelativeLayout.LayoutParams param1 = new RelativeLayout.LayoutParams(300, 300);

  param1.leftMargin = 10;

  param1.topMargin = 10;

  param1.addRule(RelativeLayout.ALIGN_TOP);

  relativeLayout.addView(imageView1,param1);

 

  buttonUpdate = new Button(context);

  buttonUpdate.setText("Update");

  buttonUpdate.setOnClickListener(new View.OnClickListener() {

    @Override

    public void onClick(View v) {

     execUpdate();

    }

  });

  RelativeLayout.LayoutParams param4 = new RelativeLayout.LayoutParams(300, 150);

  param4.leftMargin = 10;

  param4.topMargin = 640;

  param4.addRule(RelativeLayout.ALIGN_TOP);

  relativeLayout.addView(buttonUpdate,param4);

 }

 

private void execUpdate(){

  try{

    SampleDBHelper dbHelper = new SampleDBHelper(context);

    SQLiteDatabase db = dbHelper.getWritableDatabase();

 

    ContentValues values = new ContentValues();

    values.put("name"," Name-2");

 

    Bitmap bmp = ((BitmapDrawable)imageView1.getDrawable()).getBitmap();

    if (bmp != null) {

      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

      bmp.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);

      byte[] bytes = byteArrayOutputStream.toByteArray();

      values.put("image", bytes);

    }

 

    String whereId = "id = ? and type = ?";

    String whereArgs[] = new String[2];

    whereArgs[0] = "0000000001";

    whereArgs[1] = "1";

 

    db.update(DB_TABLE,values,whereId,whereArgs);

  }catch(Exception e){

    Log.e("touchUpdateButton",e.toString());

  }

}

You can use ContentValues to set field names and values like inserting data.

You can set your search criteria to the third argument and the fourth argument of update method.

 

4.How to delete data

Use delete method of SQLiteDatabase class, you can delete data in Sqlite.

Method of setting your search criteria is the same as updating data.

private ImageView imageView1;

private Button buttonDelete;

RelativeLayout relativeLayout;

Context context;

 

@Override

public void onCreate(Bundle bundle) {

  super.onCreate(bundle);

  context = getApplicationContext();

 

  relativeLayout = new RelativeLayout(context);

  setContentView(relativeLayout);

 

  imageView1 = new ImageView(context);

  Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.drawable.edit);

  imageView1.setImageBitmap(bmp);

  imageView1.setAdjustViewBounds(true);

  RelativeLayout.LayoutParams param1 = new RelativeLayout.LayoutParams(300, 300);

  param1.leftMargin = 10;

  param1.topMargin = 10;

  param1.addRule(RelativeLayout.ALIGN_TOP);

  relativeLayout.addView(imageView1,param1);

 

  buttonDelete = new Button(context);

  buttonDelete.setText("Delete");

  buttonDelete.setOnClickListener(new View.OnClickListener() {

    @Override

    public void onClick(View v) {

     execDelete();

    }

  });

  RelativeLayout.LayoutParams param5 = new RelativeLayout.LayoutParams(300, 150);

  param5.leftMargin = 10;

  param5.topMargin = 800;

  param5.addRule(RelativeLayout.ALIGN_TOP);

  relativeLayout.addView(buttonDelete,param5);

 }

 

private void execDelete(){

  try{

    SampleDBHelper dbHelper = new SampleDBHelper(context);

    SQLiteDatabase db = dbHelper.getWritableDatabase();

 

    String whereClause = "id = ?";

    String whereArgs[] = new String[1];

    whereArgs[0] = "0000000001";

 

    db.delete(DB_TABLE,whereClause,whereArgs);

  }catch(Exception e){

    Log.e("touchDeleteButton",e.toString());

  }

}

 

5.How to select data

When you select data in Sqlite, execute getReadableDatabase method of class which is made by SQLiteOpenHelper, and get SQLiteDatabase class(read only).

After, Use rawQuery method of SQLiteDatabase class, and you can select data in Sqlite.

private ArrayList _id = new ArrayList();

private ArrayList _name = new ArrayList();

private ArrayList _image = new ArrayList();

 

private void execSelect(){

  try{

    byte[] dataValue;

    Bitmap bmp = null;

    _id.clear();

    _name.clear();

    _image.clear();

 

    SampleDBHelper dbHelper = new SampleDBHelper(context);

    SQLiteDatabase db = dbHelper.getReadableDatabase();

 

    String sql = "select id,name,image from " + DB_TABLE + " where type=1 order by id";

 

    Cursor c = db.rawQuery(sql, null);

 

    int recordCount = c.getCount();

    if (recordCount > 0) {

      c.moveToFirst();

      for (int i = 0; i < recordCount; i++) {

        _id.add(c.getString(0)); //id

        _name.add(c.getString(1)); //name

        dataValue = c.getBlob(2); //image

        if (dataValue != null) {

          bmp = BitmapFactory.decodeByteArray(dataValue, 0, dataValue.length);

          _image.add(bmp); } c.moveToNext();

        }

      }

      c.close();

   }catch(Exception e){

     Log.e("touchSelectButton",e.toString());

   }

}

 

・Sample Code

package net.studioks.sample1;

 

import android.app.Activity;

import android.content.ContentValues;

import android.content.Context;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.graphics.drawable.BitmapDrawable;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.ImageView;

import android.widget.RelativeLayout;

import java.io.ByteArrayOutputStream;

import java.util.ArrayList;

 

public class sample1 extends Activity {

  private ImageView imageView1;

  private Button buttonInsert;

  private Button buttonSelect;

  private Button buttonUpdate;

  private Button buttonDelete;

  RelativeLayout relativeLayout;

  Context context;

 

  @Override

  public void onCreate(Bundle bundle) {

    super.onCreate(bundle);

    context = getApplicationContext();

 

    relativeLayout = new RelativeLayout(context);

    setContentView(relativeLayout);

 

    imageView1 = new ImageView(context);

    Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.drawable.edit);

    imageView1.setImageBitmap(bmp);

    imageView1.setAdjustViewBounds(true);

    RelativeLayout.LayoutParams param1 = new RelativeLayout.LayoutParams(300, 300);

    param1.leftMargin = 10;

    param1.topMargin = 10;

    param1.addRule(RelativeLayout.ALIGN_TOP);

    relativeLayout.addView(imageView1,param1);

 

    buttonInsert = new Button(context);

    buttonInsert.setText("Insert");

    buttonInsert.setOnClickListener(new View.OnClickListener() {

      @Override

      public void onClick(View v) {

        execInsert();

      }

    });

    RelativeLayout.LayoutParams param2 = new RelativeLayout.LayoutParams(300, 150);

    param2.leftMargin = 10;

    param2.topMargin = 320;

    param2.addRule(RelativeLayout.ALIGN_TOP);

    relativeLayout.addView(buttonInsert,param2);

 

    buttonSelect = new Button(context);

    buttonSelect.setText("Select");

    buttonSelect.setOnClickListener(new View.OnClickListener() {

      @Override

      public void onClick(View v) {

        execSelect();

      }

    });

    RelativeLayout.LayoutParams param3 = new RelativeLayout.LayoutParams(300, 150);

    param3.leftMargin = 10;

    param3.topMargin = 480;

    param3.addRule(RelativeLayout.ALIGN_TOP);

    relativeLayout.addView(buttonSelect,param3);

 

    buttonUpdate = new Button(context);

    buttonUpdate.setText("Update");

    buttonUpdate.setOnClickListener(new View.OnClickListener() {

      @Override

      public void onClick(View v) {

        execUpdate();

      }

    });

    RelativeLayout.LayoutParams param4 = new RelativeLayout.LayoutParams(300, 150);

    param4.leftMargin = 10;

    param4.topMargin = 640;

    param4.addRule(RelativeLayout.ALIGN_TOP);

    relativeLayout.addView(buttonUpdate,param4);

 

    buttonDelete = new Button(context);

    buttonDelete.setText("Delete");

    buttonDelete.setOnClickListener(new View.OnClickListener() {

      @Override

      public void onClick(View v) {

        execDelete();

      }

    });

    RelativeLayout.LayoutParams param5 = new RelativeLayout.LayoutParams(300, 150);

    param5.leftMargin = 10;

    param5.topMargin = 800;

    param5.addRule(RelativeLayout.ALIGN_TOP);

    relativeLayout.addView(buttonDelete,param5);

  }

 

  private void execInsert(){

    try{

      SampleDBHelper dbHelper = new SampleDBHelper(context);

      SQLiteDatabase db = dbHelper.getWritableDatabase();

 

      ContentValues values = new ContentValues();

      values.put("id","0000000001"); values.put("name","Name-1");

      values.put("type",1);

 

      Bitmap bmp = ((BitmapDrawable)imageView1.getDrawable()).getBitmap();

      if (bmp != null) {

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        bmp.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);

        byte[] bytes = byteArrayOutputStream.toByteArray();

        values.put("image", bytes);

      }

      db.insertOrThrow(DB_TABLE,null,values);

    }catch(Exception e){

      Log.e("touchInsertButton",e.toString());

    }

  }

 

  private void execUpdate(){

    try{

      SampleDBHelper dbHelper = new SampleDBHelper(context);

      SQLiteDatabase db = dbHelper.getWritableDatabase();

 

      ContentValues values = new ContentValues();

      values.put("name"," Name-2");

 

      Bitmap bmp = ((BitmapDrawable)imageView1.getDrawable()).getBitmap();

      if (bmp != null) {

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        bmp.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);

        byte[] bytes = byteArrayOutputStream.toByteArray();

        values.put("image", bytes);

      }

 

      String whereId = "id = ? and type = ?";

      String whereArgs[] = new String[2];

      whereArgs[0] = "0000000001";

      whereArgs[1] = "1";

 

      db.update(DB_TABLE,values,whereId,whereArgs);

    }catch(Exception e){

      Log.e("touchUpdateButton",e.toString());

    }

  }

 

  private void execDelete(){

    try{

      SampleDBHelper dbHelper = new SampleDBHelper(context);

      SQLiteDatabase db = dbHelper.getWritableDatabase();

 

      String whereClause = "id = ?";

      String whereArgs[] = new String[1];

      whereArgs[0] = "0000000001";

 

      db.delete(DB_TABLE,whereClause,whereArgs);

    }catch(Exception e){

      Log.e("touchDeleteButton",e.toString());

    }

  }

 

  private ArrayList _id = new ArrayList();

  private ArrayList _name = new ArrayList();

  private ArrayList _image = new ArrayList();

 

  private void execSelect(){

    try{

      byte[] dataValue; Bitmap bmp = null; _id.clear();

      _name.clear();

      _image.clear();

 

      SampleDBHelper dbHelper = new SampleDBHelper(context);

      SQLiteDatabase db = dbHelper.getReadableDatabase();

 

      String sql = "select id,name,image from " + DB_TABLE + " where type=1 order by id";

 

      Cursor c = db.rawQuery(sql, null);

      int recordCount = c.getCount();

      if (recordCount > 0) {

        c.moveToFirst();

        for (int i = 0; i < recordCount; i++) {

          _id.add(c.getString(0)); //id

          _name.add(c.getString(1)); //name

          dataValue = c.getBlob(2); //image

          if (dataValue != null) {

            bmp = BitmapFactory.decodeByteArray(dataValue, 0, dataValue.length);

            _image.add(bmp);

          }

          c.moveToNext();

        }

      }

      c.close();

    }catch(Exception e){

      Log.e("touchSelectButton",e.toString());

    }

  }

 

  private final static String DB_NAME = "sample1.db";

  private final static String DB_TABLE = "SampleTable";

  private final static int DB_VERSION = 1;

 

  private class SampleDBHelper extends SQLiteOpenHelper {

    public SampleDBHelper(Context context) {

      super(context, DB_NAME, null, DB_VERSION);

    }

 

    @Override

    public void onCreate(SQLiteDatabase db) {

      db.execSQL("create table if not exists " + DB_TABLE + "(id text primary key,name text,type integer,image BLOB)");

    }

 

    @Override

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

      if (newVersion == 2) {

        db.execSQL("alter table " + DB_TABLE + " add column newField integer default 0");

      }

    }

  }

}

[iOS]Core Data Programming

[日本語]

 

You can do database programming by Core Data, O/R mapping tool for Sqlite, on iOS.

 

Environment: Xcode 8.3, Swift 3

 

1.Preparation

At first, Check "Use Core Data" when project is created.

And code of Core Data Objects are created in AppDelegate.

 

Next, select "[project name].xcdatamodeld" and define table layout.

 

To save UIImage, select "Binary Data" in Type and check "Allow External Storage". 

When the size of UIImage is big, URL of UIImage is saved in Core Data.

When you don't check "Allow External Storage", the time of saving core data will take and memory utilization will be increase instantly, and an application will crash.

 

After table layout definition, execute [Editor]-[Create NSManagedObject Subclass] on Xcode.

And class of table layout definition, NSManagedObject is created.

 

At last, declare "import Core Data" at the top of class using Core Data.

 

2.How to INSERT

At first, Make NSManagedObjectContext in AppDelegate.

Next, Make NSManagedObject from NSManagedObjectContext.

Let's see code for inserting new data by Core Data.

import UIKit

import CoreData

 

class ViewController: UIViewController {  

 

 private var imageView:Array<UIImageView!> = Array<UIImageView!>() 

 

 func saveImageData(){

  

  //Save UIImageView's image  

  let imageData:NSData! = UIImageJPEGRepresentation(imageView[0].image,1.0)!

  

  var imageOrientation:Int = 0   

  if (imageView[0].image.imageOrientation == UIImageOrientation.Down){    

   imageOrientation = 2   

  }else{    

   imageOrientation = 1   

  }   

 

  let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate   

  let managedContext: NSManagedObjectContext = appDelegate.managedObjectContext   

  let objectEntity:NSManagedObject = NSEntityDescription.insertNewObjectForEntityForName("Object", inManagedObjectContext: managedContext) as NSManagedObject

  

  objectEntity.setValue(imageData, forKey: "dataValue")   

  objectEntity.setValue(imageOrientation, forKey: "imageOrientation")   

 

  do {    

   try managedContext.save()   

  }catch let error{    

   NSLog("\(error)")   

  }   

  managedContext.reset()  

 }

}

 

2.How to SELECT

Let's see code for selecting data by Core Data.

func LoadData(id:String){

 var minX:CGFloat = 0

 var minY:CGFloat = 0

 var widthValue:CGFloat = 0

 var heightValue:CGFloat = 0

 var imageOrientation:Int = 0

  

 let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate   

 let managedContext: NSManagedObjectContext = appDelegate.managedObjectContext

  

 let fetchRequest = NSFetchRequest(entityName: "Object")   

 fetchRequest.returnsObjectsAsFaults = false   

 

 let predicate = NSPredicate(format: "id == %@", id)   

 fetchRequest.predicate = predicate   

 

 let descriptor_1 = NSSortDescriptor(key: "objectType", ascending: true)   

 let descriptor_2 = NSSortDescriptor(key: "createDateTime", ascending: false)   

 fetchRequest.sortDescriptors = [descriptor_1,descriptor_2]

 

 do {     

  let fetchResults: Array = try managedContext.executeFetchRequest(fetchRequest)      

 

  for fetchResult in fetchResults {       

   let object = fetchResult as! NSManagedObject

      

   width = fetchResult.valueForKey("width") as! CGFloat       

   height = fetchResult.valueForKey("height") as! CGFloat       

   minX = fetchResult.valueForKey("minX") as! CGFloat       

   minY = fetchResult.valueForKey("minY") as! CGFloat       

   data = fetchResult.valueForKey("data") as! NSData

      

   image = UIImage(data: data)       

   imageOrientation = fetchResult.valueForKey("imageOrientation") as! Int       

   if (imageOrientation == 2) {         

    image = UIImage(CGImage: image!.CGImage!, scale: image!.scale, orientation: UIImageOrientation.Down)       

   }

 

   imageView.append(UIImageView())             

   imageView[imageView.count - 1].frame = CGRect(x:minX,y:minY,width:widthValue,height:heightValue)       

   imageView[imageView.count - 1].image = image       

   self.view.addSubView(imageView[imageView.count-1])      

  }   

 }catch let error{       

  NSLog("\(error)")   

 }   

 managedContext.reset()  

}

Use NSPredicate for designating searching options.

Use NSSortDescriptor and ascending option for designation sort options.

 

If you road UIImage, check UIImageOrientation.

If UIImageOrientation is down, you must invert UIImage.

 

3.How to UPDATE

Update value of data which is read.

Let's see code for updating data by Core Data.

func UpdateData(id:String, objectType:Int){

    var index:Int = 0

  

 let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate   

 let managedContext: NSManagedObjectContext = appDelegate.managedObjectContext   

 

 let fetchRequest = NSFetchRequest(entityName: "Object")   

 fetchRequest.returnsObjectsAsFaults = false   

 

 let predicate = NSPredicate(format: "id == %@ And objectType == %d", id, objectType)   

 fetchRequest.predicate = predicate   

 

 do {    

  let fetchResults: Array = try managedContext.executeFetchRequest(fetchRequest)     

 

  for fetchResult in fetchResults {      

   let object = fetchResult as! NSManagedObject

 

   //Get value

   index = fetchResult.valueForKey("index") as! Int      

 

   //Update value     

   object.setValue(imageView[index].frame.width, forKey: "width")      

   object.setValue(imageView[index].frame.height, forKey: "height")      

   object.setValue(imageView[index].frame.minX, forKey: "minX")      

   object.setValue(imageView[index].frame.minY, forKey: "minY")      

 

   let imageData:NSData! = UIImageJPEGRepresentation(imageView[index].image,1.0)!      

   object.setValue(imgeData, forKey: "data")

 

   var imageOrientation:Int = 0   

   if (imageView[index].image.imageOrientation == UIImageOrientation.Down){    

    imageOrientation = 2   

   }else{    

    imageOrientation = 1   

   }

   object.setValue(imageOrientation, forKey:"imageOrientation")  

  }     

  try managedContext.save()   

 }catch let error{    

  NSLog("\(error)")   

 }  

 managedContext.reset()  

}

 

4.How to DELETE

Delete data which is read.

func DeleteData(id:String,objectType:Int){   

 let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate   

 let managedContext: NSManagedObjectContext! = appDelegate.managedObjectContext

  

 let fetchRequest = NSFetchRequest(entityName: "Object")   

 fetchRequest.returnsObjectsAsFaults = false   

 

 let predicate = NSPredicate(format: "id == %@ and objectNo == %d", id,objectType)   

 fetchRequest.predicate = predicate  

 

 do {   

  var fetchResults: Array! = try managedContext.executeFetchRequest(fetchRequest)   

  for fetchResult in fetchResults {    

   let object = fetchResult as! NSManagedObject    

 

   //Making a mark as deleted   

   managedContext.deleteObject(object)   

  }

        //Exec saving -> Delete data

  try managedContext.save()  

 }catch let error{    

  NSLog("\(error)")   

 }   

 managedContext.reset()  

}

Grass Courts in Yugawara Town

[日本語]

 

I went to "bonnfemme", a pension in Yugawara Town, Kanagawa Prefecture, Japan, at the event planned by Tennis Shop LAFINO .
It has two grass tennis courts. 

 

The feel of a grass court is soft.

I snuggled down in grass court without even thinking.

 

When tennis ball bounced, the force of it got weak.

But the speed of tennis ball became quick, when we hit a serve or a slice. 
We had a hard time because tennis ball often took bad hops.

 

There are ant-hills and earthworms in grass courts.

 

We can see the sea of Yugawara from tennis courts.
We can enjoy playing tennis seeing beautiful sea.

Management of grass courts is very difficult, and a manager adjusts lawn at stated periods.
And the period of using grass courts is about a half of a year, and hours of using them is one or two hours a day.

 

This is a beautiful building of bonnefemme.

 

Also, Rooms are beautiful. 

 

There is an open spa facing the sea of Yugawara in bonnefemme.
Water of it is Yugawara hot spring.

We can enjoy nice hot spring after playing tennis.

 

This pension serves delicious French cuisine.

 

This pension is often visited by young couple.
I recommend this pension to young couple who play tennis.

Irises Screens of Nezu Museum

[日本語]

 

I went to Nezu Museum in Minami Aoyama, Tokyo, Japan.

Nezu Museum houses Japanese arts. And structures of Nezu Museum designed by Mr.Kengo Kuma, an architect of Japan, are in harmony with nature. 

 

Nezu Museum has a big Japanese garden.

There are a lot of plants and they are beautiful.
I think I am going to forget here is center of metropolitan area.

 

Nezu Museum displays "Irises Screens", a famous Japanese painting drawn by Korin Ogata, a famous painter of Edo Period, between April and May.

And there are some irises in the garden of Nezu Museum between April and May.

It is nice to see both "Irises Screens" and real irises.

 

There is a cafe "NEZUCAFÉ" in the garden of Nezu Art Museum.

I ate "Colorful Annin(Almond Jelly)" at it.

Sweet taste almond jelly and sourish taste of kiwifruit were very delicious.

0 コメント

Matsuyama's tramcar and Botchan Ressha

[日本語]

 

The main public transportation of Matsuyama City is a tramcar.

This is Iyo Railway(it is also called "Iyotetsu") Matsuyama City Line.

 

This is a conventional type car.(Moha 50, Moha 2000)

 

This is a LRT type car.(Moha 2100)

 

LRT type car is painted sponsor's color.

This is a car painted characters of Ehime Kokutai(National Sports Festival).

(It is called "Kokutai Mican Car".)

 

The interior of a tram car(Moha 50, Moha 2000).

 

Iyotetsu introduced the IC e-card, a smart card ticketing system.

But other smart card, for example, SUICA, PASMO and ICOCA, can't be used.(Apple Pay can't be used.)

 

You can use free WiFi(Ehime Free WiFi) in a tramcar.

 

It's the tramcar stop.(Okaido Station)

 

A flat fare of 160 yen(about 145 - 160 U.S. dollars) is charged on a tramcar.(Children are half price.)

A flat fare of 500 yen is charged on "one day passport for a tramcar" and a flat fare of 800 yen is charged on "two day passport for a tramcar".(Children are half price, too.)

 

"Botchan Ressha", a diesel-powered replica of a small-gauge steam locomotive installed in Matsuyama City in Meiji Period, runs a route of a tramcar.

Route:

   A. Matsuyamashi Station - Dogo Onsen Station

   B. Komachi Station - Dogo Onsen Station

"Botchan Ressha"'s name is based on "Botchan", the novel written by Soseki Natsume.

 

Its inside restores to original steam locomotive in Meiji Period.

A flat fare of 500 yen(about 450 - 500 U.S. dollars) is charged on it.

 

Botchan Ressha arrived at Dogo Onsen Station, the terminus.

 

It makes a turn at Dogo Onsen Station, Matsuyamashi Station and Komachi Station.

 

There is timetable of "Botchan Ressha" at tramcar's station that is stopped by "Botchan Ressha".

 

There is a crossing of a tramcar and a train in Matsuyama City.

It is called "Diamond Cross", and it is one of famous places of Matsuyama City.

0 コメント

< Previous                Next >