vendredi 1 mai 2015

exporting and importing contacts from an sd card

when i try to export all Contacts from the database to an sd card i get an error saying : java.io.FileNotFoundException:/data/data/com.androidhive.androidsqlite/databases/contactsManager: openfailes: EACCES (Permission denied)

the same error when i import and nothing shows in the listview.please kindly help

here is the code for the export an import function`

    Button b1 =(Button) 

    findViewById(R.id.button1);

    b1.setOnClickListener(new View.OnClickListener() {
        //--------------------------------------------------------------------------------------------
        //------------------------------------exporter------------------------------------------------
        //--------------------------------------------------------------------------------------------

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            // TODO Auto-generated method stub

            try {




                try {
                    //  File sd = Environment.getExternalStorageDirectory();
                    File data = Environment.getDataDirectory();
                    //  Log.i("sd", "" + sd.canWrite());
                    if (sd.canWrite()) {
                        //  String currentDBPath = "data/com.android.les_contacts/databases/contactsManager";

                        String currentDBPath =  "data/com.androidhive.androidsqlite/databases/contactsManager";



                        String backupDBPath = "BackupContacts";
                        File currentDB = new File(data, currentDBPath);
                        File backupDB = new File(sd, backupDBPath);
                        if (currentDB.exists()) {
                            FileChannel src = new FileInputStream(currentDB).getChannel();
                            FileChannel dst = new FileOutputStream(backupDB).getChannel();
                            dst.transferFrom(src, 0, src.size());
                            src.close();
                            dst.close();
                            Toast.makeText(getApplicationContext(), "Vos contacts ont �t� export�s avec succ�s!", Toast.LENGTH_SHORT).show();
                        }
                    }

                    //----------------test2-----------------------------------



                    db.deleteContact( db.getContact(0));
                    // Reading all contacts
                    Log.d("test2: ", "Reading all contacts.. apr� exportation");
                    List<Contact> contacts;
                    contacts=db.getAllContacts();


                    for (Contact cn : contacts) {
                        String log = "id: "+cn.get_id()+" ,nom: " + cn.get_nom() + " ,num: " + cn.get_num()
                                +  " ,email: " + cn.get_email()
                                + " ,adresse: " + cn.get_adresse();
                        // Writing Contacts to log


                        Log.d("nom: ", log);

                    }


                    //----------------test2-----------------------------------
                } catch (Exception e) {
                    Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
                }






            } catch (Exception e) {

                Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
                        .show();

            }

        }
    });
    //=======================================================================================================
    Button b2 =( Button ) findViewById(R.id.button2);
    b2.setOnClickListener(new View.OnClickListener() {
        //--------------------------------------------------------------------------------------------
        //------------------------------------importer------------------------------------------------
        //--------------------------------------------------------------------------------------------
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub


            try {


                try {
                    //      File sd = Environment.getExternalStorageDirectory();
                    File data = Environment.getDataDirectory();

                    if (sd.canWrite()) {
                        //  String currentDBPath = "data/com.android.les_contacts/databases/contactsManager";

                        String currentDBPath =  "data/com.androidhive.androidsqlite/databases/contactsManager";



                        String backupDBPath = "BackupContacts";


                        File currentDB = new File(data, currentDBPath);
                        File backupDB = new File(sd, backupDBPath);
                        if (currentDB.exists()) {
                            FileChannel src = new FileInputStream(backupDB).getChannel();
                            FileChannel dst = new FileOutputStream(currentDB).getChannel();
                            dst.transferFrom(src, 0, src.size());
                            src.close();
                            dst.close();
                            Toast.makeText(getApplicationContext(), "Vos contacts ont �t� import�s avec succ�s", Toast.LENGTH_SHORT).show();
                        }
                    }



                    //----------------test1-----------------------------------




                    // Reading all contacts
                    Log.d("test1: ", "Reading all contacts.. apr� importation");
                    List<Contact> contacts=new ArrayList<>();
                    contacts=db.getAllContacts();


                    for (Contact cn : contacts) {
                        String log = "id: "+cn.get_id()+" ,nom: " + cn.get_nom() + " ,num: " + cn.get_num()
                                +  " ,email: " + cn.get_email()
                                + " ,adresse: " + cn.get_adresse();
                        // Writing Contacts to log


                        Log.d("nom: ", log);

                    }


                    //----------------test1-----------------------------------


                } catch (Exception e) {
                    Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
                }










            } catch (Exception e) {
                Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
                        .show();

            }






        }
    });


}
}` 

