Error Invalid DriveId while retrieving files from google Drive - android

Brief Description:
In the following code what i am trying to do is when the new file is created in the drive folder i want to store the file Id in local database and this id i will be using to get that file.
upload() in this it will actually create files and upload to drive
fileIds.add(dfres.getDriveFile().getDriveId().encodeToString() Is it correct?
sync()
This is Where i am getting error:-
DriveId did = DriveId.decodeFromString(dbfileid.get(i));
Please Help
Code : *EDITED *
public class MainActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener {
SQLiteOpenHelper dbhelper;
SQLiteDatabase database;
int j=0;
private static final String LOGTAG="EXPLORECA";
private static final String DATABASE_NAME="file.db";
private static final int DATABASE_VERSION=1;
private static final String TABLE="fileids";
private static final String filename="fname";
private static final String fileid="fid";
Date driveFileDate=new Date();
Date localFileDate=new Date();
ArrayList<String> fileNames = new ArrayList<String>();
ArrayList<String> fileIds = new ArrayList<String>();
ArrayList<String> dbfilename = new ArrayList<String>();
ArrayList<String> dbfileid = new ArrayList<String>();
long lastSyncTime=0;
private static final int REQUEST_CODE_RESOLUTION = 3;
//String[] fileNames = new String[]{""};
Button b1;
private ContentsResult result;
private GoogleApiClient mGoogleApiClient;
byte[] buffer;
int i=111;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lastSyncTime= System.currentTimeMillis()-200000;
//b1=(Button)findViewById(R.id.button1);
getfiles();
if(fileNames.size()>0)
{
if (mGoogleApiClient == null) {
// Create the API client and bind it to an instance variable.
// We use this instance as the callback for connection and connection
// failures.
// Since no account name is passed, the user is prompted to choose.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
// Connect the client. Once connected, the camera is launched.
try
{
mGoogleApiClient.connect();
}catch(Exception e)
{
showToast(""+e.toString());
}
}
else
{
showToast("Else Part ");
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
showToast("connected");
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("Sky folder").build();
DriveFolderResult sky = Drive.DriveApi.getRootFolder(getGoogleApiClient()).createFolder(
getGoogleApiClient(), changeSet).await();
showToast("folder created");
upload();
}
}
private void upload() {
// TODO Auto-generated method stub
showToast("Inside Connected");
for(int i=0;i<fileNames.size();i++)
{
result = Drive.DriveApi.newContents(mGoogleApiClient).await();
OutputStream outputStream = result.getContents().getOutputStream();
String s=Environment.getExternalStorageDirectory().toString()+"/AudioRecorder";
File file = new File(s+"/"+fileNames.get(i));
showToast(file.getName()+" id uploading");
// showToast("Path="+Environment.DIRECTORY_DOWNLOADS+"/k.mp3 "+file.length());
buffer = new byte[(int)file.length()];
try {
showToast("started reading n writing");
FileInputStream is = new FileInputStream(file);
//ByteArrayInputStream iss = new ByteArrayInputStream(buffer, 0, 0);
int l =is.read(buffer);
//is.read
outputStream.write(buffer);
showToast("Buffer is written");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
showToast(""+e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
showToast(""+e.toString());
}
showToast(""+result.getContents().toString());
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(fileNames.get(i)+i)
.setMimeType("audio/MP3")
.setStarred(true).build();
showToast("meta data created");
DriveFileResult dfres= Drive.DriveApi.getRootFolder(getGoogleApiClient())
.createFile(getGoogleApiClient(), changeSet, result.getContents())
.await();
showToast("await() complete");
if (!result.getStatus().isSuccess()) {
showToast("Error while trying to create the file");
return;
}
fileIds.add(dfres.getDriveFile().getDriveId().encodeToString());
// showToast("Created a file: " + dfres.getDriveFile().getDriveId());
}
showToast("fileIds = "+fileIds.size()+" first file"+fileIds.get(0));
add_to_db();
getvalues();
synch();
}
private void synch() {
// TODO Auto-generated method stub
for(int i=0;i<fileIds.size();i++)
{
String path = Environment.getExternalStorageDirectory().toString()+"/AudioRecorder/"+dbfilename.get(i);
showToast("Files Path: " + path);
File f = new File(path);
//long fileModifiedTime = f.lastModified();
localFileDate= new Date(f.lastModified());
showToast(""+localFileDate);
//fetchDriveId(getGoogleApiClient(), dbfileid.get(i).toString()).await();
DriveId did = DriveId.decodeFromString(dbfileid.get(i));
DriveFile file2= Drive.DriveApi.getFile(getGoogleApiClient(),did);
//DriveFile file2 = Drive.DriveApi.getFile(getGoogleApiClient(),result2.getDriveId());
MetadataResult metadata=file2.getMetadata(getGoogleApiClient()).await();
Metadata md =metadata.getMetadata();
driveFileDate=md.getModifiedByMeDate();
if(f.getName().equals(md.getTitle()))
{
showToast("File Not Changed"+f.getName()+" Drive Name"+md.getTitle());
}
else
{
if(localFileDate.getTime() < driveFileDate.getTime())
{
File f2 = new File(md.getTitle());
f.renameTo(f2);
showToast("After Renaming ="+f.getName());
}
else
{
MetadataChangeSet changeSet2 = new MetadataChangeSet.Builder()
.setStarred(true)
.setTitle(f.getName().toString()).build();
file2.updateMetadata(getGoogleApiClient(), changeSet2).await();
showToast("file renamed in drive");
}
}
}
}
private void getfiles() {
// TODO Auto-generated method stub
String path = Environment.getExternalStorageDirectory().toString()+"/AudioRecorder";
showToast("Files Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
//showToast("Files Size: "+ file.length);
for (int i=0; i < file.length; i++)
{
// showToast("Files FileName:" + file[i].getName());
if(file[i].getName().contains(".mp3")||file[i].getName().contains(".wav"))
{
if(lastSyncTime < file[i].lastModified())
{
fileNames.add(file[i].getName().toString());
}
}
}
showToast("fileNames contains:"+fileNames.size());
}
private void getDriveFiles() {
// TODO Auto-generated method stub
showToast("Getting Drive files");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// TODO Auto-generated method stub
// Called whenever the API client fails to connect.
//Log.i("GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
// show the localized error dialog.
showToast("Error in on connection failed");
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
return;
}
// The failure has a resolution. Resolve it.
// Called typically when the app is not yet authorized, and an
// authorization
// dialog is displayed to the user.
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
showToast("error"+e.toString());
// Log.e(TAG, "Exception while starting resolution activity", e);
}
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == RESULT_OK) {
mGoogleApiClient.connect();
showToast("Connected");
}
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
public GoogleApiClient getGoogleApiClient() {
return mGoogleApiClient;
}
public void showToast(final String toast) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), toast, Toast.LENGTH_SHORT).show();
}
});
}
public void add_to_db()
{
dbhelper=new fileiddb(this);
database=dbhelper.getWritableDatabase();
ContentValues values = new ContentValues();
for(int i=0;i< fileNames.size();i++)
{
String name = fileNames.get(i);
String id = fileIds.get(i).substring(8);
showToast("database id ="+id);
values.put(filename,name);
values.put(fileid,id);
}
database.insert(TABLE, null, values);
database.close();
Toast.makeText(this,"Added Successfully" ,Toast.LENGTH_LONG).show();
}
public void getvalues()
{
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE;
dbhelper=new fileiddb(this);
database=dbhelper.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
dbfilename.add(cursor.getString(0));
dbfileid.add(cursor.getString(1));
showToast(dbfilename.get(j).toString()+" = "+dbfileid.get(j).toString());
j++;
} while (cursor.moveToNext());
}
}
}
fileiddb.java
public class fileiddb extends SQLiteOpenHelper {
private static final String LOGTAG="EXPLORECA";
private static final String DATABASE_NAME="file.db";
private static final int DATABASE_VERSION=1;
private static final String TABLE="fileids";
private static final String filename="fname";
private static final String fileid="fid";
private static final String TABLE_CREATE=
"CREATE TABLE "+TABLE +
" ("
+filename+" TEXT,"
+fileid +" TEXT primary key not null "
+")";
public fileiddb(Context context) {
super(context, DATABASE_NAME, null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(TABLE_CREATE);
Log.i(LOGTAG,"Table is Created");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i2) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS "+TABLE);
onCreate(sqLiteDatabase);
}
}

