たぼさんの部屋

いちょぼとのんびり

T326

f:id:donsuka_kk:20121229014211p:plain

Main.java

package com.efolab.t326;
/*
 * 一番シンプルなSQLDb
 * すべての引数はMain側で保持する
 */
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
	
public class Main extends Activity {
	Context context;
	LinearLayout base;
	View view;
	/* ListView */
	ListView lv;
	private final int resouces = R.layout.listlayout;
	private final String[] from = {"_id" , "lat" , "lng" , "update_date" };
	private final int[] to = {R.id.textView1 , R.id.textView2 , R.id.textView3 , R.id.textView4};
	private HashMap<String , Object> map;
	private List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();
	private SimpleAdapter adapter;
	/* db */
	private static final String CLASSNAME = Main.class.getSimpleName();
	private static final String DB_NAME = "DB_"+CLASSNAME;
	private static final String TABLE_NAME ="T_"+CLASSNAME;
	private static final int DB_VER = 1;
	private static final String CREATE_TABLE = "CREATE TABLE "+	TABLE_NAME +" ("
			+ "seq INTEGER primary key autoincrement" 
			+ ",lat REAL not null "
			+ ",lng REAL not null" 
			+ ",send_flg integer DEFAULT 0"
			+ ",del_flg integer DEFAULT 0"
			+ ",update_date TIMESTAMP DEFAULT (DATETIME('now','localtime'))"
			+ ");";
	private SQLiteDatabase db;
	private SQLiteOpenHelper helper;
	private String sql = null;
	private int db_count = 0;		//最後に取得した件数を格納する
	/* LocationManager */
	LocationManager lm;
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    context = getApplicationContext();
	    base = new LinearLayout(context);
	    base.setOrientation(LinearLayout.VERTICAL);
	    setContentView(base);
	    
	    
	    //db
	    helper = new SQLiteOpenHelper(context, DB_NAME, null, DB_VER) {
	    	@Override
	    	public void onCreate(SQLiteDatabase db) {
	    		try{
	    			db.execSQL(CREATE_TABLE);
	    		}catch(SQLException e){
	    			Log.e(CLASSNAME,"e:"+e);
	    		}
	    		
	    	}
			
			@Override
			public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
				// TODO Auto-generated method stub
				
			}
			
		};
		
		//LocationManager
		lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
	    
	    //ListView
	    lv = new ListView(context);
	    adapter = new SimpleAdapter(context, data, resouces, from, to){

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				View view = super.getView(position, convertView, parent);
				 if (position % 2 == 0) {
					 	view.setBackgroundColor(Color.BLACK);
			        } else {
			        	view.setBackgroundColor(Color.DKGRAY);
			        }
				return view;
				
			}
	    	
	    };
	    lv.setAdapter(adapter);
	    
	    //addview
	    base.addView(lv);
	    
	    /*
		 * db select
		 */
		sql = "select seq as _id , lat , lng , update_date from " + TABLE_NAME + " where del_flg = 0 and send_flg = 0;";
		db = helper.getReadableDatabase();
		Cursor c = db.rawQuery(sql, null);
		//データ件数を格納する
		db_count = c.getCount();
		
		c.moveToFirst();
		for(int i=0;i<c.getCount();i++){
			map = new HashMap<String , Object>();
			map.put("_id", c.getInt(0));
			map.put("lat", c.getDouble(1));
			map.put("lng", c.getDouble(2));
			map.put("update_date", c.getString(3));
			data.add(map);
			c.moveToNext();
		}
	    
	    db.close();
	    
	    adapter.notifyDataSetChanged();
	    

	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 10,l);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		lm.removeUpdates(l);
	}

	LocationListener l = new LocationListener() {
		
		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onLocationChanged(Location location) {
			// TODO Auto-generated method stub
			/*
			 * db insert
			 */
			sql = "insert into " + TABLE_NAME + " (lat,lng) values (" + location.getLatitude() +" , " + location.getLongitude() + " );";
			db = helper.getWritableDatabase();
			db.execSQL(sql);
			db.close();
			/*
			 * db select
			 */

			sql = "select seq as _id , lat , lng , update_date from " + TABLE_NAME + " where del_flg = 0 and send_flg = 0;";
			db = helper.getReadableDatabase();
			Cursor c = db.rawQuery(sql, null);
			//差分のデータ(最新データ)のみ追加する
			Toast.makeText(context, "db_count"+db_count+",c.getCount():"+c.getCount(), Toast.LENGTH_SHORT).show();
			c.moveToPosition(db_count);		//差分の最新行に移動させる(c.move()だと1つ前になる)
			/*
			 * ただし、この方法はサーバーに送信して、データ件数が変更になったときには
			 * 使えない。
			 * (send_flg = 1にセットしたとき。)
			 * その時は全数を取得しなおすこと。
			 */
			for(int i=db_count;i<c.getCount();i++){
				Toast.makeText(context, "i"+i, Toast.LENGTH_SHORT).show();
				map = new HashMap<String , Object>();
				map.put("_id", c.getInt(0));
				map.put("lat", c.getDouble(1));
				map.put("lng", c.getDouble(2));
				map.put("update_date", c.getString(3));
				data.add(map);
				c.moveToNext();
			}
			
			db_count = c.getCount();	//データベース件数を更新しておく
			db.close();
			
		    adapter.notifyDataSetChanged();	//更新 新規データのみ追記される
		    
		}
	};
}

listlayout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:padding="1dp"
    android:paddingLeft="3dp" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="3dp"
        android:text="TextView"
        android:textColor="#ff0000" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="3dp"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="3dp"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="3dp"
        android:text="TextView" />

</LinearLayout>

Manifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.efolab.t326"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
	<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
	<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity android:name="Main">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>