the main Activity `

public class MainActivity extends Activity {
private static final int edit =0,supp=1;
EditText nameTxt, phoneTxt, emailTxt, adressTxt;
List<Contact> Contacts=new ArrayList<>();
ListView contactListView;

MySQLiteHelper db;
int longClickedItemIndex;
ArrayAdapter<Contact> contactAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameTxt = (EditText) findViewById(R.id.txtName);
phoneTxt = (EditText) findViewById(R.id.txtPhone);
emailTxt = (EditText) findViewById(R.id.txtEmail);
adressTxt = (EditText) findViewById(R.id.txtAdress);

contactListView= (ListView) findViewById(R.id.listView) ;

db= new MySQLiteHelper(getApplicationContext());
registerForContextMenu(contactListView);
contactListView.setOnItemLongClickListener(new        AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
     longClickedItemIndex= position;
        return false;


    }
});

TabHost tabHost = (TabHost) findViewById(R.id.tabHost);

tabHost.setup();
TabHost.TabSpec tabSpec = tabHost.newTabSpec("Ajouter");
tabSpec.setContent(R.id.Creatortab);
tabSpec.setIndicator("Ajouter ");
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("Liste");
tabSpec.setContent(R.id.listView);
tabSpec.setIndicator("Liste");
tabHost.addTab(tabSpec);


Button syncBtn =(Button) findViewById(R.id.btnSyncr);
final Button addBtn =(Button) findViewById(R.id.btnAdd);

nameTxt.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
        addBtn.setEnabled(String.valueOf(nameTxt.getText()).trim().length() >0);
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
});


             // Bouton Ajouter
addBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {Contact contact=new Contact(db.getContactsCount(),String.valueOf(nameTxt.getText())
            ,String.valueOf(phoneTxt.getText()),String.valueOf(emailTxt.getText()),String.valueOf(adressTxt.getText()));
       if(!contactExists(contact)) {
           db.addContact(contact);
           Contacts.add(contact);
           contactAdapter.notifyDataSetChanged();
           Toast.makeText(getApplicationContext(),nameTxt.getText().toString()  + " a ete crée",Toast.LENGTH_SHORT).show();
           return;
       }
        Toast.makeText(getApplicationContext(),nameTxt.getText().toString()  + " existe deja ressayer aves un autre Nom",Toast.LENGTH_SHORT).show();
    }
});
            // Bouton Syncroniser
syncBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
          Intent intent=new Intent(view.getContext(),Main.class);
        startActivityForResult(intent,0);
    }
});
if(db.getContactsCount() != 0)
Contacts.addAll(db.getAllContacts());

      populateList()
}
public void onCreateContextMenu(ContextMenu menu, View view,ContextMenu.ContextMenuInfo menuInfo){
    super.onCreateContextMenu(menu, view, menuInfo);
     menu.setHeaderIcon(R.drawable.pencil_icon);
    menu.setHeaderTitle("Option");
    menu.add(Menu.NONE, edit,Menu.NONE,"Editer Contacte");
    menu.add(Menu.NONE, supp,Menu.NONE,"Supprimer Contacte");
    }
    public boolean onContextItemSelected(MenuItem item){
    switch (item.getItemId())
    {
        case edit :
            //TODO: Implement editing a contact
            break;
        case supp:

            db.deleteContact(Contacts.get(longClickedItemIndex));
            Contacts.remove(longClickedItemIndex);
            contactAdapter.notifyDataSetChanged();
            break;
    }
    return super.onContextItemSelected(item);
    }
   private boolean contactExists(Contact contact){
   String name = contact.get_nom();
   int contactCount = Contacts.size();
   for(int i = 0; i < contactCount; i++){
    if(name.compareToIgnoreCase(Contacts.get(i).get_nom()) == 0)
        return true;
   }
   return false;

   }
   private void populateList(){
     contactAdapter = new ContactListeAdapter();
    contactListView.setAdapter(contactAdapter);
    }
   private class ContactListeAdapter extends ArrayAdapter<Contact>{
    private ContactListeAdapter() {
        super(MainActivity.this,R.layout.listview,Contacts);
    }
    @Override
    public View getView(int position, View view, ViewGroup parent){
        if(view ==null) //view n'est pas null
            view = getLayoutInflater().inflate(R.layout.listview, parent, false);

        Contact currentContact = Contacts.get(position);
        TextView nom =(TextView) view.findViewById(R.id.contactName);
        nom.setText(currentContact.get_nom());
        TextView num =(TextView) view.findViewById(R.id.phoneNumber);
        num.setText(currentContact.get_num());
        TextView email =(TextView) view.findViewById(R.id.emailAddress);
        email.setText(currentContact.get_email());
        TextView adresse =(TextView) view.findViewById(R.id.cAddress);
        adresse.setText(currentContact.get_adresse());
        return view;
    }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    return super.onCreateOptionsMenu(menu);
} 
}`

