数据库保存所有细节而不是图像

时间:2017-08-15 11:05:12

标签: android database image

我正在编写一个简单的应用程序来保存列表中的联系人。 我的数据库工作正常,但是当我重新启动应用程序或更新联系人的详细信息时(即使我没有更新图像),所有图像都不会再次显示。

我一路上错过了什么? 提前谢谢!

MainActivity.class

package org.intracode.contactmanager;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import java.net.URI;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    //live apearences in screen objects
    EditText nameLine, PhoneLine, EmailLine, AddressLine;
    Button addBtn;
    TabHost myTab;
    List<Contact> myContactList = new ArrayList<>();
    ListView myListView;
    ImageView contactImage;
    Uri imageURI = Uri.parse("android.resource://org.intracode.contactmanager/drawable/no_logo.png");// including assigning
    DatabaseHandler contacsDB;
    ArrayAdapter<Contact> myContactsAdapter;
    int longcClickElemnt;//clicked item position
    private  static final int EDIT=0,DELETE=1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        //assigning line fields
        nameLine = (EditText) findViewById(R.id.nameLine);
        PhoneLine = (EditText) findViewById(R.id.PhoneLine);
        EmailLine = (EditText) findViewById(R.id.EmailLine);
        AddressLine = (EditText) findViewById(R.id.AdressLine);
        addBtn = (Button) findViewById(R.id.saveButton);

        //assigning tab objects
        myTab = (TabHost) findViewById(R.id.tabHost); //assigning general tab
        myTab.setup();
        //assigning first sub tub
        TabHost.TabSpec tabspec = myTab.newTabSpec("creator");
        tabspec.setContent(R.id.creatorTab);
        tabspec.setIndicator("Creator");//name of sub tab
        myTab.addTab(tabspec);// connecting the sub tab to the general tab
        // assigning second sub tub
        tabspec = myTab.newTabSpec("list");
        tabspec.setContent(R.id.tabContactList);
        tabspec.setIndicator("List");//name of sub tab
        myTab.addTab(tabspec);// connecting the sub tab to the general tab
        //assigning the listview object
        myListView = (ListView) findViewById(R.id.listview);
        // assigning ImageView object
        contactImage = (ImageView) findViewById(R.id.contactImage);
        //assignig dataBase
        contacsDB = new DatabaseHandler(getApplicationContext());
        //register a menu for the list object
        registerForContextMenu(myListView);
        myListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                longcClickElemnt=i;
                contactImage.setVisibility(View.VISIBLE);

                return false;
            }
        });

        // name event
        nameLine.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {


            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String email = charSequence.toString().trim();
                addBtn.setEnabled(String.valueOf(nameLine.getText()).trim().length() > 0 && isValidEmaillId(email));
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        // email event
        EmailLine.addTextChangedListener(new TextWatcher() {
            String emailString = EmailLine.getText().toString().trim();

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String email = charSequence.toString().trim();
                addBtn.setEnabled(nameLine.getText().toString().trim().length() > 0 && isValidEmaillId(email));
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        //buttonEvent
        addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Contact newCont = new Contact(contacsDB.getContactsCount(), nameLine.getText().toString(), PhoneLine.getText().toString(), EmailLine.getText().toString(), AddressLine.getText().toString(), imageURI);
                if (!contactExist(newCont)) {
                    contacsDB.createContact(newCont);
                    myContactList.add(newCont);
                    myContactsAdapter.notifyDataSetChanged();// let  the adapter know something is changing in our list
                    Toast.makeText(getApplicationContext(), "You added " + nameLine.getText().toString() + " to your contact list", Toast.LENGTH_SHORT).show();
                    return;
                }
                Toast.makeText(getApplicationContext(), nameLine.getText().toString() + " is already exist in your list", Toast.LENGTH_SHORT).show();
                nameLine.setText("");
                PhoneLine.setText("");
                EmailLine.setText("");
                AddressLine.setText("");
                contactImage.setImageResource(R.drawable.no_logo);


            }

        });

        //contactImageEvent
        contactImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {// defining a chooser
                Intent intent = new Intent();// intent is an object that passes a messeges in our system
                intent.setType("image/*");// Set an explicit MIME data type.
                intent.setAction(intent.ACTION_GET_CONTENT);//Allow the user to select a particular kind of data and return it.
                startActivityForResult(Intent.createChooser(intent, "Select Contact Image"), 1);
            }
        });

        //populate the list such that our list view will show all the contact that in pur database
        // synchronized with our database
        if (contacsDB.getContactsCount() > 0)
            myContactList.addAll(contacsDB.getAllContacts());
        populateList();// write the contact that we added now into the list's screen
    }


    //special method for the moment that we create the menu with its fields
    public void onCreateContextMenu(ContextMenu myMenu, View myView,ContextMenu.ContextMenuInfo menuInfo){
        super.onCreateContextMenu(myMenu,myView,menuInfo);
        myMenu.setHeaderIcon(R.drawable.edit_icon);
        myMenu.setHeaderTitle("Contact options");
        myMenu.add(Menu.NONE,EDIT,myMenu.NONE,"Edit contact");
        myMenu.add(Menu.NONE,DELETE,myMenu.NONE,"Delete contact");

    }

    public  boolean onContextItemSelected(MenuItem myItem){
        switch(myItem.getItemId()){
            case EDIT:
                Intent moveToEdit= new Intent(this,EditContactActivity.class);
                String[] argToPass={String.valueOf(myContactList.get(longcClickElemnt).getId()),myContactList.get(longcClickElemnt).getName(),
                        myContactList.get(longcClickElemnt).getPhone(), myContactList.get(longcClickElemnt).getEmail(),
                        myContactList.get(longcClickElemnt).getAddress(),String.valueOf(myContactList.get(longcClickElemnt).getImageURI())};
                moveToEdit.putExtra("args",argToPass);
                startActivityForResult(moveToEdit,2);
                break;
            case DELETE:
                //longcClickElemnt represents the position of item that we clicked on in our listview
                // , initilized every setOnItemLongClickListener
                contacsDB.deleteContact(myContactList.get(longcClickElemnt));//remove from database
                myContactList.remove(longcClickElemnt);// remove from list
                myContactsAdapter.notifyDataSetChanged();// update database instantly
                break;
        }
        return super.onContextItemSelected(myItem);
    }
    //Handling the result of clicking the contact image(Created to reply startActivityForResult function )
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 1:// comeback from image collecting screen
                    imageURI = data.getData();
                    contactImage.setImageURI(data.getData());//Sets the content of this ImageView to the specified Uri.
                    break;
                case 2://comeback from edit contact screen
                    String[] contactDetails=data.getStringArrayExtra("result");
                    contacsDB.updateContact(new Contact(Integer.parseInt(contactDetails[0]), contactDetails[1], contactDetails[2],
                            contactDetails[3],contactDetails[4], Uri.parse(contactDetails[5])));//update datatbase operation
                    myContactList.get(longcClickElemnt).setAll(contactDetails[1], contactDetails[2],
                            contactDetails[3],contactDetails[4], Uri.parse(contactDetails[5]));
                    myContactsAdapter.notifyDataSetChanged();// update database instantly
                    Toast.makeText(getApplicationContext(),"Changes saved!",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }
    // special adapter that helps display data in a UI element, extending the array adapter class
    private class ContactListAdapter extends ArrayAdapter<Contact> {

        public ContactListAdapter() {
            super(MainActivity.this, R.layout.contact_layout, myContactList);
        }

        @Override
        public View getView(int position, View myView, ViewGroup parent) {//adding a contact in a certain position to our contactList screen
            if (myView == null)
                myView = getLayoutInflater().inflate(R.layout.contact_layout, parent, false);
            Contact currContact = myContactList.get(position);

            TextView name = myView.findViewById(R.id.contact_name_store);
            name.setText(currContact.getName());

            TextView phone = myView.findViewById(R.id.phone_store);
            phone.setText(currContact.getPhone());

            TextView email = myView.findViewById(R.id.email_store);
            email.setText(currContact.getEmail());

            TextView address = myView.findViewById(R.id.address_store);
            address.setText(currContact.getAddress());

            ImageView contactImage = myView.findViewById(R.id.imageViewOnLayput);
            contactImage.setImageURI(currContact.getImageURI());

            return myView;
        }
    }

    // write inside myListView with the help of the adapter
    private void populateList() {
        myContactsAdapter = new ContactListAdapter();
        myListView.setAdapter(myContactsAdapter);
    }

    //check if one's email address is valid
    public static boolean isValidEmaillId(String email) {
        return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }

    private boolean contactExist(Contact c) {
        String c_name = c.getName();
        int count = myContactList.size();

        for (int i = 0; i < count; i++) {
            if (myContactList.get(i).getName().compareToIgnoreCase(c_name) == 0)
                return true;
        }
        return false;
    }
}

