2011年12月26日月曜日

assetsフォルダのデータベースファイル利用

assetsフォルダのデータベース利用2 を新しく書きました。
assetsフォルダにdatabase.dbがある場合

assetsフォルダのデータベースをdatabaseフォルダにコピーして使う
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.TextView;

public class RopouActivity extends Activity {

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  String DB_PATH = "/data/data/com.yamato.ropou/databases/";
  String DB_NAME = "database.db";

  try {

   InputStream myInput = getResources().getAssets()
     .open("database.db");
//InputStream myInput = this.getResources().openRawResource(R.raw.database);//res/rawフォルダにデータベースがある場合
   String outFileName = DB_PATH + DB_NAME;
   OutputStream myOutput = new FileOutputStream(outFileName);

   byte[] buffer = new byte[2048];
   int length;
   while ((length = myInput.read(buffer)) > 0) {
    myOutput.write(buffer, 0, length);
   }

   // Close the streams
   myOutput.flush();
   myOutput.close();
   myInput.close();

  } catch (IOException e) {
   // TODO 自動生成された catch ブロック
   e.printStackTrace();
  }

        //データベースを開く  
  SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, 0);
         
        Cursor c = db.query("myDatabaseTable", new String[] { "name", "age" },
          null, null, null, null, null);
         
        boolean isEof = c.moveToFirst();
        TextView textView1 = (TextView)findViewById(R.id.textView1);
         
        String text="";
        while (isEof) {
            text += String.format("%s : %d歳\r\n", c.getString(0), c.getInt(1));
            isEof = c.moveToNext();
        }
        textView1.setText(text);
         
        c.close();
        db.close();
    }
}


動かない
package com.android.word.net;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class AndroidWordNetActivity extends Activity {
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  AssetManager as = getResources().getAssets();
  
  Log.d("タグ",as.toString() );
  
  //ヘルパークラスのインスタンスを作成します。
        MyDBHelper helper = new MyDBHelper(this,as.toString()+"database.db");
         
        SQLiteDatabase db = helper.getWritableDatabase();
        
        Cursor c = db.query("myDatabaseTable", new String[] { "name", "age" },
          null, null, null, null, null);
         
        boolean isEof = c.moveToFirst();
        TextView textView1 = (TextView)findViewById(R.id.textView1);
         
        String text="";
        while (isEof) {
            text += String.format("%s : %d歳\n", c.getString(0), c.getInt(1));
            isEof = c.moveToNext();
        }
        textView1.setText(text);
         
        c.close();
        db.close();
        
 }
 

 public class MyDBHelper extends SQLiteOpenHelper {
  public MyDBHelper(Context context, String string) {
            super(context, string, null, 1);
        }
  
        @Override
        //ここでデータベース作成(コンストラクタに渡されたDBファイル名が存在しない場合に呼ばれる)
        public void onCreate(SQLiteDatabase db) {
            // テーブルを作成
        }


  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
   // TODO 自動生成されたメソッド・スタブ
   
  }
 }
}

2011年12月25日日曜日

assetsフォルダのファイル利用

assetsフォルダに入れられるファイルサイズは1MBの制限がある。



package com.android.word.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidWordNetActivity extends Activity {
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  AssetManager as = getResources().getAssets();

  BufferedReader br = null;
  StringBuilder sb = new StringBuilder();

  try {
   try {
    InputStream is = as.open("asset_file.txt");
    br = new BufferedReader(new InputStreamReader(is));

    String str;
    while ((str = br.readLine()) != null) {
     sb.append(str + "\n");
    }
   } finally {
    if (br != null)
     br.close();
   }
  } catch (IOException e) {
   Toast.makeText(this, "読み込み失敗", Toast.LENGTH_SHORT).show();
  }
  TextView label = (TextView) this.findViewById(R.id.textView1);
  label.setText(sb.toString());
 }
}

GETでホームページ取得:Android Http インターネット


package com.android.test;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.TextView;

