android 数据库同步

package org.jerry;

import org.hwq.dbutil.R;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {
	private TextView info;
	private Button runWrongBtn;
	private Button runRightBtn;
	private Button showInfoBtn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        holdUIComponents();
        showInfo();
    }

	private void holdUIComponents() {
		info = (TextView) findViewById(R.id.info);
		runWrongBtn = (Button) findViewById(R.id.runWrongBtn);
		runRightBtn = (Button) findViewById(R.id.runRightBtn);
		showInfoBtn = (Button) findViewById(R.id.showInfoBtn);
		
		runWrongBtn.setOnClickListener(this);
		runRightBtn.setOnClickListener(this);
		showInfoBtn.setOnClickListener(this);
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.runWrongBtn:
			runWrong();
			break;
		case R.id.runRightBtn:
			runRight();
			break;
		case R.id.showInfoBtn:
			showInfo();
			break;
		}
	}

	private void runWrong() {
		//因为不同步,会导致异常:database is locked
		RunWrongThread t0 = new RunWrongThread();
		RunWrongThread t1 = new RunWrongThread();
		
		t0.start();
		t1.start();
		
		try {
			t0.join();
			t1.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		showInfo();
	}
	
	private void runRight() {
		//有同步,执行正常
		RunRightThread t0 = new RunRightThread();
		RunRightThread t1 = new RunRightThread();
		
		t0.start();
		t1.start();
		
		try {
			t0.join();
			t1.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		showInfo();
	}
	
	private void showInfo() {
		int userNums = DBUtil.getUserNums(getApplicationContext());
		info.setText(Integer.toString(userNums));
	}
	
	class RunWrongThread extends Thread {
		
		@Override
		public void run() {
			DBOpenHelper dbHelper = new DBOpenHelper(getApplicationContext());
			
			for (int i = 0; i < 100; i++) {
				User user = new User();
				user.setName("name" + i);
				user.setAge(i);
				user.setEmail("email" + i);

				dbHelper.insert(user);
			}
			
			dbHelper.close();
		}
		
	}
	
	class RunRightThread extends Thread {

		@Override
		public void run() {
			for (int i = 0; i < 100; i++) {
				User user = new User();
				user.setName("name" + i);
				user.setAge(i);
				user.setEmail("email" + i);

				DBUtil.insertUser(getApplicationContext(), user);
			}
			
			DBUtil.close();
		}
		
	}
}


package org.jerry;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBOpenHelper extends SQLiteOpenHelper{
	private static final String DB_NAME = "db";
	private static final int DB_VERSION = 1;
	
	private static final String T_USER = "t_user";
	private static final String T_USER_COLUMN_ID = "id";
	private static final String T_USER_COLUMN_NAME = "name";
	private static final String T_USER_COLUMN_AGE = "age";
	private static final String T_USER_COLUMN_EMAIL = "email";
	private static final String T_USER_SQL = "create table " + T_USER + " (" + T_USER_COLUMN_ID + " integer primary key autoincrement, " + T_USER_COLUMN_NAME + " text, " + T_USER_COLUMN_AGE + " integer, " + T_USER_COLUMN_EMAIL + " text)";
	
	public DBOpenHelper(Context context) {
		super(context, DB_NAME, null, DB_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(T_USER_SQL);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		
	}
	
	public void insert(User user) {
		if (user == null) {
			return;
		}
		
		final ContentValues values = new ContentValues();
		values.put(T_USER_COLUMN_NAME, user.getName());
		values.put(T_USER_COLUMN_AGE, user.getAge());
		values.put(T_USER_COLUMN_EMAIL, user.getEmail());
		
		final SQLiteDatabase db = getWritableDatabase();
		db.insert(T_USER, null, values);
	}
	
	public int getUserNums() {
		final SQLiteDatabase db = getReadableDatabase();
		final Cursor cursor = db.query(T_USER, null, null, null, null, null, null);
		
		if (cursor == null) {
			return 0;
		}
		
		int count = cursor.getCount();
		cursor.close();
		
		return count;
	}
}


package org.jerry;

import android.content.Context;

public class DBUtil {
	private static DBOpenHelper dbHelper;
	
	private static void ensureDBHelperExist(Context context) {
		if (dbHelper == null) {
			dbHelper = new DBOpenHelper(context);
		}
	}
	
	/**
	 * 插入user
	 * @param context 务必使用ApplicationContext,直接使用activity/service的context可能导致内存泄露
	 * @param user
	 */
	public synchronized static void insertUser(Context context, User user) {
		ensureDBHelperExist(context);
		dbHelper.insert(user);
	}
	
	/**
	 * @param context 务必使用ApplicationContext,直接使用activity/service的context可能导致内存泄露
	 * @return
	 */
	public synchronized static int getUserNums(Context context) {
		ensureDBHelperExist(context);
		return dbHelper.getUserNums();
	}
	
	public synchronized static void close() {
		if (dbHelper != null) {
			dbHelper.close();
			dbHelper = null;
		}
	}
}

猜你喜欢

转载自uuubd.iteye.com/blog/1956001