DatabaseHandler.class

package org.intracode.contactmanager;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Johnny Manson on 19.01.14.
 */
public class DatabaseHandler extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;

    private static final String DATABASE_NAME = "contactManager",
            TABLE_CONTACTS = "contacts",
            KEY_ID = "id",
            KEY_NAME = "name",
            KEY_PHONE = "phone",
            KEY_EMAIL = "email",
            KEY_ADDRESS = "address",
            KEY_IMAGEURI = "imageUri";

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

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + TABLE_CONTACTS + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT," + KEY_PHONE + " TEXT," + KEY_EMAIL + " TEXT," + KEY_ADDRESS + " TEXT," + KEY_IMAGEURI + " TEXT)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

        onCreate(db);
    }

    public void createContact(Contact contact) {
        SQLiteDatabase db = getWritableDatabase();

        ContentValues values = new ContentValues();

        values.put(KEY_NAME, contact.getName());
        values.put(KEY_PHONE, contact.getPhone());
        values.put(KEY_EMAIL, contact.getEmail());
        values.put(KEY_ADDRESS, contact.getAddress());
        values.put(KEY_IMAGEURI, String.valueOf(contact.getImageURI()));
        db.insert(TABLE_CONTACTS, null, values);
        db.close();
    }

    public Contact getContact(int id) {
        SQLiteDatabase db = getReadableDatabase();

        Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID, KEY_NAME, KEY_PHONE, KEY_EMAIL, KEY_ADDRESS, KEY_IMAGEURI }, 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), Uri.parse(cursor.getString(5)));
        db.close();
        cursor.close();
        return contact;
    }

    public void deleteContact(Contact contact) {
        SQLiteDatabase db = getWritableDatabase();
        db.delete(TABLE_CONTACTS, KEY_ID + "=?", new String[] { String.valueOf(contact.getId()) });
        db.close();
    }

    public int getContactsCount() {
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_CONTACTS, null);
        int count = cursor.getCount();
        db.close();
        cursor.close();

        return count;
    }

    public int updateContact(Contact contact) {
        SQLiteDatabase db = getWritableDatabase();

        ContentValues values = new ContentValues();

        values.put(KEY_NAME, contact.getName());
        values.put(KEY_PHONE, contact.getPhone());
        values.put(KEY_EMAIL, contact.getEmail());
        values.put(KEY_ADDRESS, contact.getAddress());
        values.put(KEY_IMAGEURI, contact.getImageURI().toString());

        int rowsAffected = db.update(TABLE_CONTACTS, values, KEY_ID + "=?", new String[] { String.valueOf(contact.getId()) });
        db.close();

        return rowsAffected;
    }

    public List<Contact> getAllContacts() {
        List<Contact> contacts = new ArrayList<Contact>();

        SQLiteDatabase db = getWritableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_CONTACTS, null);

        if (cursor.moveToFirst()) {
            do {
                contacts.add(new Contact(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), Uri.parse(cursor.getString(5))));
            }
            while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return contacts;
    }
}

