Clear all database SQL tables in Android - android

Here is my DatabaseHelper which saves everything. How do i erase/clean/clear all the tables?
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final String TAG = "DatabaseHelper";
private static final String DATABASE_NAME = "user.db";
private static final int DATABASE_VERSION = 1;
private RuntimeExceptionDao<CurrentUserModel, Long> currentUserModelDao;
private RuntimeExceptionDao<Contact, String> contactDao;
private RuntimeExceptionDao<ChatModel, Long> chatDao;
private RuntimeExceptionDao<ChatMessage, Long> chatMessageDao;
private RuntimeExceptionDao<ChatContact, Long> chatContactDao;
private RuntimeExceptionDao<BroadcastMessage, Long> broadcastMessageDao;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db, ConnectionSource connection) {
try {
TableUtils.createTable(connection, CurrentUserModel.class);
TableUtils.createTable(connection, Contact.class);
TableUtils.createTable(connection, ChatModel.class);
TableUtils.createTable(connection, ChatMessage.class);
TableUtils.createTable(connection, ChatContact.class);
TableUtils.createTable(connection, BroadcastMessage.class);
} catch (SQLException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connection, int arg2, int arg3) {
try {
TableUtils.dropTable(connection, CurrentUserModel.class, true);
TableUtils.dropTable(connection, Contact.class, true);
TableUtils.dropTable(connection, ChatModel.class, true);
TableUtils.dropTable(connection, ChatMessage.class, true);
TableUtils.dropTable(connection, ChatContact.class, true);
TableUtils.dropTable(connection, BroadcastMessage.class, true);
onCreate(db, connection);
} catch (SQLException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
public RuntimeExceptionDao<CurrentUserModel, Long> getCurrentUserModelDao() {
if (currentUserModelDao == null) {
try {
currentUserModelDao = RuntimeExceptionDao.createDao(getConnectionSource(), CurrentUserModel.class);
currentUserModelDao.setObjectCache(true);
} catch (SQLException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return currentUserModelDao;
}
public RuntimeExceptionDao<Contact, String> getContactDao() {
if (contactDao == null) {
try {
contactDao = RuntimeExceptionDao.createDao(getConnectionSource(), Contact.class);
contactDao.setObjectCache(true);
} catch (SQLException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return contactDao;
}
public RuntimeExceptionDao<ChatModel, Long> getChatDao() {
if (chatDao == null) {
try {
chatDao = RuntimeExceptionDao.createDao(getConnectionSource(), ChatModel.class);
chatDao.setObjectCache(true);
} catch (SQLException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return chatDao;
}
public RuntimeExceptionDao<ChatMessage, Long> getChatMessageDao() {
if (chatMessageDao == null) {
try {
chatMessageDao = RuntimeExceptionDao.createDao(getConnectionSource(), ChatMessage.class);
chatMessageDao.setObjectCache(true);
} catch (SQLException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return chatMessageDao;
}
public RuntimeExceptionDao<ChatContact, Long> getChatContactDao() {
if (chatContactDao == null) {
try {
chatContactDao = RuntimeExceptionDao.createDao(getConnectionSource(), ChatContact.class);
chatContactDao.setObjectCache(true);
} catch (SQLException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return chatContactDao;
}
public RuntimeExceptionDao<BroadcastMessage, Long> getBroadcastMessageDao() {
if (broadcastMessageDao == null) {
try {
broadcastMessageDao = RuntimeExceptionDao.createDao(getConnectionSource(), BroadcastMessage.class);
broadcastMessageDao.setObjectCache(true);
} catch (SQLException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return broadcastMessageDao;
}
#Override
public void close() {
super.close();
if (currentUserModelDao != null) {
currentUserModelDao.clearObjectCache();
currentUserModelDao = null;
}
if (contactDao != null) {
contactDao.clearObjectCache();
contactDao = null;
}
if (chatDao != null) {
chatDao.clearObjectCache();
chatDao = null;
}
if (chatMessageDao != null) {
chatMessageDao.clearObjectCache();
chatMessageDao = null;
}
if (chatContactDao != null) {
chatContactDao.clearObjectCache();
chatContactDao = null;
}
if (broadcastMessageDao != null) {
broadcastMessageDao.clearObjectCache();
broadcastMessageDao = null;
}
}
}
I am trying to make some kind of logout, which would clear all the data. Here is what I have tried:
DatabaseHelper dh = new DatabaseHelper(getActivity().getBaseContext());
dh.close();
clearApplicationData();
This works only if after these 2 rows were done, I kill the app from recent and start it again, else the app tries to register again, and crashes when tries to use the database. how do I correctly reset all application data as it was when it was installed?

The easiest way to erase all tables is to actually delete whole database.
DatabaseHelper databaseHelper = getHelper();
databaseHelper.close();
while (databaseHelper.isOpen() == true) { // maybe you dont want to use while
Thread.sleep(500);
}
this.deleteDatabase("database.db"); // specified in DatabaseHelper class in the DATABASE_NAME field
After doing this you have to create a new database helper (it recreates database) otherwise you would get exception saying something like "unable to open already closed object":
OpenHelperManager.releaseHelper();
OpenHelperManager.setHelper(new DatabaseHelper(this));

Related

Register a new user on ejabberd server in android

I am facing the problem to create a new user on ejabberd server but sign in is working fine. i used the github repository (https://github.com/dilicode/LetsChat) for register the new user and chat between two and more users. I search on intenet, i found some way to register those are:
1.add
%% In-band registration
{access, register, [{allow, all}]}.
in access rules in ejabberd server and
2. also add
{mod_register, [
{access_from, register},
...
] ...
it in access rules of ejabberd server.
my sign up activity as follows:
public class SignupActivity extends AppCompatActivity implements OnClickListener, Listener<Boolean> {
private static final int REQUEST_CODE_SELECT_PICTURE = 1;
private static final int REQUEST_CODE_CROP_IMAGE = 2;
private static final String RAW_PHOTO_FILE_NAME = "camera.png";
private static final String AVATAR_FILE_NAME = "avatar.png";
private EditText nameText;
private EditText phoneNumberText;
private EditText passwordText;
private Button submitButton;
private ImageButton uploadAvatarButton;
private File rawImageFile;
private File avatarImageFile;
private SignupTask signupTask;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
nameText = (EditText)findViewById(R.id.et_name);
phoneNumberText = (EditText)findViewById(R.id.et_phone_number);
passwordText = (EditText)findViewById(R.id.et_password);
uploadAvatarButton = (ImageButton)findViewById(R.id.btn_upload_avatar);
submitButton = (Button)findViewById(R.id.btn_submit);
submitButton.setOnClickListener(this);
uploadAvatarButton.setOnClickListener(this);
File dir = FileUtils.getDiskCacheDir(this, "temp");
if (!dir.exists()) {
dir.mkdirs();
}
rawImageFile = new File(dir, RAW_PHOTO_FILE_NAME);
avatarImageFile = new File(dir, AVATAR_FILE_NAME);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
if (v == submitButton) {
String phoneNumber = phoneNumberText.getText().toString();
String password = passwordText.getText().toString();
String name = nameText.getText().toString();
if (phoneNumber.trim().length() == 0 || password.trim().length() == 0 ||
name.trim().length() == 0) {
Toast.makeText(this, R.string.incomplete_signup_info, Toast.LENGTH_SHORT).show();
return;
}
signupTask = new SignupTask(this, this, phoneNumber, password, name, getAvatarBytes());
signupTask.execute();
} else if(v == uploadAvatarButton) {
chooseAction();
}
}
private void chooseAction() {
Intent captureImageIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
captureImageIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(rawImageFile));
Intent pickIntent = new Intent(Intent.ACTION_GET_CONTENT);
pickIntent.setType("image/*");
Intent chooserIntent = Intent.createChooser(pickIntent, getString(R.string.profile_photo));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {captureImageIntent});
startActivityForResult(chooserIntent, REQUEST_CODE_SELECT_PICTURE);
}
#Override
public void onResponse(Boolean result) {
if (result) {
Toast.makeText(this, R.string.login_success, Toast.LENGTH_SHORT).show();
startActivity(new Intent(this, MainActivity.class));
setResult(RESULT_OK);
finish();
}
}
#Override
public void onErrorResponse(Exception exception) {
Toast.makeText(this, R.string.create_account_error, Toast.LENGTH_SHORT).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case REQUEST_CODE_SELECT_PICTURE:
boolean isCamera;
if (data == null) {
isCamera = true;
} else {
String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
if (isCamera) {
startCropImage(Uri.fromFile(rawImageFile));
} else {
startCropImage(data == null ? null : data.getData());
}
break;
case REQUEST_CODE_CROP_IMAGE:
Bitmap bitmap = BitmapFactory.decodeFile(avatarImageFile.getAbsolutePath());
RoundedBitmapDrawable drawable = RoundedBitmapDrawableFactory.create(getResources(), bitmap);
drawable.setCircular(true);
uploadAvatarButton.setImageDrawable(drawable);
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void startCropImage(Uri source) {
if (source != null) {
int size = getResources().getDimensionPixelSize(R.dimen.default_avatar_size);
CropImageIntentBuilder cropImage = new CropImageIntentBuilder(size, size, Uri.fromFile(avatarImageFile));
cropImage.setSourceImage(source);
startActivityForResult(cropImage.getIntent(this), REQUEST_CODE_CROP_IMAGE);
}
}
private byte[] getAvatarBytes() {
if (!avatarImageFile.exists()) return null;
InputStream inputStream = null;
try {
inputStream = new FileInputStream(avatarImageFile);
} catch (FileNotFoundException e) {
AppLog.e("avatar file not found", e);
}
byte[] buffer = new byte[1024];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
return output.toByteArray();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (signupTask != null) {
signupTask.dismissDialogAndCancel();
}
}
}
SignupTaskActivity as follows:
public class SignupTask extends BaseAsyncTask<Void, Void, Boolean> {
private String user;
private String name;
private String password;
private byte[] avatar;
private ProgressDialog dialog;
public SignupTask(Listener<Boolean> listener, Context context, String user, String password, String name, byte[] avatar) {
super(listener, context);
this.user = user;
this.name = name;
this.password = password;
this.avatar = avatar;
dialog = ProgressDialog.show(context, null, context.getResources().getString(R.string.signup));
}
#Override
public Response<Boolean> doInBackground(Void... params) {
Context context = getContext();
if (context != null) {
try {
SmackHelper.getInstance(context).signupAndLogin(user, password, name, avatar);
if (avatar != null) {
ImageCache.addAvatarToFile(context, user, BitmapFactory.decodeByteArray(avatar, 0, avatar.length));
}
PreferenceUtils.setLoginUser(context, user, password, name);
return Response.success(true);
} catch(SmackInvocationException e) {
AppLog.e(String.format("sign up error %s", e.toString()), e);
return Response.error(e);
}
}
return null;
}
#Override
protected void onPostExecute(Response<Boolean> response) {
dismissDialog();
super.onPostExecute(response);
}
#Override
protected void onCancelled() {
super.onCancelled();
dismissDialog();
}
public void dismissDialog() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
public void dismissDialogAndCancel() {
dismissDialog();
cancel(false);
}
}
SmackHelper class as follows:
public class SmackHelper {
private static final String LOG_TAG = "SmackHelper";
private static final int PORT = 5222;
public static final String RESOURCE_PART = "Smack";
private XMPPConnection con;
private ConnectionListener connectionListener;
private Context context;
private State state;
private PacketListener messagePacketListener;
private PacketListener presencePacketListener;
private SmackAndroid smackAndroid;
private static SmackHelper instance;
private SmackContactHelper contactHelper;
private SmackVCardHelper vCardHelper;
private FileTransferManager fileTransferManager;
private PingManager pingManager;
private long lastPing = new Date().getTime();
public static final String ACTION_CONNECTION_CHANGED = "com.mstr.letschat.intent.action.CONNECTION_CHANGED";
public static final String EXTRA_NAME_STATE = "com.mstr.letschat.State";
private SmackHelper(Context context) {
this.context = context;
smackAndroid = SmackAndroid.init(context);
messagePacketListener = new MessagePacketListener(context);
presencePacketListener = new PresencePacketListener(context);
SmackConfiguration.setDefaultPacketReplyTimeout(20 * 1000);
Roster.setDefaultSubscriptionMode(SubscriptionMode.manual);
ProviderManager.addExtensionProvider(UserLocation.ELEMENT_NAME, UserLocation.NAMESPACE, new LocationMessageProvider());
}
public static synchronized SmackHelper getInstance(Context context) {
if (instance == null) {
instance = new SmackHelper(context.getApplicationContext());
}
return instance;
}
public void setState(State state) {
if (this.state != state) {
Log.d(LOG_TAG, "enter state: " + state.name());
this.state = state;
}
}
public void signupAndLogin(String user, String password, String nickname, byte[] avatar) throws SmackInvocationException {
connect();
Map<String, String> attributes = new HashMap<String, String>();
attributes.put("name", nickname);
try {
AccountManager.getInstance(con).createAccount(user, password, attributes);
} catch (Exception e) {
throw new SmackInvocationException(e);
}
login(user, password);
vCardHelper.save(nickname, avatar);
}
public void sendChatMessage(String to, String body, PacketExtension packetExtension) throws SmackInvocationException {
Message message = new Message(to, Message.Type.chat);
message.setBody(body);
if (packetExtension != null) {
message.addExtension(packetExtension);
}
try {
con.sendPacket(message);
} catch (NotConnectedException e) {
throw new SmackInvocationException(e);
}
}
public List<RosterEntry> getRosterEntries() {
List<RosterEntry> result = new ArrayList<RosterEntry>();
Roster roster = con.getRoster();
Collection<RosterGroup> groups = roster.getGroups();
for (RosterGroup group : groups) {
result.addAll(group.getEntries());
}
return result;
}
and finally my menifest file
public UserProfile search(String username) throws SmackInvocationException {
String name = StringUtils.parseName(username);
String jid = null;
if (name == null || name.trim().length() == 0) {
jid = username + "#" + con.getServiceName();
} else {
jid = StringUtils.parseBareAddress(username);
}
if (vCardHelper == null) {
return null;
}
VCard vCard = vCardHelper.loadVCard(jid);
String nickname = vCard.getNickName();
return nickname == null ? null : new UserProfile(jid, vCard);
}
public String getNickname(String jid) throws SmackInvocationException {
VCard vCard = vCardHelper.loadVCard(jid);
return vCard.getNickName();
}
private void connect() throws SmackInvocationException {
if (!isConnected()) {
setState(State.CONNECTING);
if (con == null) {
con = createConnection();
}
try {
con.connect();
}catch (SmackException.NoResponseException er){
Log.e(LOG_TAG,"Norespponse exception");
}
catch(Exception e) {
Log.e(LOG_TAG, String.format("Unhandled exception %s", e.toString()), e);
startReconnectIfNecessary();
throw new SmackInvocationException(e);
}
}
}
#SuppressLint("TrulyRandom")
private XMPPConnection createConnection() {
ConnectionConfiguration config = new ConnectionConfiguration(PreferenceUtils.getServerHost(context), PORT);
SSLContext sc = null;
MemorizingTrustManager mtm = null;
try {
mtm = new MemorizingTrustManager(context);
sc = SSLContext.getInstance("TLS");
sc.init(null, new X509TrustManager[] { mtm }, new SecureRandom());
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
} catch (KeyManagementException e) {
throw new IllegalStateException(e);
}
config.setCustomSSLContext(sc);
config.setHostnameVerifier(mtm.wrapHostnameVerifier(new org.apache.http.conn.ssl.StrictHostnameVerifier()));
config.setSecurityMode(SecurityMode.required);
config.setReconnectionAllowed(false);
config.setSendPresence(false);
config.setSecurityMode(SecurityMode.disabled);
List<HostAddress> list = config.getHostAddresses();
boolean data = config.isSendPresence();
return new XMPPTCPConnection(config);
}
public void cleanupConnection() {
if (con != null) {
con.removePacketListener(messagePacketListener);
con.removePacketListener(presencePacketListener);
if (connectionListener != null) {
con.removeConnectionListener(connectionListener);
}
}
if (isConnected()) {
try {
con.disconnect();
} catch (NotConnectedException e) {}
}
}
private void onConnectionEstablished() {
if (state != State.CONNECTED) {
//processOfflineMessages();
try {
con.sendPacket(new Presence(Presence.Type.available));
} catch (NotConnectedException e) {}
contactHelper = new SmackContactHelper(context, con);
vCardHelper = new SmackVCardHelper(context, con);
fileTransferManager = new FileTransferManager(con);
OutgoingFileTransfer.setResponseTimeout(30000);
addFileTransferListener();
pingManager = PingManager.getInstanceFor(con);
pingManager.registerPingFailedListener(new PingFailedListener() {
#Override
public void pingFailed() {
// Note: remember that maybeStartReconnect is called from a different thread (the PingTask) here, it may causes synchronization problems
long now = new Date().getTime();
if (now - lastPing > 30000) {
Log.e(LOG_TAG, "Ping failure, reconnect");
startReconnectIfNecessary();
lastPing = now;
} else {
Log.e(LOG_TAG, "Ping failure reported too early. Skipping this occurrence.");
}
}
});
con.addPacketListener(messagePacketListener, new MessageTypeFilter(Message.Type.chat));
con.addPacketListener(presencePacketListener, new PacketTypeFilter(Presence.class));
con.addConnectionListener(createConnectionListener());
setState(State.CONNECTED);
broadcastState(State.CONNECTED);
MessageService.reconnectCount = 0;
}
}
private void broadcastState(State state) {
Intent intent = new Intent(ACTION_CONNECTION_CHANGED);
intent.putExtra(EXTRA_NAME_STATE, state.toString());
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
public void login(String username, String password) throws SmackInvocationException {
connect();
try {
if (!con.isAuthenticated()) {
con.login(username, password, RESOURCE_PART);
}
onConnectionEstablished();
} catch(Exception e) {
SmackInvocationException exception = new SmackInvocationException(e);
// this is caused by wrong username/password, do not reconnect
if (exception.isCausedBySASLError()) {
cleanupConnection();
} else {
startReconnectIfNecessary();
}
throw exception;
}
}
public String getLoginUserNickname() throws SmackInvocationException {
try {
return AccountManager.getInstance(con).getAccountAttribute("name");
} catch (Exception e) {
throw new SmackInvocationException(e);
}
}
private void processOfflineMessages() {
Log.i(LOG_TAG, "Begin retrieval of offline messages from server");
OfflineMessageManager offlineMessageManager = new OfflineMessageManager(con);
try {
if (!offlineMessageManager.supportsFlexibleRetrieval()) {
Log.d(LOG_TAG, "Offline messages not supported");
return;
}
List<Message> msgs = offlineMessageManager.getMessages();
for (Message msg : msgs) {
Intent intent = new Intent(MessageService.ACTION_MESSAGE_RECEIVED, null, context, MessageService.class);
intent.putExtra(MessageService.EXTRA_DATA_NAME_FROM, StringUtils.parseBareAddress(msg.getFrom()));
intent.putExtra(MessageService.EXTRA_DATA_NAME_MESSAGE_BODY, msg.getBody());
context.startService(intent);
}
offlineMessageManager.deleteMessages();
} catch (Exception e) {
Log.e(LOG_TAG, "handle offline messages error ", e);
}
Log.i(LOG_TAG, "End of retrieval of offline messages from server");
}
private ConnectionListener createConnectionListener() {
connectionListener = new ConnectionListener() {
#Override
public void authenticated(XMPPConnection arg0) {}
#Override
public void connected(XMPPConnection arg0) {}
#Override
public void connectionClosed() {
Log.e(LOG_TAG, "connection closed");
}
#Override
public void connectionClosedOnError(Exception arg0) {
// it may be due to network is not available or server is down, update state to WAITING_TO_CONNECT
// and schedule an automatic reconnect
Log.e(LOG_TAG, "connection closed due to error ", arg0);
startReconnectIfNecessary();
}
#Override
public void reconnectingIn(int arg0) {}
#Override
public void reconnectionFailed(Exception arg0) {}
#Override
public void reconnectionSuccessful() {}
};
return connectionListener;
}
private void startReconnectIfNecessary() {
cleanupConnection();
setState(State.WAITING_TO_CONNECT);
if (NetworkUtils.isNetworkConnected(context)) {
context.startService(new Intent(MessageService.ACTION_RECONNECT, null, context, MessageService.class));
}
}
private boolean isConnected() {
return con != null && con.isConnected();
}
public void onNetworkDisconnected() {
setState(State.WAITING_FOR_NETWORK);
}
public void requestSubscription(String to, String nickname) throws SmackInvocationException {
contactHelper.requestSubscription(to, nickname);
}
public void approveSubscription(String to, String nickname, boolean shouldRequest) throws SmackInvocationException {
contactHelper.approveSubscription(to);
if (shouldRequest) {
requestSubscription(to, nickname);
}
}
public void delete(String jid) throws SmackInvocationException {
contactHelper.delete(jid);
}
public String loadStatus() throws SmackInvocationException {
if (vCardHelper == null) {
throw new SmackInvocationException("server not connected");
}
return vCardHelper.loadStatus();
}
public VCard loadVCard(String jid) throws SmackInvocationException {
if (vCardHelper == null) {
throw new SmackInvocationException("server not connected");
}
return vCardHelper.loadVCard(jid);
}
public VCard loadVCard() throws SmackInvocationException {
if (vCardHelper == null) {
throw new SmackInvocationException("server not connected");
}
return vCardHelper.loadVCard();
}
public void saveStatus(String status) throws SmackInvocationException {
if (vCardHelper == null) {
throw new SmackInvocationException("server not connected");
}
vCardHelper.saveStatus(status);
contactHelper.broadcastStatus(status);
}
public SubscribeInfo processSubscribe(String from) throws SmackInvocationException {
SubscribeInfo result = new SubscribeInfo();
RosterEntry rosterEntry = contactHelper.getRosterEntry(from);
ItemType rosterType = rosterEntry != null ? rosterEntry.getType() : null;
if (rosterEntry == null || rosterType == ItemType.none) {
result.setType(SubscribeInfo.TYPE_WAIT_FOR_APPROVAL);
result.setNickname(getNickname(from));
} else if (rosterType == ItemType.to) {
result.setType(SubscribeInfo.TYPE_APPROVED);
result.setNickname(rosterEntry.getName());
approveSubscription(from, null, false);
}
result.setFrom(from);
return result;
}
public void sendImage(File file, String to) throws SmackInvocationException {
if (fileTransferManager == null || !isConnected()) {
throw new SmackInvocationException("server not connected");
}
String fullJid = to + "/" + RESOURCE_PART;
OutgoingFileTransfer transfer = fileTransferManager.createOutgoingFileTransfer(fullJid);
try {
transfer.sendFile(file, file.getName());
} catch (SmackException e) {
Log.e(LOG_TAG, "send file error");
throw new SmackInvocationException(e);
}
while(!transfer.isDone()) {
if(transfer.getStatus().equals(Status.refused) || transfer.getStatus().equals(Status.error)
|| transfer.getStatus().equals(Status.cancelled)){
throw new SmackInvocationException("send file error, " + transfer.getError());
}
}
Log.d(LOG_TAG, "send file status: " + transfer.getStatus());
if(transfer.getStatus().equals(Status.refused) || transfer.getStatus().equals(Status.error)
|| transfer.getStatus().equals(Status.cancelled)){
throw new SmackInvocationException("send file error, " + transfer.getError());
}
}
private void addFileTransferListener() {
fileTransferManager.addFileTransferListener(new FileTransferListener() {
public void fileTransferRequest(final FileTransferRequest request) {
new Thread() {
#Override
public void run() {
IncomingFileTransfer transfer = request.accept();
String fileName = String.valueOf(System.currentTimeMillis());
File file = new File(FileUtils.getReceivedImagesDir(context), fileName + FileUtils.IMAGE_EXTENSION);
try {
transfer.recieveFile(file);
} catch (SmackException e) {
Log.e(LOG_TAG, "receive file error", e);
return;
}
while (!transfer.isDone()) {
if(transfer.getStatus().equals(Status.refused) || transfer.getStatus().equals(Status.error)
|| transfer.getStatus().equals(Status.cancelled)){
Log.e(LOG_TAG, "receive file error, " + transfer.getError());
return;
}
}
// start service to save the image to sqlite
if (transfer.getStatus().equals(Status.complete)) {
Intent intent = new Intent(MessageService.ACTION_MESSAGE_RECEIVED, null, context, MessageService.class);
intent.putExtra(MessageService.EXTRA_DATA_NAME_FROM, StringUtils.parseBareAddress(request.getRequestor()));
intent.putExtra(MessageService.EXTRA_DATA_NAME_MESSAGE_BODY, context.getString(R.string.image_message_body));
intent.putExtra(MessageService.EXTRA_DATA_NAME_FILE_PATH, file.getAbsolutePath());
intent.putExtra(MessageService.EXTRA_DATA_NAME_TYPE, ChatMessageTableHelper.TYPE_INCOMING_IMAGE);
context.startService(intent);
}
}
}.start();
}
});
}
public void onDestroy() {
cleanupConnection();
smackAndroid.onDestroy();
}
public static enum State {
CONNECTING,
CONNECTED,
DISCONNECTED,
// this is a state that client is trying to reconnect to server
WAITING_TO_CONNECT,
WAITING_FOR_NETWORK;
}
}
but i could not found any progress.please help me out. thanks in advance.
After struggle i found solution of this kind of problem. we need to do server side changes like:
step1:
step2:
step3:
after doing all these steps we will able to register new user on ejabberd server.

Azure mobile service for android query table

I'm using azure sdk for android and follow the tutorial https://azure.microsoft.com/en-us/documentation/articles/mobile-services-dotnet-backend-android-get-started-data/.
When I'm trying to connect and insert data to mobile service table all is ok, but when I query the table in activity my app gets stuck, though there are only several entries in the table and execute method successfully returns Future.
public static MobileServiceClient mClient;
public static void connect(Context context) {
try {
mClient = new MobileServiceClient(storageLink, key, context);
} catch (MalformedURLException e) {
Log.e("AzureService.connect", "Storage access failed" + storageLink);
}
}
public static InstallationData get(final String deviceId) {
MobileServiceTable<InstallationData> table= mClient.getTable(InstallationData.class);
final MobileServiceList<InstallationData> result;
try {
result = table.where().field("deviceid").eq(deviceId).execute().get();
for (InstallationData item : result) {
return item;
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return null;
}
public static void store(final InstallationData item) {
mClient.getTable(InstallationData.class).insert(item, new TableOperationCallback<InstallationData>() {
public void onCompleted(InstallationData entity, Exception exception, ServiceFilterResponse response) {
if (exception == null) {
Log.d("AzureService.store()", "Data about " + item.getDeviceid() + "" + "is successfully updated");
} else {
exception.printStackTrace();
Log.e("AzureService.store()", "Data about " + item.getDeviceid() + "" + "is failed to update");
}
}
});
}
Thank you in advance!

How to test my dbmanager class in android?

In my android app I am using ormlite. Now I want to create some testcases for the db helper methods. I do not know how this should work properly. The database need to be created in my testcase before the concrete test can start. For example I want to test if a user will be created as expected. For this I have a addUser Method which should be tested, but how can this be done?
Currently I created a TestProject with a TestCase for my DBManager-Class.
Here is my DBHelper class
public class DBHelper extends OrmLiteSqliteOpenHelper{
private static final String DATABASE_NAME = "pdixattach.db";
private static final int DATABASE_VERSION = 4;
private static final String TAG = DBHelper.class.getSimpleName();
private static DBHelper _helperInstance;
private Dao<Attachment, Integer> attachmentDao = null;
private Dao<User, Integer> userDao = null;
private Dao<Comment, Integer> commentDao = null;
private Dao<Job, Integer> jobDao = null;
private Dao<Target, Integer> targetDao = null;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db, ConnectionSource source) {
Log.i(TAG, "onCreate");
try{
dropTables(source);
TableUtils.createTable(source, Attachment.class);
TableUtils.createTable(source, User.class);
TableUtils.createTable(source, Comment.class);
TableUtils.createTable(source, Target.class);
TableUtils.createTable(source, Job.class);
TableUtils.createTable(source, ConfigurationParameter.class);
} catch (Exception e){
Log.e(TAG, "error while creating tables " + e.getMessage());
throw new RuntimeException(e);
}
}
#Override
public void onUpgrade(final SQLiteDatabase db, final ConnectionSource connectionSource, final int oldVersion, final int newVersion) {
Log.i(TAG, "onUpgrade");
try {
dropTables(connectionSource);
onCreate(db, connectionSource);
} catch (SQLException e) {
Log.e(TAG, "error while upgrading tables " + e.getMessage());
throw new RuntimeException(e);
}
// after we drop the old databases, we create the new ones
onCreate(db, connectionSource);
}
private void dropTables(final ConnectionSource connectionSource)
throws SQLException {
TableUtils.dropTable(connectionSource, Attachment.class, true);
TableUtils.dropTable(connectionSource, User.class, true);
TableUtils.dropTable(connectionSource, Target.class, true);
TableUtils.dropTable(connectionSource, Job.class, true);
TableUtils.dropTable(connectionSource, Comment.class, true);
TableUtils.dropTable(connectionSource, ConfigurationParameter.class, true);
}
public Dao<Attachment, Integer> getAttachmentDao() throws SQLException {
if (this.attachmentDao == null) {
this.attachmentDao = getDao(Attachment.class);
}
return this.attachmentDao;
}
public Dao<User, Integer> getUserDao() throws SQLException {
if (this.userDao == null) {
this.userDao = getDao(User.class);
}
return this.userDao;
}
public Dao<Comment, Integer> getCommentDao() throws SQLException {
if (this.commentDao == null) {
this.commentDao = getDao(Comment.class);
}
return this.commentDao;
}
public Dao<Target, Integer> getTargetDao() throws SQLException {
if (this.targetDao == null) {
this.targetDao = getDao(Target.class);
}
return this.targetDao;
}
public Dao<Job, Integer> getJobDao() throws SQLException {
if (this.jobDao == null) {
this.jobDao = getDao(Job.class);
}
return this.jobDao;
}
/**
* Close the database connections and clear any cached DAOs.
*/
#Override
public void close() {
super.close();
_helperInstance = null;
this.attachmentDao = null;
this.commentDao = null;
this.jobDao = null;
this.targetDao = null;
this.userDao = null;
}
}
and my DBManager which I want to test, for example the storeUser Method
public class DBManager {
private DBHelper helper;
private static DBManager uniqueInstance;
private static final String TAG = DBManager.class.getSimpleName();
public DBManager(Context context) {
helper = new DBHelper(context);
}
public static void init(Context context) {
if (uniqueInstance == null) {
uniqueInstance = new DBManager(context);
}
}
public static DBManager getInstance() {
return uniqueInstance;
}
public boolean addUser(User u) {
boolean retVal = false;
if (u == null) {
throw new IllegalArgumentException("user must not be null");
}
try {
helper.getUserDao().create(u);
retVal = true;
} catch (SQLException e) {
Log.e(TAG, "error while adding user to db " + e.getMessage());
}
return retVal;
}
public boolean addServiceEndpoint(String endpoint) {
Log.d(TAG, "adding Service Endpoint " + endpoint);
boolean retVal = false;
if (endpoint == null) {
throw new IllegalArgumentException("endpoint must not be null");
}
try {
Target t = new Target(endpoint);
int result = helper.getTargetDao().create(t);
Log.d(TAG, "creating target entry resulted with value " + result);
retVal = (result == 1);
} catch (SQLException e) {
Log.e(TAG,"error while adding target to db, with service endpoint " + endpoint + "error" + e.getMessage());
}
return retVal;
}
public List<Target> getAllTargets() {
List<Target> retVal = new ArrayList<Target>();
try {
retVal = helper.getTargetDao().queryForAll();
} catch (SQLException e) {
Log.e(TAG,
"error while retrieving service endpoints, error" + e.getMessage());
}
return retVal;
}
public User storeUser(String username, String hashedPw, Target target,
boolean storeLogin) {
User loggedInUser = null;
int loginState = (storeLogin) ? 1 : 0;
if (username == null || hashedPw == null || target == null) {
throw new IllegalArgumentException(
"cannot store login with empty/null values");
}
try {
QueryBuilder<User, Integer> queryBuilder = helper.getUserDao().queryBuilder();
Where<User, Integer> where = queryBuilder.where();
where.eq(User.USERNAME, username)
.and().eq(User.TARGET_ID, target.getServiceEndpoint());
PreparedQuery<User> prepareStmt = queryBuilder.prepare();
List<User> userList = helper.getUserDao().query(prepareStmt);
if (userList.isEmpty()) {
Log.d(TAG, "no user found with this name in the db, need to store it");
User newUser = new User(username, hashedPw, target);
newUser.setStored(loginState);
addUser(newUser);
userList = helper.getUserDao().query(prepareStmt);
loggedInUser = userList.get(0);
} else {
Log.d(TAG, "found at least one user with username " + username + " target " + target);
for (User u : userList) {
if (u.getPassword().equals(hashedPw)) {
Log.d(TAG, "password is equal to the one in db");
}
else {
u.setPassword(hashedPw);
}
// setze diesen User als aktiv!
u.setStatus(1);
u.setStored(loginState);
helper.getUserDao().update(u);
loggedInUser = u;
}
}
} catch (SQLException e) {
Log.d(TAG, "error while storing login" + e.getMessage());
}
return loggedInUser;
}
public Comment addComment(Comment cmt) {
Comment retVal = null;
if (cmt == null) {
throw new IllegalArgumentException("cannot create a comment entry in database without comment");
}
try {
retVal = helper.getCommentDao().createIfNotExists(cmt);
} catch (SQLException e) {
e.printStackTrace();
}
return retVal;
}
public Attachment addAttachment(Attachment att) {
if (att == null) {
throw new IllegalArgumentException(
"cannot create attachment entry in database without attachment");
}
Attachment dbAttach = null;
try {
dbAttach = helper.getAttachmentDao().createIfNotExists(att);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dbAttach;
}
public Job addJob(Job job) {
Job dbJob = null;
if (job == null) {
throw new IllegalArgumentException(
"no job given, cannot create an entry");
}
try {
QueryBuilder<Job, Integer> queryBuilder = helper.getJobDao()
.queryBuilder();
Where<Job, Integer> where = queryBuilder.where();
if (job.getInstanceId() == null)
where.isNull(Job.INSTANCE_ID);
else
where.eq(Job.INSTANCE_ID, job.getInstanceId());
where.and().eq(Job.COMMENT_ID, job.getComment().getComment()).and()
.eq(Job.ATTACH_ID, job.getAtach().getAttUri()).and()
.eq(Job.STATUS, "0").and()
.eq(Job.TARGET_ID, job.getTarget().getServiceEndpoint());
PreparedQuery<Job> prepareStmt = queryBuilder.prepare();
Log.d(TAG, "querystring is " + prepareStmt.getStatement());
List<Job> jobList = helper.getJobDao().query(prepareStmt);
if (jobList.isEmpty()) {
Log.d(TAG, "no job with these parameters given, need to create one");
Log.d(TAG, "job id is " + job.getId());
dbJob = helper.getJobDao().createIfNotExists(job);
Log.d(TAG, "dbJob id is " + dbJob.getId());
} else {
Log.d(TAG,
"job does already exists for this parameters, wont create new");
dbJob = jobList.get(0);
// hier comment und status usw updaten
}
} catch (SQLException e) {
Log.d(TAG, "Exception during adding a job to db: " + e.getMessage());
}
return dbJob;
}
public void attachInstanceIdToJob(String instanceId, long jobId) {
Log.d(TAG, "attaching instance id " + instanceId + " to job with id " + jobId);
try {
Job job = helper.getJobDao().queryForId((int) jobId);
if (job != null){
job.setInstanceId(instanceId);
helper.getJobDao().update(job);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
Log.d(TAG, "error while attaching instance id " + instanceId + " to job with id " + jobId);
}
}
public List<Job> getAllOpenJobs() {
List<Job> jobList = null;
QueryBuilder<Job, Integer> queryBuilder;
try {
queryBuilder = helper.getJobDao()
.queryBuilder();
Where<Job, Integer> where = queryBuilder.where();
where.eq(Job.STATUS, JobStatusEnum.OPEN.getState())
.or().eq(Job.STATUS, JobStatusEnum.RETRY.getState());
;
PreparedQuery<Job> prepareStmt = queryBuilder.prepare();
Log.d(TAG, "querystring is " + prepareStmt.getStatement());
jobList = helper.getJobDao().query(prepareStmt);
} catch (SQLException e) {
Log.d(TAG, "error while retrieving open jobs from db" + e.getMessage());
}
return jobList;
}
public void getDataForJob(Job j, User u, Attachment att, Target target, Comment comment) {
try {
if (j != null){
helper.getUserDao().refresh(j.getUser());
helper.getAttachmentDao().refresh(j.getAtach());
helper.getTargetDao().refresh(j.getTarget());
helper.getCommentDao().refresh(j.getComment());
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public User getCurrentStoredUser(){
try {
List<User> users = helper.getUserDao().queryForAll();
for (User u: users){
if (u.getStored() == 1){
return u;
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public void updateJob(Job j) {
if (j != null){
try {
helper.getJobDao().update(j);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* The status of the given user will be configured to stored. All others will be set to unstored
* #param loggedInUser
*/
public void setUserStatusToStored(User loggedInUser) {
List<User> listOfUsers;
try {
listOfUsers = helper.getUserDao().queryForAll();
for (User u: listOfUsers){
if (u.equals(loggedInUser)){
u.setStatus(UserStatusEnum.STORED.getState());
}
else{
u.setStatus(UserStatusEnum.UNSTORED.getState());
}
helper.getUserDao().update(u);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and my TestClass
public class DBManagerTest
extends TestCase
{
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void testDBManager() {
fail( "Not yet implemented" );
}
}
Can someone help me with shat, I guess once the first test is running the others should be clear.
Thanks

How to generate TestCases for ORMLite-Database classes in Android Development

I am working on my database layer for my android app, I would like to use testcases for this but I do not know how to solve this in android development envrionement.
I have this DBHelper class
public class DBHelper extends OrmLiteSqliteOpenHelper{
private static final String DATABASE_NAME = "pdixattach.db";
private static final int DATABASE_VERSION = 1;
private static final String TAG = DBHelper.class.getSimpleName();
private static DBHelper _helperInstance;
private Dao<Attachment, Integer> attachmentDao = null;
private Dao<User, Integer> userDao = null;
private Dao<Comment, Integer> commentDao = null;
private Dao<Job, Integer> jobDao = null;
private Dao<Target, Integer> targetDao = null;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db, ConnectionSource source) {
Log.i(TAG, "onCreate");
try{
TableUtils.createTable(source, Attachment.class);
TableUtils.createTable(source, User.class);
TableUtils.createTable(source, Comment.class);
TableUtils.createTable(source, Target.class);
TableUtils.createTable(source, Job.class);
} catch (Exception e){
Log.e(TAG, "error while creating tables " + e.getMessage());
throw new RuntimeException(e);
}
}
#Override
public void onUpgrade(final SQLiteDatabase db, final ConnectionSource connectionSource, final int oldVersion, final int newVersion) {
Log.i(TAG, "onUpgrade");
try {
TableUtils.dropTable(connectionSource, Attachment.class, true);
TableUtils.dropTable(connectionSource, User.class, true);
TableUtils.dropTable(connectionSource, Target.class, true);
TableUtils.dropTable(connectionSource, Job.class, true);
TableUtils.dropTable(connectionSource, Comment.class, true);
} catch (SQLException e) {
Log.e(TAG, "error while upgrading tables " + e.getMessage());
throw new RuntimeException(e);
}
// after we drop the old databases, we create the new ones
onCreate(db, connectionSource);
}
public Dao<Attachment, Integer> getAttachmentDao() throws SQLException {
if (this.attachmentDao == null) {
this.attachmentDao = getDao(Attachment.class);
}
return this.attachmentDao;
}
public Dao<User, Integer> getUserDao() throws SQLException {
if (this.userDao == null) {
this.userDao = getDao(User.class);
}
return this.userDao;
}
public Dao<Comment, Integer> getCommentDao() throws SQLException {
if (this.commentDao == null) {
this.commentDao = getDao(User.class);
}
return this.commentDao;
}
public Dao<Target, Integer> getTargetDao() throws SQLException {
if (this.targetDao == null) {
this.targetDao = getDao(User.class);
}
return this.targetDao;
}
public Dao<Job, Integer> getJobDao() throws SQLException {
if (this.jobDao == null) {
this.jobDao = getDao(User.class);
}
return this.jobDao;
}
/**
* Close the database connections and clear any cached DAOs.
*/
#Override
public void close() {
super.close();
_helperInstance = null;
this.attachmentDao = null;
this.commentDao = null;
this.jobDao = null;
this.targetDao = null;
this.userDao = null;
}
With this DBManager:
public class DBManager {
private Dao<User,Integer> userDao;
private Dao<Attachment,Integer> attachmentDao;
private Dao<Target,Integer> targetDao;
private Dao<Comment,Integer> commentDao;
private Dao<Job,Integer> jobDao;
private DBHelper helper;
private static DBManager uniqueInstance;
private static final String TAG = DBManager.class.getSimpleName();
public DBManager(Context context) {
helper = new DBHelper(context);
}
public static void init(Context context){
if (uniqueInstance == null) {
uniqueInstance = new DBManager(context);
}
}
public static synchronized DBManager getInstance(){
return uniqueInstance;
}
private void injectDBHelper(DBHelper dbhelper) {
if (this.helper == null)
this.helper = dbhelper;
else
Log.d(TAG, "DBHelper already available in DBManager");
}
public boolean addUser(User u){
boolean retVal = false;
if (u == null){
throw new IllegalArgumentException("user must not be null");
}
try {
helper.getUserDao().create(u);
retVal = true;
} catch (SQLException e) {
Log.e(TAG, "error while adding user to db " + e.getMessage());
}
return retVal;
}
public boolean addServiceEndpoint(String endpoint) {
boolean retVal = false;
if (endpoint == null){
throw new IllegalArgumentException("endpoint must not be null");
}
try {
Target t = new Target(endpoint);
int result = helper.getTargetDao().create(t);
retVal = (result == 1);
} catch (SQLException e) {
Log.e(TAG, "error while adding target to db, with service endpoint " + endpoint + "error" + e.getMessage());
}
return retVal;
}
I want to generate testcase for the addUser method, can someone help me with that. How can I achieve this in android development envrionment?
Thanks

create / open database after closing

In my app, after user logs in, database is created. When user logs out, I have to delete the database from the internal storage to save space. The problem is, after deleting the database and a user logs back in, database cannot be created anymore. I tried using .close() but it only makes the problem worse.
Here is my code.
DatabaseHelper
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final String DATABASE_PATH = "/mnt/sdcard/Philpost/databases/";
private static final String DATABASE_NAME = "DeliveriesDB.sqlite";
private static final int DATABASE_VERSION = 1;
// the DAO object we use to access the SimpleData table
private Dao<DeliveriesDB, Integer> DeliveriesDbDao = null;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database,
ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource, DeliveriesDB.class);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
throw new RuntimeException(e);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource,
int oldVersion, int newVersion) {
try {
Log.i(DatabaseHelper.class.getName(), "onUpgrade");
TableUtils.dropTable(connectionSource, DatabaseHelper.class, true);
onCreate(db, connectionSource);
} catch (java.sql.SQLException e) {
// TODO Auto-generated catch block
Log.e(DatabaseHelper.class.getName(), "Cant drop database", e);
e.printStackTrace();
}
}
public Dao<DeliveriesDB, Integer> getDeliveriesDbDao() {
if (null == DeliveriesDbDao) {
try {
DeliveriesDbDao = getDao(DeliveriesDB.class);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
return DeliveriesDbDao;
}
}
DatabaseManager
public class DatabaseManager {
static private DatabaseManager instance;
static public void init(Context ctx) {
if (null == instance) {
instance = new DatabaseManager(ctx);
}
}
static public DatabaseManager getInstance() {
return instance;
}
private DatabaseHelper helper;
public DatabaseManager(Context ctx) {
helper = new DatabaseHelper(ctx);
}
public DatabaseHelper getHelper(Context ctx) {
if(helper == null){
helper = OpenHelperManager.getHelper(ctx, DatabaseHelper.class);
}
return helper;
}
public void releaseDb(Context ctx) {
DatabaseConnection connect;
try {
connect = getHelper(ctx).getConnectionSource()
.getReadWriteConnection();
getHelper(ctx).getConnectionSource().releaseConnection(connect);
helper = null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void closeDb(){
helper.close();
}
public List<DeliveriesDB> getAllDeliveriesDB(Context ctx) {
List<DeliveriesDB> deliveriesdb = null;
try {
deliveriesdb = getHelper(ctx).getDeliveriesDbDao().queryForAll();
} catch (SQLException e) {
e.printStackTrace();
}
return deliveriesdb;
}
public void addDeliveriesDb(DeliveriesDB l, Context ctx) {
try {
getHelper(ctx).getDeliveriesDbDao().create(l);
} catch (SQLException e) {
e.printStackTrace();
}
}
public DeliveriesDB getDeliveriesDbWithId(int deliveriesDbId, Context ctx) {
DeliveriesDB deliveriesDb = null;
try {
deliveriesDb = getHelper(ctx).getDeliveriesDbDao().queryForId(
deliveriesDbId);
} catch (SQLException e) {
e.printStackTrace();
}
return deliveriesDb;
}
public void deleteDeliveriesDb(DeliveriesDB deliveriesDb, Context ctx) {
try {
getHelper(ctx).getDeliveriesDbDao().delete(deliveriesDb);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void refreshDeliveriesDb(DeliveriesDB deliveriesDb, Context ctx) {
try {
getHelper(ctx).getDeliveriesDbDao().refresh(deliveriesDb);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void updateDeliveriesDb(DeliveriesDB deliveriesDb, Context ctx) {
try {
getHelper(ctx).getDeliveriesDbDao().update(deliveriesDb);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
The class where creation and deletion of database happens
public class DeliveryListActivity extends ListActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DatabaseManager.init(this);
setContentView(R.layout.deliverylist_layout);
if (getLastNonConfigurationInstance() != null) {
deliveryIndex = (Integer) getLastNonConfigurationInstance();
}
if (PhilpostApplication.DELIVERIES == null) {
new RetrieveDeliveriesTask().execute();
} else {
updateCachedList(PhilpostApplication.DELIVERIES);
}
}
private void updateCachedList(List<Delivery> deliveries) {
File expath = context.getFilesDir();
String apppath = "/databases/DeliveriesDB.sqlite";
File path = new File(expath, apppath);
adapter = new DeliveryListAdapter(this,
R.layout.deliverylist_row_layout, deliveries);
setListAdapter(adapter);
PhilpostApplication.DELIVERIES = deliveries;
Log.d(TAG, "Updating UI list");
if (PhilpostApplication.firstDb) {
if (!path.exists()) {
createBackupDb();
Log.d(TAG, "DB first Creation");
}
}
}
public void createBackupDb() {
for (int i = 0; i < PhilpostApplication.DELIVERIES.size(); i++) {
// create db first
dId = PhilpostApplication.DELIVERIES.get(i).getId();
rId = PhilpostApplication.DELIVERIES.get(i).getRecipientId();
lastn = PhilpostApplication.DELIVERIES.get(i).getLastName();
firstn = PhilpostApplication.DELIVERIES.get(i).getFirstName();
addr = PhilpostApplication.DELIVERIES.get(i).getAddress();
dtype = PhilpostApplication.DELIVERIES.get(i).getType();
amount = PhilpostApplication.DELIVERIES.get(i).getCash();
pMan = PhilpostApplication.DELIVERIES.get(i).getPostman();
stats = PhilpostApplication.DELIVERIES.get(i).getStatus();
createNewDeliveriesDb(dId, rId, lastn, firstn, addr, dtype, amount,
pMan, stats);
keyNum[i] = PhilpostApplication.DELIVERIES.get(i).getId();
}
Log.d(TAG, "database created");
PhilpostApplication.firstDb = false;
}
public void logout() {
if (PhilpostApplication.listSynced == false) {
// if( checkIfSyncedList() ){
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Sync data first before logging out.")
.setCancelable(false).setPositiveButton("OK", null);
final AlertDialog alert = builder.create();
alert.show();
} else {
dialog = ProgressDialog.show(this, "Logging out", "please wait");
try {
WebService.logout();
PhilpostApplication.SESSION_KEY = null; // clear Application
// Session
// Key
AccountStore.clear(this);
// clear cached list
PhilpostApplication.DELIVERIES = null;
MemoryUtils.deleteCache(this);
PhilpostApplication.incompleteSync = false;
PhilpostApplication.loggedIn = false;
PhilpostApplication.firstDb = true;
DatabaseManager.getInstance().closeDb();
deleteInternalDb();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (PhilpostApplication.canToggleGPS) {
turnGpsOff();
}
dialog.dismiss();
exitActivity();
}
}
}
Deleting Database
public void deleteInternalDb() {
File internalDb = new File(
Environment.getDataDirectory()
+ "/data/packagename/databases/DeliveriesDB.sqlite");
if (internalDb.exists()) {
internalDb.delete();
Log.d(TAG, "Internal Db deleted");
}
}
Check the example here this will give you an idea how to use existing database.
when your getting response from db follow following formate. it work fine bcz i had face this problem.we must have close db in finally block try this it may help you.
try
{
//Query
}
catch
{
}
finally
{
c.close();
db.close();
}

Categories

Resources