Fetching image from SQLite database in android - android

I am unable to fetch the image from the database, please look at my databasehelper (that is my fetchimg(String i) and MainActivity (that is showmeth(View w)) class.
What I am actually doing here is firstly capturing the image with camera, then it is temporary pasted on 1st ImageView and after i click on save button it gets saved in the database(No problem yet). But when i click show button then it must show the image in a 2nd ImageView by taking reference id as a textview's id but it is not showing the image, that is showmeth(View w) unable to fetch the image from database.
My MainActivity
package com.example.expnewbutton;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private Uri fileUri;
Bitmap img;
TextView t1;
databasehelper helper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1 = (TextView) findViewById(R.id.text);
helper = new databasehelper(this);
}
public void cammethod(View w) {
try {
PackageManager packageManager = getPackageManager();
boolean doesHaveCamera = packageManager
.hasSystemFeature(PackageManager.FEATURE_CAMERA);
if (doesHaveCamera) {
// start the image capture Intent
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Get our fileURI
// fileUri = getOutputMediaFile();
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, 100);
}
} catch (Exception ex) {
Toast.makeText(getApplicationContext(),
"There was an error with the camera.", Toast.LENGTH_LONG)
.show();
}
}
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
if (intent == null) {
// The picture was taken but not returned
Toast.makeText(
getApplicationContext(),
"The picture was taken and is located here: "
+ fileUri.toString(), Toast.LENGTH_LONG)
.show();
} else {
// The picture was returned
Bundle extras = intent.getExtras();
img = (Bitmap) extras.get("data");
ImageView imageView1 = (ImageView) findViewById(R.id.imageView1);
imageView1.setImageBitmap((Bitmap) extras.get("data"));
}
}
}
}
public void insertimg(View w) {
long a = 0;
String id = t1.getText().toString();
try {
helper.deleterecord(id);
a = helper.insert(id, img);
if (a >= 1) {
Toast.makeText(getBaseContext(),
a + "Record Successfully Saved", 30).show();
} else {
Toast.makeText(getBaseContext(), "Not Saved", 30).show();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), "there is error", 5).show();
}
}
public void showmeth(View w) {
String i = null;
boolean flag = false;
i = t1.getText().toString();
try {
flag = helper.fetchimg(i);
} catch (Exception e) {
Toast.makeText(getBaseContext(), "database exception", 10).show();
}
if (flag == true) {
Toast.makeText(getBaseContext(),
"Here your image save on imageview", 10).show();
ImageView imageView2 = (ImageView) findViewById(R.id.imageView2);
imageView2.setImageBitmap(helper.bmp);
} else {
Toast.makeText(getBaseContext(), "Add a Pic first", 50).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
My Database File:
package com.example.expnewbutton;
import java.io.ByteArrayOutputStream;
import android.content.ContentValues;
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.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.util.Log;
public class databasehelper extends SQLiteOpenHelper {
final static String databasename = "Image";
final static int databaseversion = 1;
Bitmap bmp = null;
public databasehelper(Context ctx) {
super(ctx, databasename, null, databaseversion);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
Log.d("tag4545", "database");
db.execSQL("create table mypic(id text,pic BLOB)");
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if Exists mypic");
// db.execSQL("drop table if Exists emer");
onCreate(db);
}
public long insert(String id, Bitmap img) {
SQLiteDatabase base = getWritableDatabase();
byte[] data = getBitmapAsByteArray(img); // this is a function
ContentValues value = new ContentValues();
value.put("id", id);
value.put("pic", data);
long a = base.insert("mypic", null, value);
return a;
}
public static byte[] getBitmapAsByteArray(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray();
}
public boolean fetchimg(String i) {
SQLiteDatabase base = getReadableDatabase();
Cursor cs = null;
try {
cs = base.query("mypic", new String[] { "pic" }, "id=?",
new String[] { "i" }, null, null, null);
/*
* String qu= "select pic from mypic where id"+i;
*
* Cursor cs=null; try{ cs =base.rawQuery(qu, null); }
* catch(Exception e) { return false; }
*/
if (cs != null) {
cs.moveToFirst();
byte[] imgbyte = cs.getBlob(0);
cs.close();
bmp = BitmapFactory.decodeByteArray(imgbyte, 0, imgbyte.length);
return true;
}
else {
return false;
}
}
catch (Exception e) {
return false;
}
}
public void deleterecord(String pe_id) {
SQLiteDatabase base = getWritableDatabase();
base.delete("mypic", "id=?", new String[] { pe_id });
}
}
My xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/gb2"
tools:context=".MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText2"
android:layout_marginLeft="16dp"
android:layout_marginTop="32dp"
android:layout_toRightOf="#+id/textView2"
android:onClick="cammethod"
android:text="Cam" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button1"
android:layout_marginLeft="46dp"
android:layout_toRightOf="#+id/button1"
android:onClick="insertimg"
android:text="Save" />
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button2"
android:layout_alignParentRight="true"
android:layout_marginRight="22dp"
android:text="Photo"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text"
android:layout_toRightOf="#id/imageView1"
android:onClick="showmeth"
android:text="show" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/imageView1" />
</RelativeLayout>
Please help me in code, I need it soon. Thank you.
So the problem may be with database query(I tried query with both methods which i hidden or which is not hidden) or may be with using BLOB in my code. Please help me to find error

You are passing the string "i" where you need to pass the value of i.
You should change your query to:
cs = base.query("mypic", new String[] { "pic" }, "id=?",
new String[] { String.valueOf(i) }, null, null, null);

Related

Android: App stop when trying to get paired bluetooth device

When trying to get the list of the paired device, unexpected error occur that make my app stops. It is new for me to solve all these complex issues.
Here is my MainActivity.java:
package com.example.admin.bluetooth_demo;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private ListView lv;
private ArrayList<String> mDeviceList = new ArrayList<String>();
private BluetoothAdapter BA;
Button openbtn,closebtn,searchbtn,senbtn;
ArrayList<BluetoothDevice>mmPairedDevicesList;
BluetoothDevice mmDevice;
BluetoothSocket mmSocket;
EditText entry;
String msg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView)findViewById(R.id.list_devices);
openbtn = (Button)findViewById(R.id.button_open);
closebtn = (Button)findViewById(R.id.button_close);
searchbtn = (Button)findViewById(R.id.button_search);
senbtn = (Button)findViewById(R.id.button4);
entry = (EditText)findViewById(R.id.editText_entry);
msg = entry.getText().toString();
BA = BluetoothAdapter.getDefaultAdapter();
openbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(BA == null){
Toast.makeText(MainActivity.this,"No connection!!",Toast.LENGTH_LONG).show();
}else{
if(!BA.isEnabled()){
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Toast.makeText(getApplicationContext(), "Turned on",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Already on", Toast.LENGTH_LONG).show();
}
}
}
});
closebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BA.disable();
Toast.makeText(getApplicationContext(), "Turned off" ,Toast.LENGTH_LONG).show();
}
});
searchbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BA.startDiscovery();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver,filter);
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ConnectThread mConnectThread = new ConnectThread(mmPairedDevicesList.get(position));
mConnectThread.start();
}
});
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device.getName() + "\n" + device.getAddress());
mmPairedDevicesList.add(device);
Log.i("BT", device.getName() + "\n" + device.getAddress());
ArrayAdapter adp = new ArrayAdapter(context,android.R.layout.simple_list_item_1,mDeviceList);
lv.setAdapter(adp);
adp.notifyDataSetChanged();
}
}
};
public class ConnectThread extends Thread{
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public ConnectThread(BluetoothDevice device){
BluetoothSocket tmp = null;
mmDevice = device;
try{
tmp = device.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
e.printStackTrace();
}
mmSocket = tmp;
}
public void run(){
BA.cancelDiscovery();
try{
mmSocket.connect();
} catch (IOException e) {
try{
mmSocket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return;
}
final ConnectedThread mConnectedThread = new ConnectedThread(mmSocket);
mConnectedThread.start();
senbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
msg += "\n";
mConnectedThread.write(msg.getBytes());
Toast.makeText(MainActivity.this,"Data sent!!!",Toast.LENGTH_LONG).show();
}
});
}
public void cancel(){
try{
mmSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Here is ConnectedThread.java:
package com.example.admin.bluetooth_demo;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ConnectedThread extends Thread {
private BluetoothSocket mmBluetoothsocket;
private InputStream mInputStream;
private OutputStream mOutputStream;
public ConnectedThread(BluetoothSocket socket){
mmBluetoothsocket = socket;
InputStream tmpIN = null;
OutputStream tmpOUT = null;
try{
tmpIN = socket.getInputStream();
tmpOUT = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
mInputStream = tmpIN;
mOutputStream = tmpOUT;
}
public void run(){
byte[] buffer = new byte[1024];
int begin = 0;
int bytes = 0;
Handler mHandler = new Handler(){
#Override
public void handleMessage(Message msg){
byte [] writeBuff = (byte[]) msg.obj;
int begin = (int) msg.arg1;
int end = (int) msg.arg2;
switch(msg.what){
case 1:
String writeMessage = new String (writeBuff);
writeMessage = writeMessage.substring(begin,end);
break;
}
}
};
while(true){
try{
bytes += mInputStream.read(buffer, bytes, buffer.length-bytes);
for (int i = begin; i < bytes; i++){
if(buffer[i] == "#".getBytes()[0]){
mHandler.obtainMessage(1,begin,i,buffer).sendToTarget();
begin = i + 1;
if(i == bytes-1){
bytes = 0;
begin = 0;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write(byte[] bytes){
try{
mOutputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
public void cancel(){
try{
mmBluetoothsocket.close();
mOutputStream.close();
mInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is Main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.admin.bluetooth_demo.MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text="Type here:"
android:ems="10"
android:layout_above="#+id/button_open"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/editText_entry"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/list_devices"
android:layout_above="#+id/editText_entry"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:text="Open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button_open"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:text="Close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button_close"
android:layout_alignParentBottom="true"
android:layout_toRightOf="#+id/button_open"
android:layout_toEndOf="#+id/button_open" />
<Button
android:text="Send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button4"
android:layout_alignParentBottom="true"
android:layout_toRightOf="#+id/button_close"
android:layout_toEndOf="#+id/button_close" />
<Button
android:text="Search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button_search"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>

how to multiple image upload using intent service with update UI from service

I am android developer .I have face issue ANR when multiple image send in background using intent service.I have call service on Resume() method.I have update UI when step by step image upload finish .My all code in service .But i don't understand why my UI hang.I have created ResultReceiver class for Update UI. Please tell me what is wrong i am doing.
public class UploadImageService extends IntentService {
public static final int STATUS_RUNNING = 0;
public static final int STATUS_FINISHED = 1;
public static final int STATUS_ERROR = 2;
private static final String TAG = "UploadImageService";
public static String SHOW_MSG = "showMsg";
public static String SET_IN_ADAPTER = "setData";
public static String UPLOAD_IMAGE = "uploadImage";
public static String RESULT = "result";
private String threadType, toUser, chatThreadId, gcmRegistrationId, openCloseChatWindowType, recipientName, threadTopicName, attachmentID, attachmentType, currentChunks, originalBase64Img, dateTime, classType, loginUserId;
// Declare Web services variable
private MultipartEntity multipartEntityBuilder;
Database database;
Bundle bundle;
ResultReceiver receiver;
public UploadImageService() {
super(UploadImageService.class.getName());
}
#Override
protected void onHandleIntent(Intent intent) {
//initialize database
database = new Database(UploadImageService.this, Database.DATABASE_NAME, null, Database.DATABASE_VERSION);
Log.d(TAG, "Service Started!");
receiver = intent.getParcelableExtra("receiver");
try {
bundle = new Bundle();
/* Update UI: upload Service is Running */
//receiver.send(STATUS_RUNNING, Bundle.EMPTY);
try {
new UploadThumbImageAsync().execute();
} catch (Exception e) {
e.printStackTrace();
bundle.putString(Intent.EXTRA_TEXT, e.toString());
receiver.send(STATUS_ERROR, bundle);
}
/* new Thread(new Runnable(){
public void run() {
// TODO Auto-generated method stub
while(true)
{
try {
new UploadThumbImageAsync().execute();
} catch (Exception e) {
e.printStackTrace();
bundle.putString(Intent.EXTRA_TEXT, e.toString());
receiver.send(STATUS_ERROR, bundle);
}
}
}
}).start();*/
} catch (Exception e) {
e.printStackTrace();
}
Log.e(TAG, "Service Stopping!");
//this.stopSelf();
}
private class UploadThumbImageAsync extends AsyncTask<String, Void, String> {
/*this method is use for initializing dialog(ProgressDialog,CustomDialog) and showing*/
String toUser, comTypeId, threadType, chatThreadId, threadTopicName, chatAttachmentType, chatMessage, thumbBase64AttachmentPath /*original_image*/, loginUserName, recipientName, originalBase64Image, originalFilePath;
#Override
protected void onPreExecute() {
super.onPreExecute();
//showProgressDialog();
}
/*starts the loading of the data in background in doInBackground() method */
#Override
protected String doInBackground(String... params) {
try {
toUser = params[0];
comTypeId = params[1];
threadType = params[2];
chatThreadId = params[3];
threadTopicName = params[4];
chatAttachmentType = params[5];
chatMessage = params[6];
thumbBase64AttachmentPath = params[7];
loginUserName = params[8];
recipientName = params[9];
originalBase64Image = params[10];
originalFilePath = params[11];
String url;
if (!TextUtils.isEmpty(threadType) && threadType.equals(RecentChatList.SIMPLE_TYPE)) {
url = WS.URL.concat(WS.SAVE_CHAT);
} else {
url = WS.URL.concat(WS.GROUP_SAVE_CHAT);
}
Log.e(TAG, "url_" + chatMessage + " = " + url);
String response = HttpClientExecuteMethod.executeMultipartPostMethod(url, multipartEntityBuilder);
//Log.e(TAG, "save_chat_history_response_" + threadType + "_" + chatMessage + " =" + response);
return response;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/*This method is called after the background computation finishes.
The result of background process in passed in this method as parameters
and now you can dismiss progress dialog
and get the result and display on onPostExecute() method
*/
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
// Log.e(TAG, "chatAttachmentType = " + chatAttachmentType);
updateCounter();
if (result != null) {
JSONObject jo = new JSONObject(result);
String success = null;
final int storeLimit = SharedPreference.getLimit(UploadImageService.this);
if (jo.has(WS.SUCCESS)) {
success = jo.getString(WS.SUCCESS);
if (!TextUtils.isEmpty(success) && success.equals("0")) {
return;
}
if (!TextUtils.isEmpty(success) && success.equals("100")) {
callWsSaveChat(chatAttachmentType, chatMessage, thumbBase64AttachmentPath, originalBase64Image, originalFilePath);
updateRecentChatAndThreadList();
return;
}
if (!TextUtils.isEmpty(success) && success.equals("99")) {
updateRecentChatAndThreadList();
return;
}
}
try {
ArrayList<Chat> saveChatArrayList = null;
if (!TextUtils.isEmpty(success) && success.equals("1")) {
saveChatArrayList = new Chat().getChatHistory(UploadImageService.this, result, TAG, "");
// Log.e(TAG, "onPostExecute_saveChatArrayList.size = " + saveChatArrayList);
ArrayList<Chat> chatHistoryWithoutMsgId = database.getWithoutMsgIdChatHistory(chatThreadId, "#");
//Log.e(TAG, "onPostExecute_chatHistoryWithoutMsgId.size = " + chatHistoryWithoutMsgId.size());
if (saveChatArrayList != null && !saveChatArrayList.isEmpty() && saveChatArrayList.size() > 0) {
for (int i = 0; i < saveChatArrayList.size(); i++) {
final Chat apiChat = saveChatArrayList.get(i);
String apiMsg = apiChat.getMessage();
String apiThumb = null;
if (!TextUtils.isEmpty(apiChat.getAttachment_thumb())) {
apiThumb = apiChat.getAttachment_thumb().concat("$");
}
if (chatHistoryWithoutMsgId != null && !chatHistoryWithoutMsgId.isEmpty() && chatHistoryWithoutMsgId.size() > 0) {
for (int j = 0; j < chatHistoryWithoutMsgId.size(); j++) {
Chat dbChat = chatHistoryWithoutMsgId.get(j);
final String db_message = dbChat.getMessage();
final String db_thumb = dbChat.getAttachment_thumb();
if (apiThumb.equals(db_thumb)) {
database.updateChatList(apiChat, result, "#", db_message, db_thumb, loginUserId, toUser, chatThreadId, threadType);
bundle.putString(RESULT, UPLOAD_IMAGE);
receiver.send(STATUS_FINISHED, bundle);
if (!TextUtils.isEmpty(chatAttachmentType) && chatAttachmentType.equals(getResources().getString(R.string.Image))) {
originalBase64Image = getBase64Image(originalFilePath);
}
int subLength = 1024 * 256;
//Log.e(TAG, "upload_subLength = " + subLength);
int index = 0;
int totalChunks = 0;
if (!TextUtils.isEmpty(originalBase64Image)) {
for (int k = 0; index < originalBase64Image.length(); k++) {
index = index + subLength;
totalChunks++;
}
database.insertOriginalUploadImageList(apiChat.getAttachment_id(), totalChunks, 0, originalFilePath, chatThreadId, apiChat.getDt_sender_created(), chatAttachmentType);
// database.deleteAttachmentImageList(originalBase64Image);
database.deleteAttachmentImageList(originalFilePath);
UploadOriginalImageList(apiChat.getAttachment_id());
}
break;
} else {
// Log.e(TAG, "onPostExecute_not_equal_image");
}
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
// Util.showAlertDialog(mContext, mContext.getResources().getString(R.string.No_internet_connection_available));
}
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "error = " + e.getMessage());
}
}
There are many methods to upload more images to the server.. one could be including two libraries: apache-mime4j-0.6.jar and httpmime-4.0.1.jar.. After that create your java main code:
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class FileUploadTest extends Activity {
private static final int SELECT_FILE1 = 1;
private static final int SELECT_FILE2 = 2;
String selectedPath1 = "NONE";
String selectedPath2 = "NONE";
TextView tv, res;
ProgressDialog progressDialog;
Button b1,b2,b3;
HttpEntity resEntity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.tv);
res = (TextView)findViewById(R.id.res);
tv.setText(tv.getText() + selectedPath1 + "," + selectedPath2);
b1 = (Button)findViewById(R.id.Button01);
b2 = (Button)findViewById(R.id.Button02);
b3 = (Button)findViewById(R.id.upload);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
openGallery(SELECT_FILE1);
}
});
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
openGallery(SELECT_FILE2);
}
});
b3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!(selectedPath1.trim().equalsIgnoreCase("NONE")) && !(selectedPath2.trim().equalsIgnoreCase("NONE"))){
progressDialog = ProgressDialog.show(FileUploadTest.this, "", "Uploading files to server.....", false);
Thread thread=new Thread(new Runnable(){
public void run(){
doFileUpload();
runOnUiThread(new Runnable(){
public void run() {
if(progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
});
thread.start();
}else{
Toast.makeText(getApplicationContext(),"Please select two files to upload.", Toast.LENGTH_SHORT).show();
}
}
});
}
public void openGallery(int req_code){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select file to upload "), req_code);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
if (requestCode == SELECT_FILE1)
{
selectedPath1 = getPath(selectedImageUri);
System.out.println("selectedPath1 : " + selectedPath1);
}
if (requestCode == SELECT_FILE2)
{
selectedPath2 = getPath(selectedImageUri);
System.out.println("selectedPath2 : " + selectedPath2);
}
tv.setText("Selected File paths : " + selectedPath1 + "," + selectedPath2);
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void doFileUpload(){
File file1 = new File(selectedPath1);
File file2 = new File(selectedPath2);
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class FileUploadTest extends Activity {
private static final int SELECT_FILE1 = 1;
private static final int SELECT_FILE2 = 2;
String selectedPath1 = "NONE";
String selectedPath2 = "NONE";
TextView tv, res;
ProgressDialog progressDialog;
Button b1,b2,b3;
HttpEntity resEntity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.tv);
res = (TextView)findViewById(R.id.res);
tv.setText(tv.getText() + selectedPath1 + "," + selectedPath2);
b1 = (Button)findViewById(R.id.Button01);
b2 = (Button)findViewById(R.id.Button02);
b3 = (Button)findViewById(R.id.upload);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
openGallery(SELECT_FILE1);
}
});
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
openGallery(SELECT_FILE2);
}
});
b3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!(selectedPath1.trim().equalsIgnoreCase("NONE")) && !(selectedPath2.trim().equalsIgnoreCase("NONE"))){
progressDialog = ProgressDialog.show(FileUploadTest.this, "", "Uploading files to server.....", false);
Thread thread=new Thread(new Runnable(){
public void run(){
doFileUpload();
runOnUiThread(new Runnable(){
public void run() {
if(progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
});
thread.start();
}else{
Toast.makeText(getApplicationContext(),"Please select two files to upload.", Toast.LENGTH_SHORT).show();
}
}
});
}
public void openGallery(int req_code){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select file to upload "), req_code);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
if (requestCode == SELECT_FILE1)
{
selectedPath1 = getPath(selectedImageUri);
System.out.println("selectedPath1 : " + selectedPath1);
}
if (requestCode == SELECT_FILE2)
{
selectedPath2 = getPath(selectedImageUri);
System.out.println("selectedPath2 : " + selectedPath2);
}
tv.setText("Selected File paths : " + selectedPath1 + "," + selectedPath2);
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void doFileUpload(){
File file1 = new File(selectedPath1);
File file2 = new File(selectedPath2);
String urlString = "http://10.0.2.2/upload_test/upload_media_test.php";
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
FileBody bin1 = new FileBody(file1);
FileBody bin2 = new FileBody(file2);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploadedfile1", bin1);
reqEntity.addPart("uploadedfile2", bin2);
reqEntity.addPart("user", new StringBody("User"));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
final String response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE",response_str);
runOnUiThread(new Runnable(){
public void run() {
try {
res.setTextColor(Color.GREEN);
res.setText("n Response from server : n " + response_str);
Toast.makeText(getApplicationContext(),"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
catch (Exception ex){
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
}
}
Now your layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Multiple File Upload from CoderzHeaven"
/>
<Button
android:id="#+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get First File">
</Button>
<Button
android:id="#+id/Button02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Second File">
</Button>
<Button
android:id="#+id/upload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Upload">
</Button>
<TextView
android:id="#+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Selected File path : "
/>
<TextView
android:id="#+id/res"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
/>
</LinearLayout>
of course, include the internet permission in your manifest:
<uses-permission android:name="android.permission.INTERNET" />
And voilà. Anyway i followed this example in my case: http://www.coderzheaven.com/2011/08/16/how-to-upload-multiple-files-in-one-request-along-with-other-string-parameters-in-android/ try to see there.. There are 4 methods to upload multiple files. See which you like

Problems in integrating Dropbox with android application

I am trying to integrate Dropbox with android application using Dropbox API using this tutorial. My code compiles fine with no error. But when I try to download the file from Dropbox, I only receive an empty file. To me it seems that its not interacting with dropbox. Could you please have a look at my code. I am posting all my files. Thank you so much.
APP : My Application
MainActivity.java file:
package com.tutorialspoint.myapplication;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.ProgressListener;
import com.dropbox.client2.android.AndroidAuthSession;
import com.dropbox.client2.session.AppKeyPair;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
public class MainActivity extends ActionBarActivity {
public static Button button1;
public static Button button2;
public static Button button3;
public static Button button4;
public static TextView textView;
public static String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/AAA_DB_Tutorials/" ;
public static File Dir = new File(path);
public void onClickBut1(View v)
{
UploadToDropboxFromPath(path + "testfile.txt", "db_tutorial/uploadFileFromPath.txt");
}
public void onClickBut2(View v)
{
UploadToDropboxFromSelectedApp("db_tutorial/UploadFilesFromSelectedApp");
}
public void onClickBut3(View v)
{
UploadToDropboxFromFilemanager(path + "testfile.txt");
}
public void onClickBut4(View v)
{
DownloadFromDropboxFromPath(path + "downloadFileFromDrobboxkkk","db_tutorial/uploadFileFromPath.txt" );
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button)findViewById(R.id.button1);
button2 = (Button)findViewById(R.id.button2);
button3 = (Button)findViewById(R.id.button3);
button4 = (Button)findViewById(R.id.button4);
textView = (TextView)findViewById(R.id.textView);
AndroidAuthSession session = buildSession();
dropboxAPI = new DropboxAPI<AndroidAuthSession>(session);
Dir.mkdir();
}
static DropboxAPI<AndroidAuthSession> dropboxAPI;
private static final String APP_KEY = "xxxxxx";
private static final String APP_SECRET = "xxxx";
private static final String ACCESSTOKEN = "xxxxxx";
private DropboxAPI.UploadRequest request;
private AndroidAuthSession buildSession()
{
AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeyPair);
session.setOAuth2AccessToken(ACCESSTOKEN);
return session;
}
static final int UploadFromSelectApp = 9501;
static final int UploadFromFilemanager = 9502;
public static String DropboxUploadPathFrom = "";
public static String DropboxUploadName = "";
public static String DropboxDownloadPathFrom = "";
public static String DropboxDownloadPathTo = "";
private void UploadToDropboxFromPath (String uploadPathFrom, String uploadPathTo)
{
Toast.makeText(getApplicationContext(), "Upload file ...", Toast.LENGTH_SHORT).show();
final String uploadPathF = uploadPathFrom;
final String uploadPathT = uploadPathTo;
Thread th = new Thread(new Runnable()
{
public void run()
{
File tmpFile = null;
try
{
tmpFile = new File(uploadPathF);
}
catch (Exception e) {e.printStackTrace();}
FileInputStream fis = null;
try
{
fis = new FileInputStream(tmpFile);
}
catch (FileNotFoundException e) {e.printStackTrace();}
try
{
dropboxAPI.putFileOverwrite(uploadPathT, fis, tmpFile.length(), null);
}
catch (Exception e) {}
getMain().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "File successfully uploaded.", Toast.LENGTH_SHORT).show();
}
});
}
});
th.start();
}
private void UploadToDropboxFromSelectedApp (String uploadName)
{
DropboxUploadName = uploadName;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "Upload from ..."), UploadFromSelectApp);
}
private void UploadToDropboxFromFilemanager (String uploadName)
{
DropboxUploadName = uploadName;
Intent intent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
intent.putExtra("CONTENT_TYPE", "*/*");
intent.addCategory(Intent.CATEGORY_DEFAULT);
startActivityForResult(intent, UploadFromFilemanager);
}
private void DownloadFromDropboxFromPath (String downloadPathTo, String downloadPathFrom)
{
DropboxDownloadPathTo = downloadPathTo;
DropboxDownloadPathFrom = downloadPathFrom;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Download file ...", Toast.LENGTH_SHORT).show();
Thread th = new Thread(new Runnable() {
public void run() {
File file = new File(DropboxDownloadPathTo + DropboxDownloadPathFrom.substring(DropboxDownloadPathFrom.lastIndexOf('.')));
if (file.exists()) file.delete();
try {
FileOutputStream outputStream = new FileOutputStream(file);
MainActivity.dropboxAPI.getFile(DropboxDownloadPathFrom, null, outputStream, null);
getMain().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "File successfully downloaded.", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
th.start();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == UploadFromFilemanager)
{
final Uri currFileURI = intent.getData();
final String pathFrom = currFileURI.getPath();
Toast.makeText(getApplicationContext(), "Upload file ...", Toast.LENGTH_SHORT).show();
Thread th = new Thread(new Runnable()
{
public void run()
{
getMain().runOnUiThread(new Runnable()
{
#Override
public void run()
{
UploadToDropboxFromPath(pathFrom, "/db-test/" + DropboxUploadName + pathFrom.substring(pathFrom.lastIndexOf('.')));
Toast.makeText(getApplicationContext(), "File successfully uploaded.", Toast.LENGTH_SHORT).show();
}
});
}
});
th.start();
}
if (requestCode == UploadFromSelectApp)
{
Toast.makeText(getApplicationContext(), "Upload file ...", Toast.LENGTH_SHORT).show();
final Uri uri = intent.getData();
DropboxUploadPathFrom = getPath(getApplicationContext(), uri);
if(DropboxUploadPathFrom == null) {
DropboxUploadPathFrom = uri.getPath();
}
Thread th = new Thread(new Runnable(){
public void run() {
try
{
final File file = new File(DropboxUploadPathFrom);
InputStream inputStream = getContentResolver().openInputStream(uri);
dropboxAPI.putFile("/db-test/" + DropboxUploadName + file.getName().substring(file.getName().lastIndexOf("."),
file.getName().length()), inputStream, file.length(), null, new ProgressListener(){
#Override
public long progressInterval() {return 100;}
#Override
public void onProgress(long arg0, long arg1){}
});
getMain().runOnUiThread(new Runnable()
{
#Override
public void run()
{
Toast.makeText(getApplicationContext(), "File successfully uploaded.", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {e.printStackTrace();}
}
});
th.start();
}
super.onActivityResult(requestCode, resultCode, intent);
}
public String getPath(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA, MediaStore.Video.Media.DATA, MediaStore.Audio.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
if(s!=null) {
cursor.close();
return s;
}
}
catch(Exception e){}
try {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
if(s!=null) {
cursor.close();
return s;
}
}
catch(Exception e){}
try {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
cursor.close();
return s;
}
finally {
if (cursor != null) {
cursor.close();
}
}
}
public MainActivity getMain()
{
return this;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.tutorialspoint.myapplication.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hellppppppo World!"
android:id="#+id/textView"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="UPLOAD WITH FIXED PATH"
android:id="#+id/button1"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="onClickBut1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="UPLOAD FROM SELECTED APP"
android:id="#+id/button2"
android:layout_below="#+id/button1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="onClickBut2"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="UPLOAD FROM FILE MANAGER"
android:id="#+id/button3"
android:layout_below="#+id/button2"
android:layout_alignRight="#+id/button2"
android:layout_alignEnd="#+id/button2"
android:onClick="onClickBut3"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DOWNLOAD"
android:id="#+id/button4"
android:layout_below="#+id/button3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="onClickBut4"/>
</RelativeLayout>
build.gradle file
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.tutorialspoint.myapplication"
minSdkVersion 16
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile files ('libs/json_simple-1.1.jar')
compile files ('libs/dropbox-android-sdk-1.6.3.jar')
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutorialspoint.myapplication">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>

What's wrong with my code? "no such table: TaxiFile" [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
here is the DBHelper class
package com.example.taxirecordapp;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context c, String dbName, int dbVer) {
super(c, dbName, null, dbVer);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String driverSQL = "CREATE TABLE DriverFile (DriverNumber TEXT PRIMARY KEY NOT NULL, DriverFName TEXT, DriverLName TEXT, DriverDateHired TEXT, DriverContactNumber TEXT, DriverAddress TEXT)";
String taxiSQL = "CREATE TABLE TaxiFile (TaxiPlateNumber TEXT PRIMARY KEY NOT NULL, TaxiDriverNumber TEXT, TaxiRentDate TEXT, TaxiDriverBalance INTEGER)";
db.execSQL(taxiSQL);
db.execSQL(driverSQL);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
String driverSQL = "DROP TABLE IF EXISTS DriverFile";
String taxiSQL = "DROP TABLE IF EXISTS TaxiFile";
db.execSQL(taxiSQL);
db.execSQL(driverSQL);
onCreate(db);
}
}
the AddTaxi class
package com.example.taxirecordapp;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AddTaxi extends Activity {
EditText etPlateNumber, etDate, etBalance, etDriverNumber;
Button btnSave, btnBack;
SQLiteDatabase dbase;
int position;
int balance = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add_taxi);
DBHelper helper = new DBHelper(getApplication(), "TaxiRecordAppDB", 1);
dbase = helper.getWritableDatabase();
etPlateNumber = (EditText) findViewById(R.id.etPlateNumber);
etDate = (EditText) findViewById(R.id.etDate);
etBalance = (EditText) findViewById(R.id.etBalance);
etDriverNumber = (EditText) findViewById(R.id.etDriverNumber);
btnSave = (Button) findViewById(R.id.btnSave);
btnBack = (Button) findViewById(R.id.btnBack);
Intent i = getIntent();
position = i.getIntExtra("position", position);
Cursor rsCursor;
String[] rsFields = { "DriverNumber", "DriverFName", "DriverLName",
"DriverDateHired", "DriverContactNumber", "DriverAddress" };
rsCursor = dbase.query("DriverFile", rsFields, null, null, null, null,
null, null);
rsCursor.moveToPosition(position);
if (rsCursor.isAfterLast() == false) {
if (rsCursor.getPosition() == position) {
etDriverNumber.setText(rsCursor.getString(0).toString());
}
}
rsCursor.close();
btnSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (etPlateNumber.getText().toString().length() == 0) {
Toast.makeText(getApplicationContext(),
"Please input Plate Number!", Toast.LENGTH_SHORT)
.show();
} else if (etDate.getText().toString().length() == 0) {
Toast.makeText(getApplicationContext(),
"Please input Date Rented!", Toast.LENGTH_SHORT)
.show();
}
else {
if (etBalance.getText().toString().length() == 0) {
balance = 0;
} else {
balance = Integer.parseInt(etBalance.getText()
.toString());
}
AddTaxiRecord(etPlateNumber.getText().toString(),
etDriverNumber.getText().toString(), etDate
.getText().toString(), balance);
}
}
});
btnBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(AddTaxi.this, MainActivity.class);
startActivity(i);
}
});
}
public void AddTaxiRecord(String plateNumber, String driverNumber,
String date, int balance) {
try {
Cursor rsCursor;
String[] rsFields = { "TaxiPlateNumber", "TaxiDriverNumber",
"TaxiRentDate", "TaxiDriverBalance" };
rsCursor = dbase.query("TaxiFile", rsFields, "TaxiPlateNumber = "
+ plateNumber, null, null, null, null, null);
rsCursor.moveToFirst();
if (rsCursor.isAfterLast() == false) {
Toast.makeText(getApplicationContext(),
"Plate number already exist!", Toast.LENGTH_SHORT)
.show();
} else {
ContentValues rsValues = new ContentValues();
rsValues.put("TaxiPlateNumber", plateNumber);
rsValues.put("TaxiDriverNumber", driverNumber);
rsValues.put("TaxiRentDate", date);
rsValues.put("TaxiDriverBalance", balance);
dbase.insert("TaxiFile", null, rsValues);
Toast.makeText(getApplicationContext(),
"Record Successfully Saved!", Toast.LENGTH_SHORT)
.show();
}
} catch (Exception e) {
}
}
}
and the AddDriver class which is working fine
package com.example.taxirecordapp;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AddDriver extends Activity {
EditText etDriverNumber, etFirstName, etLastName, etDateHired,
etContactNumber, etAddress;
Button btnSave, btnBack;
SQLiteDatabase dbase;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add_driver);
etDriverNumber = (EditText) findViewById(R.id.etDriverNumber);
etFirstName = (EditText) findViewById(R.id.etFirstName);
etLastName = (EditText) findViewById(R.id.etLastName);
etDateHired = (EditText) findViewById(R.id.etDateHired);
etContactNumber = (EditText) findViewById(R.id.etContactNumber);
etAddress = (EditText) findViewById(R.id.etAddress);
btnSave = (Button) findViewById(R.id.btnSave);
btnBack = (Button) findViewById(R.id.btnBack);
DBHelper helper = new DBHelper(getApplication(), "TaxiRecordAppDB", 1);
dbase = helper.getWritableDatabase();
btnSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (etDriverNumber.getText().toString().length() == 0) {
Toast.makeText(getApplicationContext(),
"Please input Driver Number!", Toast.LENGTH_SHORT)
.show();
} else if (etFirstName.getText().toString().length() == 0) {
Toast.makeText(getApplicationContext(),
"Please input Driver's First Name!",
Toast.LENGTH_SHORT).show();
} else if (etLastName.getText().toString().length() == 0) {
Toast.makeText(getApplicationContext(),
"Please input Driver's Last Name!",
Toast.LENGTH_SHORT).show();
} else if (etDateHired.getText().toString().length() == 0) {
Toast.makeText(getApplicationContext(),
"Please input Driver's Date Hired!",
Toast.LENGTH_SHORT).show();
} else if (etContactNumber.getText().toString().length() == 0) {
Toast.makeText(getApplicationContext(),
"Please input Driver's Contact Number!",
Toast.LENGTH_SHORT).show();
} else if (etAddress.getText().toString().length() == 0) {
Toast.makeText(getApplicationContext(),
"Please input Driver's Address!",
Toast.LENGTH_SHORT).show();
}
else {
AddDriverRecord(Integer.parseInt(etDriverNumber.getText()
.toString()), etFirstName.getText().toString(),
etLastName.getText().toString(), etDateHired
.getText().toString(), etContactNumber
.getText().toString(), etAddress.getText()
.toString());
}
}
});
btnBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(AddDriver.this,
MainActivity.class);
startActivity(i);
}
});
}
public void AddDriverRecord(int driverNumber, String firstName,
String lastName, String dateHired, String contactNumber,
String address) {
try {
Cursor rsCursor;
String[] rsFields = { "DriverNumber", "DriverFName", "DriverLName",
"DriverDateHired", "DriverContactNumber", "DriverAddress" };
rsCursor = dbase.query("DriverFile", rsFields, "DriverNumber = "
+ driverNumber, null, null, null, null, null);
rsCursor.moveToFirst();
if (rsCursor.isAfterLast() == false) {
Toast.makeText(getApplicationContext(),
"Driver number already exist!", Toast.LENGTH_SHORT)
.show();
} else {
ContentValues rsValues = new ContentValues();
rsValues.put("DriverNumber", driverNumber);
rsValues.put("DriverFName", firstName);
rsValues.put("DriverLName", lastName);
rsValues.put("DriverDateHired", dateHired);
rsValues.put("DriverContactNumber", contactNumber);
rsValues.put("DriverAddress", address);
dbase.insert("DriverFile", null, rsValues);
Toast.makeText(getApplicationContext(),
"Record Successfully Saved!", Toast.LENGTH_SHORT)
.show();
}
} catch (Exception e) {
}
}
}
I don't see any problems. So my guess is that you added the TaxiFile table after you added the DriverFile table.
To ensure that onUpgrade is called, you need to increase the database version but you are still using 1:
DBHelper helper = new DBHelper(getApplication(), "TaxiRecordAppDB", 1);
That probably means that TaxiFile is never created.
Every database schema change requires an increment of database version to make sure that onUpgrade is called.
Edit:
While development you can do the shortcut: Keep the version 1 but delete the app on the device or clear the data in the app info (both will force a complete new creation of the database).
Be warned: That shortcut does not work as soon as you have the app published because the user should never be required to do that. In that case you really need to handle schema changes and version increments by yourself.