How can the code above even work / compile if you initialize and connect 'mGoogleApiClient' and you use 'getGoogleApiClient()' coming from godknowswhere. I recommend you start with primitive example like this one and build from there. The example is as simple as you can get the GAC class is a complete wrapper for most of the GDAA scenarios, and if you start building from there, most of your questions will be answered by your own debugger.

Related

App stops whenever I press back button

Problem: This only happening on some pages. when I press back app stops. I get this error. I am not able to figure it out the exact problem. I am new to android. and this is happening at many pages.Any help would be highly appreciated.
logcat error:
InputEventSender:Exception dispatching finished signal.E/MessageQueue-JNI:Exception in MessageQueue callback:handleReceiveCallbackE/MessageQueue-JNI:java.lang.NullPointerException: Attempt to invoke virtual method 'void android.database.sqlite.SQLiteDatabase.close()' on a null object reference at twik.in.DBHelper.close(DBHelper.java:102)at twik.in.ActivityMenuDetail.onBackPressed(ActivityMenuDetail.java:285)at android.app.Activity.onKeyUp(Activity.java:2477)at android.view.KeyEvent.dispatch(KeyEvent.java:2664)at android.app.Activity.dispatchKeyEvent(Activity.java:2730)
In error these two classes are mentioned so I am posting its code here
public class ActivityMenuDetail extends Activity {
ImageView imgPreview;
TextView txtText, txtSubText;
WebView txtDescription;
Button btnAdd;
ScrollView sclDetail;
ProgressBar prgLoading;
TextView txtAlert;
// declare dbhelper object
static DBHelper dbhelper;
// declare ImageLoader object
ImageLoader imageLoader;
// declare variables to store menu data
String Menu_image, Menu_name, Menu_serve, Menu_description;
double Menu_price;
int Menu_quantity;
long Menu_ID;
String MenuDetailAPI;
int IOConnect = 0;
// create price format
DecimalFormat formatData = new DecimalFormat("#.##");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_detail);
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.header)));
bar.setTitle("Service Centre Detail");
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
txtText = (TextView) findViewById(R.id.txtText);
txtSubText = (TextView) findViewById(R.id.txtSubText);
txtDescription = (WebView) findViewById(R.id.txtDescription);
btnAdd = (Button) findViewById(R.id.btnAdd);
//btnShare = (Button) findViewById(R.id.btnShare);
sclDetail = (ScrollView) findViewById(R.id.sclDetail);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
txtAlert = (TextView) findViewById(R.id.txtAlert);
// get screen device width and height
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int wPix = dm.widthPixels;
int hPix = wPix / 2 + 50;
// change menu image width and height
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(wPix, hPix);
imgPreview.setLayoutParams(lp);
imageLoader = new ImageLoader(ActivityMenuDetail.this);
dbhelper = new DBHelper(this);
// get menu id that sent from previous page
Intent iGet = getIntent();
Menu_ID = iGet.getLongExtra("menu_id", 0);
// Menu detail API url
MenuDetailAPI = Constant.MenuDetailAPI+"?accesskey="+Constant.AccessKey+"&menu_id="+Menu_ID;
// call asynctask class to request data from server
new getDataTask().execute();
// event listener to handle add button when clicked
btnAdd.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
// show input dialog
addtoCart();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_detail, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.cart:
// refresh action
Intent iMyOrder = new Intent(ActivityMenuDetail.this, ActivityCart.class);
startActivity(iMyOrder);
overridePendingTransition (R.anim.open_next, R.anim.close_next);
return true;
case android.R.id.home:
// app icon in action bar clicked; go home
this.finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// method to show number of order form
void addtoCart(){
// open database first
try{
dbhelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
if(dbhelper.isDataExist(Menu_ID)){
dbhelper.updateData(Menu_ID, 1, (Menu_price));
}else{
dbhelper.addData(Menu_ID, Menu_name, 1, (Menu_price));
}
startActivity(new Intent(ActivityMenuDetail.this,ActivityCart.class));
};
// asynctask class to handle parsing json in background
public class getDataTask extends AsyncTask<Void, Void, Void>{
// show progressbar first
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(8);
// if internet connection and data available show data
// otherwise, show alert text
if((Menu_name != null) && IOConnect == 0){
sclDetail.setVisibility(0);
imageLoader.DisplayImage(Constant.AdminPageURL+Menu_image, imgPreview);
txtText.setText(Menu_name);
txtSubText.setText("Price : " +Menu_price+" "+ActivityMenuList.Currency+"\n"+"Status : "+Menu_serve+"\n"+"Empty Slots : "+Menu_quantity);
txtDescription.loadDataWithBaseURL("", Menu_description, "text/html", "UTF-8", "");
txtDescription.setBackgroundColor(Color.parseColor("#e7e7e7"));
}else{
txtAlert.setVisibility(0);
}
}
}
// method to parse json data from server
public void parseJSONData(){
try {
// request data from menu detail API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(MenuDetailAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
// parse json data and store into tax and currency variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data"); // this is the "items: [ ] part
for (int i = 0; i < data.length(); i++) {
JSONObject object = data.getJSONObject(i);
JSONObject menu = object.getJSONObject("Menu_detail");
Menu_image = menu.getString("Menu_image");
Menu_name = menu.getString("Menu_name");
Menu_price = Double.valueOf(formatData.format(menu.getDouble("Price")));
Menu_serve = menu.getString("Serve_for");
Menu_description = menu.getString("Description");
Menu_quantity = menu.getInt("Quantity");
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// close database before back to previous page
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
dbhelper.close();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
//imageLoader.clearCache();
super.onDestroy();
}
#Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}
}
and debhelper class here
public class DBHelper extends SQLiteOpenHelper{
String DB_PATH;
private final static String DB_NAME = "db_order";
public final static int DB_VERSION = 1;
public static SQLiteDatabase db;
private final Context context;
private final String TABLE_NAME = "tbl_order";
private final String ID = "id";
private final String MENU_NAME = "Menu_name";
private final String QUANTITY = "Quantity";
private final String TOTAL_PRICE = "Total_price";
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
DB_PATH = Constant.DBPath;
}
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
SQLiteDatabase db_Read = null;
if(dbExist){
//do nothing - database already exist
}else{
db_Read = this.getReadableDatabase();
db_Read.close();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase(){
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
private void copyDataBase() throws IOException{
InputStream myInput = context.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException{
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
#Override
public void close() {
db.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
/** this code is used to get all data from database */
public ArrayList<ArrayList<Object>> getAllData(){
ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
Cursor cursor = null;
try{
cursor = db.query(
TABLE_NAME,
new String[]{ID, MENU_NAME, QUANTITY, TOTAL_PRICE},
null,null, null, null, null);
cursor.moveToFirst();
if (!cursor.isAfterLast()){
do{
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cursor.getLong(0));
dataList.add(cursor.getString(1));
dataList.add(cursor.getString(2));
dataList.add(cursor.getString(3));
dataArrays.add(dataList);
}
while (cursor.moveToNext());
}
cursor.close();
}catch (SQLException e){
Log.e("DB Error", e.toString());
e.printStackTrace();
}
return dataArrays;
}
/** this code is used to get all data from database */
public boolean isDataExist(long id){
boolean exist = false;
Cursor cursor = null;
try{
cursor = db.query(
TABLE_NAME,
new String[]{ID},
ID +"="+id,
null, null, null, null);
if(cursor.getCount() > 0){
exist = true;
}
cursor.close();
}catch (SQLException e){
Log.e("DB Error", e.toString());
e.printStackTrace();
}
return exist;
}
/** this code is used to get all data from database */
public boolean isPreviousDataExist(){
boolean exist = false;
Cursor cursor = null;
try{
cursor = db.query(
TABLE_NAME,
new String[]{ID},
null,null, null, null, null);
if(cursor.getCount() > 0){
exist = true;
}
cursor.close();
}catch (SQLException e){
Log.e("DB Error", e.toString());
e.printStackTrace();
}
return exist;
}
public void addData(long id, String menu_name, int quantity, double total_price){
// this is a key value pair holder used by android's SQLite functions
ContentValues values = new ContentValues();
values.put(ID, id);
values.put(MENU_NAME, menu_name);
values.put(QUANTITY, quantity);
values.put(TOTAL_PRICE, total_price);
// ask the database object to insert the new data
try{db.insert(TABLE_NAME, null, values);}
catch(Exception e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
public void deleteData(long id){
// ask the database manager to delete the row of given id
try {db.delete(TABLE_NAME, ID + "=" + id, null);}
catch (Exception e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
public void deleteAllData(){
// ask the database manager to delete the row of given id
try {db.delete(TABLE_NAME, null, null);}
catch (Exception e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
public void updateData(long id, int quantity, double total_price){
// this is a key value pair holder used by android's SQLite functions
ContentValues values = new ContentValues();
values.put(QUANTITY, quantity);
values.put(TOTAL_PRICE, total_price);
// ask the database object to update the database row of given rowID
try {db.update(TABLE_NAME, values, ID + "=" + id, null);}
catch (Exception e)
{
Log.e("DB Error", e.toString());
e.printStackTrace();
}
}}
The logcat says your dbhelper object is null when preforming close()
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
if (dbhelper != null)
dbhelper.close();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
}
That should fix the problem
From the error trace that you have provided, it seems that "db" instance in DBHelper is null. Therefore in your onBackPressed() when you try to close db by called dbHelper.close(), it's throwing the NullPointerException. Adding a null check will help.
// close database before back to previous page
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
dbhelper.close();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
}
The above function will eventually call the function below:
#Override
public void close() {
db.close();
}
Add a null check for "db"
#Override
public void close() {
if (db != null) {
db.close();
}
}
In a quick glance of your code, it seems that you are opening DB only on action like "add to cart".
void addtoCart(){
// open database first
try{
dbhelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
if(dbhelper.isDataExist(Menu_ID)){
dbhelper.updateData(Menu_ID, 1, (Menu_price));
}else{
dbhelper.addData(Menu_ID, Menu_name, 1, (Menu_price));
}
startActivity(new Intent(ActivityMenuDetail.this,ActivityCart.class));
};
If you try to close the screen without performing such action DB object would not be available.
This is because it may getting null object reference of dbhelper and also it doesn't need to use finish(); as when onBackPressed() called activity finished automatically.
if (dbhelper != null)
dbhelper.close();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
super.onBackPressed();
According to logcat you dbhelper is null, so its giving a NULL POINTER EXCEPTION.
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
dbhelper.close();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
}
In the above method, super.onBackPressed(); is called first before closing the database, which is not a good practice.
Change it to,
#Override
public void onBackPressed() {
if (dbhelper != null)
dbhelper.close();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
super.onBackPressed();
}
Also change,
public void close() {
db.close();
}
to
public void close() {
if(db!=null)
db.close();
}
in Dbhelper.class

How to wait for an activity to finish in asynctask

I know that the purpose of the AsyncTask is to run asynchronously with other tasks of the app and finish in the background, but apparently I need to do this, I need to start an activity from AsyncTask and since I cant extend an activity in this class I can not use startactivityforresult, so how can I wait till my activity finishes?
Here is my code:
public class ListSpdFiles extends AsyncTask<Void, Void, String[]> {
public AsyncResponse delegate = null;
private static final String TAG = "ListSpdFiles: ";
Context applicationContext;
ContentResolver spdappliationcontext;
public final CountDownLatch setSignal= new CountDownLatch(1);
private final ReentrantLock lock = new ReentrantLock();
String username = "";
/**
* Status code returned by the SPD on operation success.
*/
private static final int SUCCESS = 4;
private boolean createbutt;
private boolean deletebutt;
private String initiator;
private String path;
private String pass;
private String url;
private SecureApp pcas;
private boolean isConnected = false; // connected to PCAS service?
private String CurrentURL = null;
private PcasConnection pcasConnection = new PcasConnection() {
#Override
public void onPcasServiceConnected() {
Log.d(TAG, "pcasServiceConnected");
latch.countDown();
}
#Override
public void onPcasServiceDisconnected() {
Log.d(TAG, "pcasServiceDisconnected");
}
};
private CountDownLatch latch = new CountDownLatch(1);
public ListSpdFiles(boolean createbutt, boolean deletebutt, String url, String pass, Context context, String initiator, String path, AsyncResponse asyncResponse) {
this.initiator = initiator;
this.path = path;
this.pass= pass;
this.url= url;
this.createbutt= createbutt;
this.deletebutt=deletebutt;
applicationContext = context.getApplicationContext();
spdappliationcontext = context.getContentResolver();
delegate = asyncResponse;
}
private void init() {
Log.d(TAG, "starting task");
pcas = new AndroidNode(applicationContext, pcasConnection);
isConnected = pcas.connect();
}
private void term() {
Log.d(TAG, "terminating task");
if (pcas != null) {
pcas.disconnect();
pcas = null;
isConnected = false;
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
init();
}
#Override
protected String[] doInBackground(Void... params) {
CurrentURL = getLastAccessedBrowserPage();
// check if connected to PCAS Service
if (!isConnected) {
Log.v(TAG, "not connected, terminating task");
return null;
}
// wait until connection with SPD is up
try {
if (!latch.await(20, TimeUnit.SECONDS)) {
Log.v(TAG, "unable to connected within allotted time, terminating task");
return null;
}
} catch (InterruptedException e) {
Log.v(TAG, "interrupted while waiting for connection in lsdir task");
return null;
}
// perform operation (this is where the actual operation is called)
try {
return lsdir();
} catch (DeadServiceException e) {
Log.i(TAG, "service boom", e);
return null;
} catch (DeadDeviceException e) {
Log.i(TAG, "device boom", e);
return null;
}
}
#Override
protected void onPostExecute(String[] listOfFiles) {
super.onPostExecute(listOfFiles);
if (listOfFiles == null) {
Log.i(TAG, "task concluded with null list of files");
} else {
Log.i(TAG, "task concluded with the following list of files: "
+ Arrays.toString(listOfFiles));
}
term();
delegate.processFinish(username);
}
#Override
protected void onCancelled(String[] listOfFiles) {
super.onCancelled(listOfFiles);
Log.i(TAG, "lsdir was canceled");
term();
}
/**
* Returns an array of strings containing the files available at the given path, or
* {#code null} on failure.
*/
private String[] lsdir() throws DeadDeviceException, DeadServiceException {
Result<List<String>> result = pcas.lsdir(initiator, path); // the lsdir call to the
boolean crtbut = createbutt;
boolean dlbut= deletebutt;
ArrayList<String> mylist = new ArrayList<String>();
final Global globalVariable = (Global) applicationContext;
if (crtbut==false && dlbut == false){
if ( globalVariable.getPasswordButt()==false ) {
final boolean isusername = globalVariable.getIsUsername();
if (isusername == true) {
Log.i(TAG, "current url: " + CurrentURL);
if (Arrays.toString(result.getValue().toArray(new String[0])).contains(CurrentURL)) {
String sharareh = Arrays.toString(result.getValue().toArray(new String[0]));
String[] items = sharareh.split(", ");
for (String item : items) {
String trimmed;
if (item.startsWith("[" + CurrentURL + ".")) {
trimmed = item.replace("[" + CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
} else if (item.startsWith(CurrentURL + ".")) {
trimmed = item.replace(CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
}
}
}
globalVariable.setPopupdone(false);
Intent i = new Intent(applicationContext, PopUp.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("EXTRA_SESSION_ID", mylist);
applicationContext.startActivity(i);
username = globalVariable.getUsername();
}
else if (isusername == false)
Log.i(TAG, "Wrong Input Type For Username.");
}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
//}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
public String getLastAccessedBrowserPage() {
String Domain = null;
Cursor webLinksCursor = spdappliationcontext.query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, null, null, Browser.BookmarkColumns.DATE + " DESC");
int row_count = webLinksCursor.getCount();
int title_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.TITLE);
int url_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.URL);
if ((title_column_index > -1) && (url_column_index > -1) && (row_count > 0)) {
webLinksCursor.moveToFirst();
while (webLinksCursor.isAfterLast() == false) {
if (webLinksCursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX) != 1) {
if (!webLinksCursor.isNull(url_column_index)) {
Log.i("History", "Last page browsed " + webLinksCursor.getString(url_column_index));
try {
Domain = getDomainName(webLinksCursor.getString(url_column_index));
Log.i("Domain", "Last page browsed " + Domain);
return Domain;
} catch (URISyntaxException e) {
e.printStackTrace();
}
break;
}
}
webLinksCursor.moveToNext();
}
}
webLinksCursor.close();
return null;
}
public String getDomainName(String url) throws URISyntaxException {
URI uri = new URI(url);
String domain = uri.getHost();
return domain.startsWith("www.") ? domain.substring(4) : domain;
}}
My Activity class:
public class PopUp extends Activity {
private static final String TAG = "PopUp";
ArrayList<String> value = null;
ArrayList<String> usernames;
#Override
protected void onCreate(Bundle savedInstanceState) {
final Global globalVariable = (Global) getApplicationContext();
globalVariable.setUsername("");
Bundle extras = getIntent().getExtras();
if (extras != null) {
value = extras.getStringArrayList("EXTRA_SESSION_ID");
}
usernames = value;
super.onCreate(savedInstanceState);
setContentView(R.layout.popupactivity);
final Button btnOpenPopup = (Button) findViewById(R.id.openpopup);
btnOpenPopup.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button btnSelect = (Button) popupView.findViewById(R.id.select);
Spinner popupSpinner = (Spinner) popupView.findViewById(R.id.popupspinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(PopUp.this, android.R.layout.simple_spinner_item, usernames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
popupSpinner.setAdapter(adapter);
popupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
globalVariable.setUsername(usernames.get(arg2));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
btnSelect.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
globalVariable.setPopupdone(true);
popupWindow.dismiss();
finish();
}
}
);
popupWindow.showAsDropDown(btnOpenPopup, 50, -30);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.poupup_menu, menu);
return true;
}}

Call an AsyncTask subclass of activity from another class?

I know this kind of questions are maybe too old, but I got stock with this silly thing.
I have an AsyncTask class which is a subclass of an activity class, and right now I want to call it from another class: following codes shows what I mean:
public class STA extends Activity {
public class ListSpdFiles extends AsyncTask<Void, Void, String[]> {
private static final String TAG = "ListSpdFiles: ";
/**
* Status code returned by the SPD on operation success.
*/
private static final int SUCCESS = 4;
private String initiator;
private String path;
private SecureApp pcas;
private boolean isConnected = false; // connected to PCAS service?
private PcasConnection pcasConnection = new PcasConnection() {
#Override
public void onPcasServiceConnected() {
Log.d(TAG, "pcasServiceConnected");
latch.countDown();
}
#Override
public void onPcasServiceDisconnected() {
Log.d(TAG, "pcasServiceDisconnected");
}
};
private CountDownLatch latch = new CountDownLatch(1);
public ListSpdFiles(String initiator, String path) {
this.initiator = initiator;
this.path = path;
}
private void init() {
Log.d(TAG, "starting task");
pcas = new AndroidNode(getApplicationContext(), pcasConnection);
isConnected = pcas.connect();
}
private void term() {
Log.d(TAG, "terminating task");
if (pcas != null) {
pcas.disconnect();
pcas = null;
isConnected = false;
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
init();
}
#Override
protected String[] doInBackground(Void... params) {
// check if connected to PCAS Service
if (!isConnected) {
Log.v(TAG, "not connected, terminating task");
return null;
}
// wait until connection with SPD is up
try {
if (!latch.await(20, TimeUnit.SECONDS)) {
Log.v(TAG, "unable to connected within allotted time, terminating task");
return null;
}
} catch (InterruptedException e) {
Log.v(TAG, "interrupted while waiting for connection in lsdir task");
return null;
}
// perform operation (this is where the actual operation is called)
try {
return lsdir();
} catch (DeadServiceException e) {
Log.i(TAG, "service boom", e);
return null;
} catch (DeadDeviceException e) {
Log.i(TAG, "device boom", e);
return null;
}
}
#Override
protected void onPostExecute(String[] listOfFiles) {
super.onPostExecute(listOfFiles);
if (listOfFiles == null) {
Log.i(TAG, "task concluded with null list of files");
// tv.setText("task concluded with a null list of files");
} else {
Log.i(TAG, "task concluded with the following list of files: "
+ Arrays.toString(listOfFiles));
//tv.setText("List of files received is:\n" + Arrays.toString(listOfFiles));
}
term();
}
#Override
protected void onCancelled(String[] listOfFiles) {
super.onCancelled(listOfFiles);
Log.i(TAG, "lsdir was canceled");
term();
}
/**
* Returns an array of strings containing the files available at the given path, or
* {#code null} on failure.
*/
private String[] lsdir() throws DeadDeviceException, DeadServiceException {
Result<List<String>> result = pcas.lsdir(initiator, path); // the lsdir call to the
final Global globalVariable = (Global) getApplicationContext();
if (globalVariable.getPasswordButt() == false) {
// Calling Application class (see application tag in AndroidManifest.xml)
// Get name and email from global/application context
final boolean isusername = globalVariable.getIsUsername();
if (isusername == true) {
String username = "/" + getLastAccessedBrowserPage() + ".username" + ".txt";
//String password = "/" + CurrentURL + "password" + ".txt";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
pcas.readFile(initiator, username, baos);
Log.i(TAG, "OutputStreampassword: "
+ new String(baos.toByteArray()));
String name = new String(baos.toByteArray());
if (!name.equalsIgnoreCase("")) {
globalVariable.setUsername(name);
// getCurrentInputConnection().setComposingText(name, 1);
// updateCandidates();
}
globalVariable.setIsUsername(false);
} else if (isusername == false)
Log.i(TAG, "Wrong Input Type For Username.");
// globalVariable.setUsernameButt(false);
} else if (globalVariable.getPasswordButt() == true) {
// Calling Application class (see application tag in AndroidManifest.xml)
// final Global globalVariable = (Global) getApplicationContext();
// Get name and email from global/application context
final boolean ispassword = globalVariable.getIsPassword();
if (ispassword == true) {
// String username = "/" + CurrentURL + "username" + ".txt";
String password = "/" + getLastAccessedBrowserPage() + ".password" + ".txt";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
pcas.readFile(initiator, password, baos);
Log.i(TAG, "OutputStreampassword: "
+ new String(baos.toByteArray()));
String name = new String(baos.toByteArray());
if (!name.equalsIgnoreCase("")) {
globalVariable.setPassword(name);
//getCurrentInputConnection().setComposingText(name, 1);
// updateCandidates();
}
globalVariable.setIsPassword(false);
} else if (ispassword == false)
Log.i(TAG, "Wrong Input Type For Password.");
globalVariable.setPasswordButt(false);
// boolpassword=false;
}
//}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
}
public String getLastAccessedBrowserPage() {
String Domain = null;
Cursor webLinksCursor = getContentResolver().query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, null, null, Browser.BookmarkColumns.DATE + " DESC");
int row_count = webLinksCursor.getCount();
int title_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.TITLE);
int url_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.URL);
if ((title_column_index > -1) && (url_column_index > -1) && (row_count > 0)) {
webLinksCursor.moveToFirst();
while (webLinksCursor.isAfterLast() == false) {
if (webLinksCursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX) != 1) {
if (!webLinksCursor.isNull(url_column_index)) {
Log.i("History", "Last page browsed " + webLinksCursor.getString(url_column_index));
try {
Domain = getDomainName(webLinksCursor.getString(url_column_index));
Log.i("Domain", "Last page browsed " + Domain);
return Domain;
} catch (URISyntaxException e) {
e.printStackTrace();
}
break;
}
}
webLinksCursor.moveToNext();
}
}
webLinksCursor.close();
return null;
}
public String getDomainName(String url) throws URISyntaxException {
URI uri = new URI(url);
String domain = uri.getHost();
return domain.startsWith("www.") ? domain.substring(4) : domain;
}}
Would you please tell me what should I do to fix this code?
Looking over the code I did not see anywhere you referenced anything from the Activity itself besides the application context so you can move the ListSpdFiles class to its own java file and pass it a context into the constructor when you make a new instance of it.
Put this class in a ListSpdFiles.java file so it is no longer an inner class.
public class ListSpdFiles extends AsyncTask<Void, Void, String[]> {
Context applicationContext;
public ListSpdFiles(Context context, String initiator, String path) {
this.initiator = initiator;
this.path = path;
applicationContext = context.getApplicationContext();
}
// The rest of your code still goes here. Replace other calls to
// getApplicationContext() with the new applicationContext field
}
You can now use this class anywhere a Context is available. You create a new instance by doing:
ListSpdFiles listSpdFilesTask = new ListSpdFiles(context, "someInitiator", "somePath");
listSpdFilesTask.execute();

How do I download several images from Dropbox via API?

I wanted to download images via Dropbox API so i followed the sample code # Android Dropbox API file download but i do not understand how to integrate it into my current code. I tried changing api.getFileStream("dropbox", dbPath, null); to dropbox.getFileStream("dropbox", dbPath, null); resulting in the error:
'getFileStream(java.lang.String, java.lang.String)' in 'com.dropbox.client2.DropboxAPI' cannot be applied to '(java.lang.String, java.lang.String, null)'
Updated 1 : Changed to `dropbox.getFileStream(FILE_DIR,null)
Main Code
public class Dropbox extends AppCompatActivity implements View.OnClickListener {
private DropboxAPI<AndroidAuthSession> dropbox;
private final static String FILE_DIR = "/DropboxSample/";
private final static String DROPBOX_NAME = "dropbox_prefs";
private final static String ACCESS_KEY = "Insert Key here";
private final static String ACCESS_SECRET = "Insert Key here";
private boolean isLoggedIn;
private Button logIn;
private Button uploadFile;
private Button downloadFile;
private Button listFiles;
private LinearLayout container;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dropbox);
logIn = (Button) findViewById(R.id.dropbox_login);
logIn.setOnClickListener(this);
uploadFile = (Button) findViewById(R.id.upload_file);
uploadFile.setOnClickListener(this);
downloadFile = (Button) findViewById(download_file);
downloadFile.setOnClickListener(this);
listFiles = (Button) findViewById(R.id.list_files);
listFiles.setOnClickListener(this);
container = (LinearLayout) findViewById(R.id.container_files);
loggedIn(false);
AndroidAuthSession session;
AppKeyPair pair = new AppKeyPair(ACCESS_KEY, ACCESS_SECRET);
SharedPreferences prefs = getSharedPreferences(DROPBOX_NAME, 0);
String key = prefs.getString(ACCESS_KEY, null);
String secret = prefs.getString(ACCESS_SECRET, null);
if (key != null && secret != null) {
AccessTokenPair token = new AccessTokenPair(key, secret);
session = new AndroidAuthSession(pair ,token);
} else {
session = new AndroidAuthSession(pair );
}
dropbox = new DropboxAPI<>(session);
}
#Override
protected void onResume() {
super.onResume();
AndroidAuthSession session = dropbox.getSession();
if (session.authenticationSuccessful()) {
try {
session.finishAuthentication();
TokenPair tokens = session.getAccessTokenPair();
SharedPreferences prefs = getSharedPreferences(DROPBOX_NAME, 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(ACCESS_KEY, tokens.key);
editor.putString(ACCESS_SECRET, tokens.secret);
editor.commit();
loggedIn(true);
} catch (IllegalStateException e) {
Toast.makeText(this, "Error during Dropbox authentication",
Toast.LENGTH_SHORT).show();
}
}
}
public void loggedIn(boolean isLogged) {
isLoggedIn = isLogged;
uploadFile.setEnabled(isLogged);
downloadFile.setEnabled(isLogged);
listFiles.setEnabled(isLogged);
logIn.setText(isLogged ? "Log out" : "Log in");
}
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
ArrayList<String> result = msg.getData().getStringArrayList("data");
for (String fileName : result) {
Log.i("ListFiles", fileName);
TextView tv = new TextView(Dropbox.this);
tv.setText(fileName);
container.addView(tv);
}
}
};
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.dropbox_login:
if (isLoggedIn) {
dropbox.getSession().unlink();
loggedIn(false);
} else {
dropbox.getSession().startAuthentication(Dropbox.this);
}
break;
case R.id.list_files:
ListDropboxFiles list = new ListDropboxFiles(dropbox, FILE_DIR,
handler);
list.execute();
break;
case R.id.upload_file:
UploadFileToDropbox upload = new UploadFileToDropbox(dropbox, FILE_DIR);
upload.execute();
break;
case R.id.download_file:
try {
downloadDropboxFile(FILE_DIR,(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES+"CapturyGallery")));
} catch (IOException e) {
e.printStackTrace();
}
break;
default:
break;
}
}
public class UploadFileToDropbox extends AsyncTask<Void, Long, Boolean> {
private DropboxAPI<?> dropbox;
private String mPath;
private Context mContext;
private final ProgressDialog mDialog;
private DropboxAPI.UploadRequest mRequest;
private String mErrorMsg;
private File[] listFile;
private int mFilesUploaded;
private int mCurrentFileIndex;;
public UploadFileToDropbox(DropboxAPI<?> dropbox, String path) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "/CapturyGallery");
listFile = file.listFiles();
mContext = Dropbox.this;
this.dropbox = dropbox;
this.mPath = path;
mFilesUploaded = 0 ;
mCurrentFileIndex = 0 ;
mDialog = new ProgressDialog(mContext);
mDialog.setMax(100);
mDialog.setMessage("Uploading file 1 /" +listFile.length);
mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.setProgress(0);
mDialog.setButton(ProgressDialog.BUTTON_POSITIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// This will cancel the putFile operation
try {
mRequest.abort();
} catch (Exception e) {
}
}
});
mDialog.show();
mDialog.setCanceledOnTouchOutside(false);
}
#Override
protected Boolean doInBackground(Void... params) {
try {
for (int y = 0; y < listFile.length; y++) {
mCurrentFileIndex = y;
File file = listFile[y];
// 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(file);
String path = mPath + file.getName();
mRequest = dropbox.putFileOverwriteRequest(path, fis, file.length(),
new ProgressListener() {
#Override
public long progressInterval() {
// Update the progress bar every half-second or so
return 5;
}
#Override
public void onProgress(long bytes, long total) {
if (isCancelled()) {
mRequest.abort();
} else {
publishProgress(bytes);
}
}
});
mRequest.upload();
if(!isCancelled()){
mFilesUploaded++;
}else{
return false;
}
}
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) {
// 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) {
long totalBytes = 0;
long bytesUploaded = 0;
for (int i = 0; i < listFile.length; i++) {
Long bytes = listFile[i].length();
totalBytes += bytes;
if (i < mCurrentFileIndex) {
bytesUploaded += bytes;
}
bytesUploaded += progress[0];
int percent = 100;
int percent1 = (int) (percent * (bytesUploaded/totalBytes));
mDialog.setMessage("Uploading file " + (mCurrentFileIndex + 1) + " / " + listFile.length);
mDialog.setProgress(percent1);
}
}
#Override
protected void onPostExecute(Boolean result) {
mDialog.dismiss();
if (result) {
showToast("Successfully uploaded");
} else {
showToast(mErrorMsg);
}
}
private void showToast(String msg) {
Toast error = Toast.makeText(Dropbox.this, msg, Toast.LENGTH_LONG);
error.show();
}
}
public class ListDropboxFiles extends AsyncTask<Void, Void, ArrayList<String>> {
private DropboxAPI<?> dropbox;
private String path;
private Handler handler;
public ListDropboxFiles(DropboxAPI<?> dropbox, String path, Handler handler) {
this.dropbox = dropbox;
this.path = path;
this.handler = handler;
}
#Override
protected ArrayList<String> doInBackground(Void... params) {
ArrayList<String> files = new ArrayList<String>();
try {
DropboxAPI.Entry directory = dropbox.metadata(path, 1000, null, true, null);
for (DropboxAPI.Entry entry : directory.contents) {
files.add(entry.fileName());
}
} catch (DropboxException e) {
e.printStackTrace();
}
return files;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
Message msgObj = handler.obtainMessage();
Bundle b = new Bundle();
b.putStringArrayList("data", result);
msgObj.setData(b);
handler.sendMessage(msgObj);
}
}
Added from Sample code
private boolean downloadDropboxFile(String dbPath, File localFile) throws IOException {
BufferedInputStream br = null;
BufferedOutputStream bw = null;
try {
if (!localFile.exists()) {
localFile.createNewFile(); //otherwise dropbox client will fail silently
}
FileDownload fd = dropbox.getFileStream("dropbox", dbPath, null);
br = new BufferedInputStream(fd.is);
bw = new BufferedOutputStream(new FileOutputStream(localFile));
byte[] buffer = new byte[4096];
int read;
while (true) {
read = br.read(buffer);
if (read <= 0) {
break;
}
bw.write(buffer, 0, read);
}
} finally {
//in finally block:
if (bw != null) {
bw.close();
}
if (br != null) {
br.close();
}
}
return true;
}
}
>
The error message is indicating that the method definition is:
getFileStream(java.lang.String, java.lang.String)
This is also what the documentation for the getFileStream method in the Dropbox Android Core SDK shows.
However, you're attempting to use three parameters:
(java.lang.String, java.lang.String, null)
So, to properly call the method, you should remove that last parameter (null).

Android: FTP client file transfer in passive mode taking time to close connection after 100% upload

Android: FTP client file transfer in passive mode taking time to close connection after 100% upload
While transferring files through FTP client, in passive mode, we are using async task.
Even after the progress update specified 100% of the file has been uploaded, still ftp connection holds async task from coming to on post execute.
The time taken is directly proportional to Internet speed and size of the file uploaded.
Tried with standalone application to upload zip files,
Tried ftp both in active and passive modes.
Still the issue persists.
public class UploadZipFiles extends AsyncTask<Object, Integer, Object> {
ArrayList<String> zipFiles;
String userName, password;
WeakReference<ServiceStatusListener> listenerReference;
private Context mContext;
private long totalFileSize = 0;
protected long totalTransferedBytes = 0;
final NumberFormat nf = NumberFormat.getInstance();
private CustomFtpClient ftpClient = null;
public UploadZipFiles(Context mContext, ServiceStatusListener listener,
ArrayList<String> zipFiles, String userName, String password) {
Log.d("u and p", "" + userName + "=" + password);
this.mContext = mContext;
this.zipFiles = zipFiles;
this.userName = userName;
this.password = password;
this.listenerReference = new WeakReference<ServiceStatusListener>(
listener);
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// getting total size of the file
for (String file : zipFiles) {
totalFileSize = totalFileSize + new File(file).length();
}
}
#Override
protected Object doInBackground(Object... arg0) {
ftpClient = new CustomFtpClient();
try {
ftpClient.connect(ftpUrl, 21);
ftpClient.login(userName, password);
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
for (String file : zipFiles) {
InputStream in;
in = new FileInputStream(new File(file));
ftpClient.storeFile(new File(file).getName(), in);
in.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
return "Success";
}
#Override
protected void onPostExecute(Object result) {
if (result instanceof Exception) {
listenerReference.get().onFailure(
new Exception(result.toString()));
} else {
listenerReference.get().onSuccess("Success");
}
}
#Override
protected void onProgressUpdate(Integer... values) {
int uploadProgress = ((float) values[0] / totalFileSize) * 100);
//Some code to show loader
.......
}
/** Custom client to publish progress **/
public class CustomFtpClient extends FTPClient {
public boolean storeFile(String remote, InputStream local)
throws IOException {
final OutputStream output;
final Socket socket;
if ((socket = _openDataConnection_(FTPCommand.STOR, remote)) == null)
return false;
output = new BufferedOutputStream(socket.getOutputStream(),
getBufferSize());
try {
Util.copyStream(local, output, getBufferSize(),
CopyStreamEvent.UNKNOWN_STREAM_SIZE,
new CopyStreamListener() {
#Override
public void bytesTransferred(
long totalBytesTransferred,
int bytesTransferred, long streamSize) {
totalTransferedBytes = totalTransferedBytes
+ bytesTransferred;
publishProgress((int) totalTransferedBytes);
if (totalTransferedBytes == totalFileSize) {
Log.d(TAG, "upload completed");
}
}
#Override
public void bytesTransferred(
CopyStreamEvent arg0) {
// TODO Auto-generated method stub
}
});
} catch (IOException e) {
try {
socket.close();
} catch (IOException f) {
}
throw e; }
output.close();
socket.close();
return completePendingCommand();
}
}
}

Categories

Resources