I have a variable MyFinalPressure which is populated with sensor data from the sensors pressure. If MyFinalPressure is == to 4000 (4000 points or 40 sec) then stop writing to local storage.
But it looks like when I debug the code, it hits the boolean MaxPoints and is still writing. I wonder if my logic is wrong or not.
Could you please help me out.
public Boolean Store = false;
Boolean MaxPoints = false;
if (activity.Store) {
activity.writeToFile(MyFinalPressure);//MyFinalPressure is float of one dimension array or stream of array.
}
if (MyFinalPressure==4000){ //this conditon, am trying to stop wrting to local memory.
activity.MaxPoints = true;
}
FileOutputStream fileOutputStream;
//method to write into local memory.
public void writeToFile(final float MyFinalPressure) {
Log.d(TAG, "writeToFile.");
String finalData;
finalData = String.valueOf(MyFinalPressure);
try {
// true here for 'append'
fileOutputStream = new FileOutputStream(file, true);
String Space = " ";
byte[] convert = Space.getBytes();
fileOutputStream.write(finalData.getBytes());
fileOutputStream.write(convert);
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//write to file.
StartWriting = (ToggleButton) findViewById(R.id.startWriting);
StartWriting.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (StartWriting.isChecked()) {
Store = true;
Toast.makeText(getApplicationContext(), "Data Starts writing into (Message.txt) file", Toast.LENGTH_LONG).show();
} else {
if (!StartWriting.isChecked()|| MaxPoints==true) { //here - this is wrong logic to stop writing to my file.
Toast.makeText(getApplicationContext(), "Data Stored at myAppFile", Toast.LENGTH_SHORT).show();
String finalData1;
finalData1 = String.valueOf(fileOutputStream);
Log.i(TAG, "of_writes: " + finalData1);
// Toast.makeText(getApplicationContext(), "Data_write_number: " + finalData1.length(), Toast.LENGTH_SHORT).show();
Store = false;
}
}
}
});
Just take out !StartWriting.isChecked()
Because of the above if statement StartWriting.isChecked() will always be false. Then because you are checking for "!StartWriting.isChecked()" it will always enter the statement.
Related
I'm trying to write the stream of my array that is coming from Bluetooth module and read from (HandleRead), to the internal storage directly. Is that possible in the first place?
Note that I am reading 100 samples per second. That means the file will fill up quickly. I am not familiar with storage, and my code isn't executed as I expected.
public class MainActivity extends ActionBarActivity implements SensorEventListener {
File Root = Environment.getExternalStorageDirectory();
File Dir = new File (Root.getAbsolutePath()+"/myAppFile");
File file = new File(Dir,"Message.txt");
#Override
protected void onCreate(Bundle savedInstanceState){
String state;
state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)){
if (!Dir.exists()){
Dir.mkdir();
}
}
private void handleRead(Message msg) {
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf);
ByteBuffer buffer = ByteBuffer.wrap(readBuf, 0, readBuf.length);
buffer.order(ByteOrder.BIG_ENDIAN);
buffer.clear();
final String[] strNumbers = readMessage.split("\n");
for (int j = 1; j <= strNumbers.length - 2; j++) {
pressure = Integer.parseInt(readMessage2);
MyFinalPressure = (float) (9.677 +0.831 * pressure);
// trying to store directly to internal sotrage
activity.save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(activity.file);
fileOutputStream.write((int) MyFinalPressure);
fileOutputStream.close();
Toast.makeText(activity.getApplicationContext(),"Message saved ", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
}
}
It appears you are not setting the FileOutputStream to 'append' (you need to add 'true' as 2nd parameter in constructor.)
This would write over the file from the file-start every time
also your 'setOnClickListener' is INSIDE your loop. This doesn't do anything for you as far as I can tell.
I recommend always setting up UI elements in a private void setupUI() {...} method that onCreate calls. The public void onClick(View v) {buttonForSavingPresssed()} where buttonForSavingPressed(){...} is the 'logic' of your onClick() method.
This will help you clean up the class and not have stray onClickListener assignments, etc.
My guess is that either your multiple assignments is very inefficient, since clickListeners aren't cheap, or... the clickListener might not even work at all because of a timing issue (if your loop is long running and you press the button and the listener has already been swapped for a new one)
I've cleaned up your code some, There are some suggestions and some log statements that should help you figure out what is going on.
// this is inside your onCreate()
...
activity.save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { buttonPressed();}
});
...
// Here is where you would put your logic when the button is presssed
public void buttonPressed(){
Toast.makeText(activity.getApplicationContext(),"Button Pressed ",
Toast.LENGTH_SHORT).show();
}
// you should make 'helper' functions that consolidate separate pieces of logic like this,
// that way you can more easily track what is happening in each method.
// Plus it helps keep each method shorter for ease of understanding, etc.
public void writeToFile(float finalPressure){
Log.d(LOG_TAG // where LOG_TAG is the String name of this class
"writeToFile(float) called." );
try{
// true here for 'append'
FileOutputStream fileOutputStream = new
FileOutputStream(activity.file, true);
fileOutputStream.write((int) finalPressure);
fileOutputStream.close();
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// now back to your handleRead, is this method called async wenever
// a message is read? Then wouldn't this be called a lot? I'm lost as to why
// you had the button in here at all.
private void handleRead(Message msg) {
Log.d(LOG_TAG // where LOG_TAG is the String name of this class
"handleRead(Message) called." );
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf);
ByteBuffer buffer = ByteBuffer.wrap(readBuf, 0, readBuf.length);
buffer.order(ByteOrder.BIG_ENDIAN);
buffer.clear();
final String[] strNumbers = readMessage.split("\n");
Log.d(LOG_TAG // where LOG_TAG is the String name of this class
"strNumbers length: " + strNumbers.length );
for (int j = 1; j <= strNumbers.length - 2; j++) {
pressure = Integer.parseInt(readMessage2);
MyFinalPressure = (float) (9.677 +0.831 * pressure);
// trying to store directly to internal sotrage
writeToFile(MyFinalPressure);
}
}
Edit:- i'm able to start the internet using vpn.The other issues is that now i'm receiving packets in my service in this piece of code of my VpnService.But i can't think of a proper way to block particular website.I've tried using name resolution using InnetAddress but that's not giving the expected result :
**#Override
public void run()
{
Log.i(TAG, "Started");
FileChannel vpnInput = new FileInputStream(vpnFileDescriptor).getChannel();
FileChannel vpnOutput = new FileOutputStream(vpnFileDescriptor).getChannel();
try
{
ByteBuffer bufferToNetwork = null;
boolean dataSent = true;
boolean dataReceived;
while (!Thread.interrupted())
{
if (dataSent)
bufferToNetwork = ByteBufferPool.acquire();
int readBytes = vpnInput.read(bufferToNetwork);
if (readBytes > 0)
{
dataSent = true;
bufferToNetwork.flip();
Packet packet = new Packet(bufferToNetwork);
Log.e("loggg packet",packet.toString());
if (packet.isUDP())
{
deviceToNetworkUDPQueue.offer(packet);
}
else if (packet.isTCP())
{
deviceToNetworkTCPQueue.offer(packet);
}
else
{
Log.w(TAG, "Unknown packet type");
dataSent = false;
}
}
else
{
dataSent = false;
}
ByteBuffer bufferFromNetwork = networkToDeviceQueue.poll();
if (bufferFromNetwork != null)
{
bufferFromNetwork.flip();
vpnOutput.write(bufferFromNetwork);
dataReceived = true;
ByteBufferPool.release(bufferFromNetwork);
}
else
{
dataReceived = false;
}
if (!dataSent && !dataReceived)
Thread.sleep(10);
}
}
catch (InterruptedException e)
{
Log.i(TAG, "Stopping");
}
catch (IOException e)
{
Log.w(TAG, e.toString(), e);
}
finally
{
closeResources(vpnInput, vpnOutput);
}
}**
I'm receiving a packet in this format:
Packet{ip4Header=IP4Header{version=4, totalLength=40, protocol=TCP, headerChecksum=14192, sourceAddress=10.0.8.1, destinationAddress=216.58.196.100}, tcpHeader=TCPHeader{sourcePort=39217, destinationPort=443, sequenceNumber=800911985, acknowledgementNumber=823271551, headerLength=20, window=29596, checksum=32492, flags= ACK}, payloadSize=0}
I'm using THIS CODE for starter and unable to block packets.
Apps like greyshirts no root firewall and mobiwool no root firewall works perfectly and they are also vpn based.Any suggestion is most welcomed.
Does anyone know how to create folder programatically using dropbox api for android??I am not using sync api.I have managed to upload images and files but I am unable to create folder.
This is my upload asynctask:
public class UploadFile extends AsyncTask<Void, Long, Boolean> {
private DropboxAPI<?> mApi;
private String mPath;
private File mFile;
private long mFileLen;
private UploadRequest mRequest;
private Context mContext;
private ProgressDialog mDialog;
final static private String ACCOUNT_PREFS_NAME = "prefs";
private String mErrorMsg;
public UploadFile(Context context, DropboxAPI<?> api, String dropboxPath,
File file) {
mContext = context;
mFileLen = file.length();
mApi = api;
mPath = dropboxPath;
mFile = file;
mDialog = new ProgressDialog(context);
mDialog.setMax(100);
mDialog.setMessage("Uploading " + file.getName());
mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.setProgress(0);
mDialog.setButton("Cancel", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// This will cancel the putFile operation
mRequest.abort();
}
});
mDialog.show();
}
#Override
protected Boolean doInBackground(Void... params) {
try {
// By creating a request, we get a handle to the putFile operation,
// so we can cancel it later if we want to
FileInputStream fis = new FileInputStream(mFile);
String path = mPath + mFile.getName();
mRequest = mApi.putFileOverwriteRequest(path, fis, mFile.length(),
new ProgressListener() {
#Override
public long progressInterval() {
// Update the progress bar every half-second or so
return 500;
}
#Override
public void onProgress(long bytes, long total) {
publishProgress(bytes);
}
});
if (mRequest != null) {
mRequest.upload();
return true;
}
} catch (DropboxUnlinkedException e) {
// This session wasn't authenticated properly or user unlinked
mErrorMsg = "This app wasn't authenticated properly.";
} catch (DropboxFileSizeException e) {
// File size too big to upload via the API
mErrorMsg = "This file is too big to upload";
} catch (DropboxPartialFileException e) {
// We canceled the operation
mErrorMsg = "Upload canceled";
} catch (DropboxServerException e) {
// Server-side exception. These are examples of what could happen,
// but we don't do anything special with them here.
if (e.error == DropboxServerException._401_UNAUTHORIZED) {
// Unauthorized, so we should unlink them. You may want to
// automatically log the user out in this case.
} else if (e.error == DropboxServerException._403_FORBIDDEN) {
// Not allowed to access this
} else if (e.error == DropboxServerException._404_NOT_FOUND) {
// path not found (or if it was the thumbnail, can't be
// thumbnailed)
} else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) {
// user is over quota
} else {
// Something else
}
// This gets the Dropbox error, translated into the user's language
mErrorMsg = e.body.userError;
if (mErrorMsg == null) {
mErrorMsg = e.body.error;
}
} catch (DropboxIOException e) {
e.printStackTrace();
// Happens all the time, probably want to retry automatically.
mErrorMsg = "Network error. Try again.";
} catch (DropboxParseException e) {
// Probably due to Dropbox server restarting, should retry
mErrorMsg = "Dropbox error. Try again.";
} catch (DropboxException e) {
// Unknown error
mErrorMsg = "Unknown error. Try again.";
} catch (FileNotFoundException e) {
}
return false;
}
#Override
protected void onProgressUpdate(Long... progress) {
int percent = (int) (100.0 * (double) progress[0] / mFileLen + 0.5);
mDialog.setProgress(percent);
}
#Override
protected void onPostExecute(Boolean result) {
mDialog.dismiss();
if (result) {
showToast("Successfully uploaded");
// mApi.getSession().unlink();
//
// // Clear our stored keys
// clearKeys();
} else {
showToast(mErrorMsg);
}
}
private void showToast(String msg) {
Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
error.show();
}
private void clearKeys() {
SharedPreferences prefs = mContext.getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.clear();
edit.commit();
}
}
Please help.
According to dropbox documentation
try {
// creating folder
val fo = client.files().createFolderV2(File.separator + folderPath)
} catch (ex: CreateFolderErrorException) {
if (ex.errorValue.isPath && ex.errorValue.pathValue.isConflict) {
// folder already exist
}
}
You can simply give like this for creating a folder! its very simple
dropbox.putFile("Mynumber2/myregion2/"+"/"+"A"+"/"+"B"+"/"+"ENTRY.db", fileInputStream,file.length(), null, null);
if you do, mynumber2-->myregion2-->A-->B will be your folder structure created on dropbox!
You want the createFolder method of DropboxAPI. See https://www.dropbox.com/static/developers/dropbox-android-sdk-1.6.1-docs/com/dropbox/client2/DropboxAPI.html#createFolder(java.lang.String).
Use the following for DIR:
"/your_folder_name/"
I m getting exception "Can't create handler inside thread that has not called Looper.prepare()
in the function doFirstTime().
I m trying to upload my data at Dropbox using Dropbox API
Can you tell me how to fix it?
public class DownloadFile extends AsyncTask<Void, Long, Boolean>
`{
private Context mContext;
private DropboxAPI<?> mApi;
private String mPath;
private FileOutputStream mFos;
private String mErrorMsg;
private StringBuilder xmlcode,newXMLCode;
private final static String FILE_NAME = "fuelrecords.xml";
private final static String ZIP_FILE_NAME = "fuelpad.zip";
private String dropbox_xml_records[];
private ArrayList<ArrayList<String>> dropbox_records;
private ArrayList<ArrayList<String>> database_records;
private ExpenseOperations eop;
private UploadFile up;
private boolean no_file;
public DownloadFile(Context context, DropboxAPI<?> api,String dropboxPath)
{
// We set the context this way so we don't accidentally leak activities
mContext = context.getApplicationContext();
mApi = api;
mPath = dropboxPath;
dropbox_records = new ArrayList<ArrayList<String>>();
database_records = new ArrayList<ArrayList<String>>();
eop = new ExpenseOperations(mContext);
xmlcode=new StringBuilder("");
newXMLCode=new StringBuilder("");
no_file = false;
}
#Override
protected Boolean doInBackground(Void... params)
{
Log.d("yes1", " in do in back of download..");
try
{
// Get the metadata for a directory
Entry dirent = mApi.metadata(mPath, 1000, null, true, null);
if (!dirent.isDir || dirent.contents == null)
{
// It's not a directory, or there's nothing in it
mErrorMsg = "Could not locate the file...";
return false;
}
String cachefilePath = mContext.getCacheDir().getAbsolutePath() + "/" + FILE_NAME;
String cachezipPath = mContext.getCacheDir().getAbsolutePath() + "/" + ZIP_FILE_NAME;
try
{
mFos = new FileOutputStream(cachezipPath);
}
catch (FileNotFoundException e)
{
mErrorMsg = "Couldn't create a local file to store the image";
return false;
}
Notification("SmartExpense", "Now syncing to dropbox");
mApi.getFile("/SmartExpenses.zip",null,mFos,null);
try
{
FileInputStream fin = new FileInputStream(cachezipPath);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
if((ze = zin.getNextEntry()) != null)
{
Log.v("Decompress", "Unzipping " + ze.getName());
if(ze.isDirectory())
{
}
else
{
FileOutputStream fout = new FileOutputStream(cachefilePath);
for (int c = zin.read(); c != -1; c = zin.read())
{
fout.write(c);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
}
catch(Exception ee)
{
Log.d("In unzip:", ""+ee);
}
try
{
FileInputStream fs =new FileInputStream(cachefilePath);
byte buff[] =new byte[1024];
while(fs.read(buff)>0)
{
xmlcode.append(new String(buff));
}
fs.close();
Log.d("Hhhhhhhhhhhaaaaaaaaaaaaa : ",""+xmlcode);
Looper.prepare();
if(!(xmlcode.toString().contains("<expenserecord>")) && getDBRecords())
{
doFirstTime();
Log.d("1","1");
}
else if((xmlcode.toString().contains("<expenserecord>")) && getDBRecords())
{
Log.d("2","2");
makeDropboxRecordArray();
performSync();
}
else if((xmlcode.toString().contains("<expenserecord>")) && !getDBRecords())
{
Log.d("3","3");
makeDropboxRecordArray();
fillDBwithDropboxRecords();
}
else if(!(xmlcode.toString().contains("<expenserecord>")) && !getDBRecords())
{
Log.d("4","4");
mErrorMsg ="No records exist to sync";
}
}
catch (Exception e)
{
Log.d("Exception in doback: ",""+e);
}
return true;
}
catch (DropboxUnlinkedException e)
{
mErrorMsg = "Error :Dropbox unliked";
// The AuthSession wasn't properly authenticated or user unlinked.
}
catch (DropboxPartialFileException e)
{
// We canceled the operation
mErrorMsg = "Download canceled";
}
catch (DropboxServerException e)
{
// Server-side exception. These are examples of what could happen,
// but we don't do anything special with them here.
if (e.error == DropboxServerException._304_NOT_MODIFIED)
{
mErrorMsg = "Server Error.....";
// won't happen since we don't pass in revision with metadata
}
else if (e.error == DropboxServerException._401_UNAUTHORIZED)
{
mErrorMsg = "Server Error : Unautherized user...";
// Unauthorized, so we should unlink them. You may want to
// automatically log the user out in this case.
}
else if (e.error == DropboxServerException._403_FORBIDDEN)
{
mErrorMsg = "Server Error : Access denied";
// Not allowed to access this
}
else if (e.error == DropboxServerException._404_NOT_FOUND)
{
no_file = true;
doFirstTime();
// path not found
}
else if (e.error == DropboxServerException._406_NOT_ACCEPTABLE)
{
mErrorMsg = "Server Error : Congestion...";
// too many entries to return
}
else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE)
{
// user is over quota
mErrorMsg = "Server Error : Insufficient Storage...";
}
else
{
// Something else
mErrorMsg = "Server Error...";
}
// This gets the Dropbox error, translated into the user's language
mErrorMsg = e.body.userError;
if (mErrorMsg == null)
{
mErrorMsg = e.body.error;
}
}
catch (DropboxIOException e)
{
// Happens all the time, probably want to retry automatically.
mErrorMsg = "Network error. Try again.";
}
catch (DropboxParseException e)
{
// Probably due to Dropbox server restarting, should retry
mErrorMsg = "Dropbox error. Try again.";
}
catch (DropboxException e)
{
// Unknown error
mErrorMsg = "Unknown error. Try again.";
}
return false;
}
public void fillDBwithDropboxRecords()
{
Log.d("In fill db","yetoy");
try
{
for(int i=0 ; i<dropbox_records.size()-1 ; i++)
{
{
eop.addRecord(Integer.parseInt(dropbox_records.get(i).get(0)), dropbox_records.get(i).get(1), dropbox_records.get(i).get(2), Integer.parseInt(dropbox_records.get(i).get(3)));
}
}
}
catch (Exception e)
{
Log.d("In fill db", ""+e);
}
}
private void doFirstTime()
{
Log.d("yes2", " in do first time of download..");
try
{
if(!getDBRecords())
{
mErrorMsg = "No records exist to sync";
return;
}
newXMLCode.append("<smartexpense>");
for(int i=0 ; i<database_records.size() ; i++)
{
newXMLCode.append("<expenserecord>");
newXMLCode.append("<c_id>"+database_records.get(i).get(0)+"</c_id>");
newXMLCode.append("<title>"+database_records.get(i).get(1)+"</title>");
newXMLCode.append("<date>"+database_records.get(i).get(2)+"</date>");
newXMLCode.append("<amount>"+database_records.get(i).get(3)+"</amount>");
newXMLCode.append("</expenserecord>");
}//for
newXMLCode.append("</smartexpense>");
up = new UploadFile(mContext,mApi,newXMLCode.toString());
up.execute();
}
catch(Exception e)
{
Log.d("Exception in doFirtstTime : ",""+e);
}
}//doFirstTime
public void makeDropboxRecordArray()
{
Log.d("yes3", " in make record array of download..");
try
{
dropbox_xml_records = (xmlcode.toString()).split("</expenserecord>");
for(int i=0 ; i< dropbox_xml_records.length ; i++)
{
dropbox_records.add(new ArrayList<String>());
dropbox_records.get(i).add(dropbox_xml_records[i].substring(
((dropbox_xml_records[i].indexOf("<c_id>"))+
("<c_id>".length())),
dropbox_xml_records[i].indexOf("</c_id>")
));
dropbox_records.get(i).add(dropbox_xml_records[i].substring(
((dropbox_xml_records[i].indexOf("<title>"))+
("<title>".length())),
dropbox_xml_records[i].indexOf("</title>")
));
dropbox_records.get(i).add(dropbox_xml_records[i].substring(
((dropbox_xml_records[i].indexOf("<date>"))+
("<date>".length())),
dropbox_xml_records[i].indexOf("</date>")
));
dropbox_records.get(i).add(dropbox_xml_records[i].substring(
((dropbox_xml_records[i].indexOf("<amount>"))+
("<amount>".length())),
dropbox_xml_records[i].indexOf("</amount>")
));
}
}
catch (Exception e)
{
Toast.makeText(mContext,"In fill records :"+e , 2000).show();
}
}
public boolean getDBRecords()
{
Log.d("yes4", " in get dbrecords of download..");
try
{
Cursor cc = eop.getRecords();
if(cc.getCount() == 0)
return false;
int i=0;
if(cc.moveToFirst())
{
do
{
database_records.add(new ArrayList<String>());
database_records.get(i).add(cc.getString(cc.getColumnIndex("c_id")));
database_records.get(i).add(cc.getString(cc.getColumnIndex("title")));
database_records.get(i).add(cc.getString(cc.getColumnIndex("date")));
database_records.get(i).add(cc.getString(cc.getColumnIndex("amount")));
i++;
}while(cc.moveToNext());
}
cc.close();
}
catch(Exception ee)
{
Toast.makeText(mContext,"getDBRecords :"+ee , 2000).show();
}
return true;
}
public void performSync()
{
try
{
//compare database records with dropbox records
newXMLCode.append("<smartexpense>");
for(int i=0 ; i<database_records.size() ; i++)
{
newXMLCode.append("<expenserecord>");
newXMLCode.append("<c_id>"+database_records.get(i).get(0)+"</c_id>");
newXMLCode.append("<title>"+database_records.get(i).get(1)+"</title>");
newXMLCode.append("<date>"+database_records.get(i).get(2)+"</date>");
newXMLCode.append("<amount>"+database_records.get(i).get(3)+"</amount>");
newXMLCode.append("</expenserecord>");
}
for(int i=0 ; i<dropbox_records.size()-1 ; i++)
{
eop.addRecord(Integer.parseInt(dropbox_records.get(i).get(0)),
dropbox_records.get(i).get(1),
dropbox_records.get(i).get(2),
Integer.parseInt(dropbox_records.get(i).get(3)));
newXMLCode.append("<expenserecord>");
newXMLCode.append("<c_id>"+dropbox_records.get(i).get(0)+"</c_id>");
newXMLCode.append("<title>"+dropbox_records.get(i).get(1)+"</title>");
newXMLCode.append("<date>"+dropbox_records.get(i).get(2)+"</date>");
newXMLCode.append("<amount>"+dropbox_records.get(i).get(3)+"</amount>");
newXMLCode.append("</expenserecord>");
}
//}
newXMLCode.append("</smartexpense>");
Log.d("Comming : ","yetoy..");
up = new UploadFile(mContext,mApi,newXMLCode.toString());
up.execute();
}
catch (Exception e)
{
Log.d("Perform sync: ",""+e);
}
}
#Override
protected void onPostExecute(Boolean result)
{
//mDbHelper.close();
if (result)
{
//showToast("File successfully downloaded");
}
else
{
if(!no_file)
{
// Couldn't download it, so show an error
showToast("Error in sync.Check notification.");
Notification("SmartExpense", mErrorMsg);
}
}
}
private void showToast(String msg)
{
Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
error.show();
}
// Notification Function
private void Notification(String notificationTitle, String notificationMessage)
{
NotificationManager notificationManager = (NotificationManager)mContext.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(android.R.drawable.ic_menu_save, "Dropbox Sync", System.currentTimeMillis());
Intent notificationIntent = new Intent(mContext, UploadFile.class);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, 0);
notification.setLatestEventInfo(mContext, notificationTitle, notificationMessage, pendingIntent);
notificationManager.notify(10001, notification);
}
}
This error is received while you try and update your UI from a background thread. In your case the doInBackground method.
It appears that you are trying to post a notification from doInBackground from the following line.
Notification("SmartExpense", "Now syncing to dropbox");
This might be causing the issue. Try commenting this and any other UI updates you might be doing in doInBackground
This Exception indicates that you are trying to access UI elements in a non UI thread. From your code probably the problem is caused by these two lines inside your doInBackground method (you are accessing the Activity's context):
String cachefilePath = mContext.getCacheDir().getAbsolutePath() + "/" + FILE_NAME;
String cachezipPath = mContext.getCacheDir().getAbsolutePath() + "/" + ZIP_FILE_NAME;
If you declare this two variables outside the doInBackgroud method and instatiate them in your constructor, you should be ok. Also, remove the lines in your code that you are calling Looper.prepare() since they will not fix the problem.
The only way to get and visualize the data table of my database inside external devices is by atribution of privilege of superuser privilege in external device? Don't exist another way that allow visualize the data tables as in emulator?
I make this question because this way of superuser privilege not inspire me security.
Thanks for your attention (PS: Sorry by mistakes, but english is not my mother language :) )
You can add functionality to export the database file from the internal read-only app storage to the SD-Card by simply letting your app copy the file.
Then use whatever ways you have to get it from there. Works on any device and no root required.
private void exportDb() {
File database = getDatabasePath("myDb.db");
File sdCard = new File(Environment.getExternalStorageDirectory(), "myDb.db");
if (copy(database, sdCard)) {
Toast.makeText(this, "Get db from " + sdCard.getPath(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Copying the db failed", Toast.LENGTH_LONG).show();
}
}
private static boolean copy(File src, File target) {
// try creating necessary directories
target.mkdirs();
boolean success = false;
FileOutputStream out = null;
FileInputStream in = null;
try {
out = new FileOutputStream(target);
in = new FileInputStream(src);
byte[] buffer = new byte[8 * 1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
success = true;
} catch (FileNotFoundException e) {
// maybe log
} catch (IOException e) {
// maybe log
} finally {
close(in);
close(out);
}
if (!success) {
// try to delete failed attempts
target.delete();
}
return success;
}
private static void close(final Closeable closeMe) {
if (closeMe != null)
try {
closeMe.close();
} catch (IOException ignored) {
// ignored
}
}