How to connect a mobile and a printer via bluetooth in android?

Can anyone tell me how to connect a mobile and a printer via bluetooth to print a text file in android?
That is,if i click the print button from the android application,the printer has to print that corresponding file.As per my knowledge i have searched for it in Google, but i couldn't find any good samples to do it.Has anyone have at-least one sample android program to do this, it will be better to clear my chaos.
Suggestions please.
Thanks for your precious time!..
Bluetooth Printer Android Example
Create a new android project BlueToothPrinterApp in your editor.
Step 1:
Create main activity like below
com.example.BlueToothPrinterApp / BlueToothPrinterApp.java
package com.example.BlueToothPrinterApp;
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import java.io.OutputStream;
import android.bluetooth.BluetoothSocket;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class BlueToothPrinterApp extends Activity {
/** Called when the activity is first created. */
EditText message;
Button printbtn;
byte FONT_TYPE;
private static BluetoothSocket btsocket;
private static OutputStream btoutputstream;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
message = (EditText) findViewById(R.id.message);
printbtn = (Button) findViewById(R.id.printButton);
printbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
connect();
}
});
}
protected void connect() {
if (btsocket == null) {
Intent BTIntent = new Intent(getApplicationContext(), BTDeviceList.class);
this.startActivityForResult(BTIntent, BTDeviceList.REQUEST_CONNECT_BT);
} else {
OutputStream opstream = null;
try {
opstream = btsocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
btoutputstream = opstream;
print_bt();
}
}
private void print_bt() {
try {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
btoutputstream = btsocket.getOutputStream();
byte[] printformat = {
0x1B,
0× 21,
FONT_TYPE
};
btoutputstream.write(printformat);
String msg = message.getText().toString();
btoutputstream.write(msg.getBytes());
btoutputstream.write(0x0D);
btoutputstream.write(0x0D);
btoutputstream.write(0x0D);
btoutputstream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
if (btsocket != null) {
btoutputstream.close();
btsocket.close();
btsocket = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
btsocket = BTDeviceList.getSocket();
if (btsocket != null) {
print_bt();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Step 2:
com.example.BlueToothPrinterApp / BTDeviceList.java
package com.example.BlueToothPrinterApp;
import java.io.IOException;
import java.util.Set;
import java.util.UUID;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class BTDeviceList extends ListActivity {
static public final int REQUEST_CONNECT_BT = 0× 2300;
static private final int REQUEST_ENABLE_BT = 0× 1000;
static private BluetoothAdapter mBluetoothAdapter = null;
static private ArrayAdapter < String > mArrayAdapter = null;
static private ArrayAdapter < BluetoothDevice > btDevices = null;
private static final UUID SPP_UUID = UUID
.fromString(“8 ce255c0 - 200 a - 11e0 - ac64 - 0800200 c9a66″);
// UUID.fromString(“00001101-0000-1000-8000-00805F9B34FB”);
static private BluetoothSocket mbtSocket = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(“Bluetooth Devices”);
try {
if (initDevicesList() != 0) {
this.finish();
return;
}
} catch (Exception ex) {
this.finish();
return;
}
IntentFilter btIntentFilter = new IntentFilter(
BluetoothDevice.ACTION_FOUND);
registerReceiver(mBTReceiver, btIntentFilter);
}
public static BluetoothSocket getSocket() {
return mbtSocket;
}
private void flushData() {
try {
if (mbtSocket != null) {
mbtSocket.close();
mbtSocket = null;
}
if (mBluetoothAdapter != null) {
mBluetoothAdapter.cancelDiscovery();
}
if (btDevices != null) {
btDevices.clear();
btDevices = null;
}
if (mArrayAdapter != null) {
mArrayAdapter.clear();
mArrayAdapter.notifyDataSetChanged();
mArrayAdapter.notifyDataSetInvalidated();
mArrayAdapter = null;
}
finalize();
} catch (Exception ex) {} catch (Throwable e) {}
}
private int initDevicesList() {
flushData();
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(getApplicationContext(), “Bluetooth not supported!!”, Toast.LENGTH_LONG).show();
return -1;
}
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
mArrayAdapter = new ArrayAdapter < String > (getApplicationContext(),
android.R.layout.simple_list_item_1);
setListAdapter(mArrayAdapter);
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
try {
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} catch (Exception ex) {
return -2;
}
Toast.makeText(getApplicationContext(), “Getting all available Bluetooth Devices”, Toast.LENGTH_SHORT)
.show();
return 0;
}
#Override
protected void onActivityResult(int reqCode, int resultCode, Intent intent) {
super.onActivityResult(reqCode, resultCode, intent);
switch (reqCode) {
case REQUEST_ENABLE_BT:
if (resultCode == RESULT_OK) {
Set < BluetoothDevice > btDeviceList = mBluetoothAdapter
.getBondedDevices();
try {
if (btDeviceList.size() > 0) {
for (BluetoothDevice device: btDeviceList) {
if (btDeviceList.contains(device) == false) {
btDevices.add(device);
mArrayAdapter.add(device.getName() + “\n” +
device.getAddress());
mArrayAdapter.notifyDataSetInvalidated();
}
}
}
} catch (Exception ex) {}
}
break;
}
mBluetoothAdapter.startDiscovery();
}
private final BroadcastReceiver mBTReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
try {
if (btDevices == null) {
btDevices = new ArrayAdapter < BluetoothDevice > (
getApplicationContext(), android.R.id.text1);
}
if (btDevices.getPosition(device) < 0) {
btDevices.add(device);
mArrayAdapter.add(device.getName() + “\n” +
device.getAddress() + “\n”);
mArrayAdapter.notifyDataSetInvalidated();
}
} catch (Exception ex) {
// ex.fillInStackTrace();
}
}
}
};
#Override
protected void onListItemClick(ListView l, View v, final int position,
long id) {
super.onListItemClick(l, v, position, id);
if (mBluetoothAdapter == null) {
return;
}
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
Toast.makeText(
getApplicationContext(), “Connecting to” + btDevices.getItem(position).getName() + “, ”
+btDevices.getItem(position).getAddress(),
Toast.LENGTH_SHORT).show();
Thread connectThread = new Thread(new Runnable() {
#Override
public void run() {
try {
boolean gotuuid = btDevices.getItem(position)
.fetchUuidsWithSdp();
UUID uuid = btDevices.getItem(position).getUuids()[0]
.getUuid();
mbtSocket = btDevices.getItem(position)
.createRfcommSocketToServiceRecord(uuid);
mbtSocket.connect();
} catch (IOException ex) {
runOnUiThread(socketErrorRunnable);
try {
mbtSocket.close();
} catch (IOException e) {
// e.printStackTrace();
}
mbtSocket = null;
return;
} finally {
runOnUiThread(new Runnable() {
#Override
public void run() {
finish();
}
});
}
}
});
connectThread.start();
}
private Runnable socketErrorRunnable = new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), “Cannot establish connection”, Toast.LENGTH_SHORT).show();
mBluetoothAdapter.startDiscovery();
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, Menu.FIRST, Menu.NONE, “Refresh Scanning”);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case Menu.FIRST:
initDevicesList();
break;
}
return true;
}
}
Step 3:
Edit your main.xml file and paste below code.
res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<TextView
android:id="#+id/msgtextlbl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enter Your Message : "/>
<EditText
android:id="#+id/message"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:layout_below="#+id/msgtextlbl"
android:text=""/>
<Button
android:id="#+id/printButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/message"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dip"
android:text="Print"/>
</RelativeLayout>
Step 4:
Now edit your AndroidManifest.xml
Add bluetooth permission and admin permission.
AndroidManifest.xml
<?xml version=”1.0″ encoding=”utf-8″?>
<manifest
xmlns:android=”http://schemas.android.com/apk/res/android
package=”com.example.BlueToothPrinterApp”
android:versionCode=”1″
android:versionName=”1.0″>
<uses-sdk android:minSdkVersion=”14″ />
<uses-permission android:name=”android.permission.BLUETOOTH”></uses-permission>
<uses-permission android:name=”android.permission.BLUETOOTH_ADMIN”></uses-permission>
<application
android:label=”#string/app_name”
android:icon=”#drawable/ic_launcher”>
<activity
android:name=”BlueToothPrinterApp”
android:label=”#string/app_name”>
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
<activity android:name=”BTDeviceList”></activity>
</application>
</manifest>
Compile and run this application. Enter message and press print button.
You will see list of bluetooth devices. Select bluettoth printer.
Check print on your bluetooth printer.
here is the CODE Reference...
You can use this awesome lib, you can connect to any printer and print easily,
https://github.com/mazenrashed/Printooth
you can download it by:
implementation 'com.github.mazenrashed:Printooth:${LAST_VERSION}'
and use it like:
var printables = ArrayList<Printable>()
var printable = Printable.PrintableBuilder()
.setText("Hello World")
printables.add(printable)
BluetoothPrinter.printer().print(printables)

Categories

Resources