the database code:`

package com.informatique.contacts;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class MySQLiteHelper extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "contactsManager";

// Contacts table name
private static final String TABLE_CONTACTS = "contacts";

// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "nom";
private static final String KEY_PH_NO = "num";
private static final String KEY_EMAIL ="email";
private static final String KEY_ADRESS ="adresse";

public MySQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
            + KEY_PH_NO + " TEXT,"
            + KEY_EMAIL + " TEXT,"
            + KEY_ADRESS + " TEXT" +")";
    db.execSQL(CREATE_CONTACTS_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

    // Create tables again
    onCreate(db);
}

/**
 * All CRUD(Create, Read, Update, Delete) Operations
 */

// Adding new contact
void addContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_ID, contact.get_id()); // Contact id
    values.put(KEY_NAME, contact.get_nom()); // Contact Name
    values.put(KEY_PH_NO, contact.get_num()); // Contact Phone
    values.put(KEY_EMAIL, contact.get_email()); // Contact  Email
    values.put(KEY_ADRESS, contact.get_adresse()); //Contact Adress

    // Inserting Row
    db.insert(TABLE_CONTACTS, null, values);
    db.close(); // Closing database connection
}

// Getting single contact
Contact getContact(int id) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
                    KEY_NAME, KEY_PH_NO, KEY_EMAIL, KEY_ADRESS }, KEY_ID + "=?",
            new String[] { String.valueOf(id) }, null, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();

    Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
            cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4));
    // return contact
    return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
    List<Contact> contactList;
    contactList = new ArrayList<Contact>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    // looping through all rows and adding to list
    if (cursor.moveToFirst()) do {
        Contact contact = new Contact();
        contact.set_id(Integer.parseInt(cursor.getString(0)));
        contact.set_nom(cursor.getString(1));
        contact.set_num(cursor.getString(2));
        contact.set_email(cursor.getString(3));
        contact.set_adresse(cursor.getString(4));
        // Adding contact to list
        contactList.add(contact);
    } while (cursor.moveToNext());
    // return contact list
    return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.get_nom());
    values.put(KEY_PH_NO, contact.get_num());
    values.put(KEY_EMAIL, contact.get_email());
    values.put(KEY_ADRESS, contact.get_adresse());

    // updating row
    return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
            new String[] { String.valueOf(contact.get_id()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
            new String[] { String.valueOf(contact.get_id()) });
    db.close();
}
// Getting contacts Count
public int getContactsCount() {
    String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    int count = cursor.getCount();
    db.close();
    cursor.close();
    // return count
    return count;
}
}`

Aucun commentaire:

Enregistrer un commentaire