public class AndroidTestHttpActivity extends Activity {
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitAll().build());
  
  HttpURLConnection http = null;
  InputStream in = null;
  TextView web = (TextView) findViewById(R.id.textView1);
  try {
   // URLにHTTP接続
   URL url = new URL("http://www.google.co.jp");
   http = (HttpURLConnection) url.openConnection();
   http.setRequestMethod("GET");
   http.connect();
   // データを取得
   in = http.getInputStream();

   // HTMLソースを読み出す
   String src = new String();
   byte[] line = new byte[1024];
   int size;
   while (true) {
    size = in.read(line);
    if (size <= 0)
     break;
    src += new String(line);
   }
   // HTMLソースを表示
   web.setText(src);
  } catch (Exception e) {
   web.setText(e.toString());
  } finally {
   try {
    if (http != null)
     http.disconnect();
    if (in != null)
     in.close();
   } catch (Exception e) {
   }
  }

 }
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

</LinearLayout>


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

    <uses-sdk android:minSdkVersion="14" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".AndroidTestHttpActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

2011年12月24日土曜日

端末起動時にサービスを実行:タイマーで指定時間から繰り返し

端末起動時にサービスを実行:タイマーで繰り返し の記事の一部を修正

package com.my.android.test;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class MainService extends Service {
 private Timer timer;
 @Override
 public IBinder onBind(Intent intent) {
  // TODO Auto-generated method stub
  return null;
 }
 @Override
   public void onCreate() {
     super.onCreate();
     Log.d("TAG", "onCreate");
   }
 @Override
 //onStartは2.0以降は非推奨でonStartCommandを使うことが推奨されている
 //public void onStart(Intent intent, int startId) {
 public int onStartCommand(Intent intent, int flags, int startId) {
  //現在時刻の取得
  long currentTimeMillis = System.currentTimeMillis();
  Date date = new Date(currentTimeMillis + 10000);//現在時刻+10秒

  // タイマの設定
  timer = new Timer(true);
  final Handler handler = new Handler();
  //service = Executors.newSingleThreadScheduledExecutor();
  timer.scheduleAtFixedRate( new TimerTask() {
   @Override
   public void run() {
    handler.post(new Runnable() {
     public void run() {
       Log.d("TAG", "onStartCommand");
     }
    });
   }
  }, date, 3000);//スタート時間、3秒間隔
  //super.onStart(intent, startId);
  return START_STICKY;
 }
 @Override
   public void onDestroy() {
     super.onDestroy();
     if(timer != null){
       timer.cancel();
     }
     Log.d("TAG", "onDestroy");
   }

}

Executorsクラスで繰り返し

端末起動時にサービスを実行:タイマーで繰り返しの記事の一部を修正


package com.my.android.test;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class MainService extends Service {
 private Timer timer;
 private ScheduledExecutorService service;
 @Override
 public IBinder onBind(Intent intent) {
  // TODO Auto-generated method stub
  return null;
 }
 @Override
   public void onCreate() {
     super.onCreate();
     Log.d("TAG", "onCreate");
   }
 @Override
 //onStartは2.0以降は非推奨でonStartCommandを使うことが推奨されている
 //public void onStart(Intent intent, int startId) {
 public int onStartCommand(Intent intent, int flags, int startId) {
  
  final Handler handler = new Handler();
  service = Executors.newSingleThreadScheduledExecutor();
  service.scheduleAtFixedRate( new TimerTask() {
   @Override
   public void run() {
    handler.post(new Runnable() {
     public void run() {
       Log.d("TAG", "onStartCommand");
     }
    });
   }
  }, 1000, 3000, TimeUnit.MILLISECONDS);//遅延、3秒間隔、単位時間
  //super.onStart(intent, startId);
  return START_STICKY;
 }
 @Override
   public void onDestroy() {
     super.onDestroy();
     if(timer != null){
       timer.cancel();
     }
     Log.d("TAG", "onDestroy");
   }

}