EditActivity.class

package org.intracode.contactmanager;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class EditContactActivity extends AppCompatActivity {
    //live appearances in screen objects
    EditText editName, editPhone, editEmail, editAddress;
    Button editButton;
    ImageView editImage;
    Uri imageURI = Uri.parse("android.resource://org.intracode.contactmanager/drawable/no_logo.png");// including assigning

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_contact);

        //assigning fields
        editName = (EditText) findViewById(R.id.editName);
        editPhone = (EditText) findViewById(R.id.editPhone);
        editEmail = (EditText) findViewById(R.id.editEmail);
        editAddress = (EditText) findViewById(R.id.editAddress);
        editButton = (Button) findViewById(R.id.editButton);
        editImage = (ImageView) findViewById(R.id.editImage);
        // getting passed arguments
        String[] passedArg = getIntent().getStringArrayExtra("args");
        editName.setText(passedArg[1]);
        editPhone.setText(passedArg[2]);
        editEmail.setText(passedArg[3]);
        editAddress.setText(passedArg[4]);
        editImage.setImageURI(Uri.parse(passedArg[5]));
        //events

        editName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {


            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String email = charSequence.toString().trim();
                editButton.setEnabled(String.valueOf(editName.getText()).trim().length() > 0 && MainActivity.isValidEmaillId(email));
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        // email event
        editEmail.addTextChangedListener(new TextWatcher() {
            String emailString = editEmail.getText().toString().trim();

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String email = charSequence.toString().trim();
                editButton.setEnabled(editName.getText().toString().trim().length() > 0 && MainActivity.isValidEmaillId(email));
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        //buttonEvent
        editButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent returnIntent = new Intent();
                String[] passedArg = getIntent().getStringArrayExtra("args");
                String[] argToReturn = {passedArg[0], String.valueOf(editName.getText()), String.valueOf(editPhone.getText()), String.valueOf(editEmail.getText()),
                        String.valueOf(editAddress.getText()), String.valueOf(editImage)};
                returnIntent.putExtra("result", argToReturn);
                setResult(Activity.RESULT_OK, returnIntent);
                finish();
            }
        });
        editImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {// defining a chooser
                Intent intent = new Intent();// intent is an object that passes a messeges in our system
                intent.setType("image/*");// Set an explicit MIME data type.
                intent.setAction(intent.ACTION_GET_CONTENT);//Allow the user to select a particular kind of data and return it.
                startActivityForResult(Intent.createChooser(intent, "Select Contact Image"), 1);

            }
        });


    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 1:// comeback from image collecting screen
                    imageURI = data.getData();
                    editImage.setImageURI(data.getData());//Sets the content of this ImageView to the specified Uri.


            }
        }
    }
}

联系班级

package org.intracode.contactmanager;

import android.net.Uri;

import java.net.URI;

/**
 * Created by Roey on 09/08/2017.
 */

public class Contact {
    private String name ,email, phone, address;
    private Uri imageURI;
    private int id;// added for database manners


    public Contact(int id,String name ,String phone,String email,String address,Uri imageURI){
        this.id=id;
        this.name=name;
        this.email=email;
        this.phone=phone;
        this.address=address;
        this.imageURI=imageURI;
    }

    //getters
    public String getName(){
        return name;
    }
    public String getEmail(){
        return email;
    }
    public String getPhone(){
        return phone;
    }
    public String getAddress(){
        return address;
    }
    public Uri getImageURI(){
        return imageURI;
    }
    public int getId(){
        return id;
    }
    //setters
    public void setAll(String name,String phone,String email,String address,Uri imageURI){
        this.name=name;
        this.email=email;
        this.phone=phone;
        this.address=address;
        this.imageURI=imageURI;
    }



}

0 个答案:

没有答案