简体   繁体   中英

getting error while reading contact details and saving to sql database android

I want to save contact phone number and name to sql database. I was able to save database using editext but when i pass my contacts details to database app force closed. I also added permission to read contact and my database is also working fine as when i use edittext to pass information it works fine. Please help...here is my code.

PS I have added permissions so don't worry about that.

public class RegistrationActivity extends Activity {
    RegistrationAdapter adapter;
    RegistrationOpenHelper helper;
    EditText fnameEdit, lnameEdit;
    Button submitBtn, resetBtn;
    private static final int PICK_CONTACT = 0;
    Button button;
    TextView name,num;
    int number;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        fnameEdit = (EditText) findViewById(R.id.et_fname);
        lnameEdit = (EditText) findViewById(R.id.et_lname);
        submitBtn = (Button) findViewById(R.id.btn_submit);
        //resetBtn = (Button) findViewById(R.id.btn_reset);
        adapter = new RegistrationAdapter(this);

        submitBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(intent, PICK_CONTACT);
                // String fnameValue = fnameEdit.getText().toString();
                //String lnameValue = lnameEdit.getText().toString();
                //long val = adapter.insertDetails(fnameValue, lnameValue);
                //finish();
            }

        });}

        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            switch (requestCode) {
                case PICK_CONTACT:
                    if (resultCode == Activity.RESULT_OK) {
                        Uri contactData = data.getData();
                        Cursor c = managedQuery(contactData, null, null, null, null);
                        if (c.moveToFirst()) {
                            String fnameValue = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));

                            String hasPhone =
                                    c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

                            if (hasPhone.equalsIgnoreCase("1")) {
                                Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + fnameValue, null, null);
                                phones.moveToFirst();
                                String cNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                                // Toast.makeText(getApplicationContext(), cNumber, Toast.LENGTH_SHORT).show();
                                num.setText(cNumber);
                                String number=num.getText().toString();
                                long val = adapter.insertDetails(fnameValue, number);
                            }
                        }
                    }
            }
        }
}

        /*resetBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                fnameEdit.setText("");
                lnameEdit.setText("");
            }
        });*/

public class RegistrationAdapter {
        SQLiteDatabase database_ob;
        RegistrationOpenHelper openHelper_ob;
        Context context;

        public RegistrationAdapter(Context c) {
            context = c;
        }

        public RegistrationAdapter opnToRead() {
            openHelper_ob = new RegistrationOpenHelper(context,
                    openHelper_ob.DATABASE_NAME, null, openHelper_ob.VERSION);
            database_ob = openHelper_ob.getReadableDatabase();
            return this;

        }

        public RegistrationAdapter opnToWrite() {
            openHelper_ob = new RegistrationOpenHelper(context,
                    openHelper_ob.DATABASE_NAME, null, openHelper_ob.VERSION);
            database_ob = openHelper_ob.getWritableDatabase();
            return this;

        }

        public void Close() {
            database_ob.close();
        }

        public long insertDetails(String fname, String lname) {
            ContentValues contentValues = new ContentValues();
            contentValues.put(openHelper_ob.FNAME, fname);
            contentValues.put(openHelper_ob.LNAME, lname);
            opnToWrite();
            long val = database_ob.insert(openHelper_ob.TABLE_NAME, null,
                    contentValues);
            Close();
            return val;

        }

        public Cursor queryName() {
            String[] cols = { openHelper_ob.KEY_ID, openHelper_ob.FNAME,
                    openHelper_ob.LNAME };
            opnToWrite();
            Cursor c = database_ob.query(openHelper_ob.TABLE_NAME, cols, null,
                    null, null, null, null);

            return c;

        }

        public Cursor queryAll(int nameId) {
            String[] cols = { openHelper_ob.KEY_ID, openHelper_ob.FNAME,
                    openHelper_ob.LNAME };
            opnToWrite();
            Cursor c = database_ob.query(openHelper_ob.TABLE_NAME, cols,
                    openHelper_ob.KEY_ID + "=" + nameId, null, null, null, null);

            return c;

        }

        public long updateldetail(int rowId, String fname, String lname) {
            ContentValues contentValues = new ContentValues();
            contentValues.put(openHelper_ob.FNAME, fname);
            contentValues.put(openHelper_ob.LNAME, lname);
            opnToWrite();
            long val = database_ob.update(openHelper_ob.TABLE_NAME, contentValues,
                    openHelper_ob.KEY_ID + "=" + rowId, null);
            Close();
            return val;
        }

        public int deletOneRecord(int rowId) {
            // TODO Auto-generated method stub
            opnToWrite();
            int val = database_ob.delete(openHelper_ob.TABLE_NAME,
                    openHelper_ob.KEY_ID + "=" + rowId, null);
            Close();
            return val;
        }

    }

--------------------------------------------------------------thats log file---------

05-10 17:05:26.125    3937-3937/braindevs.other E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: braindevs.other, PID: 3937
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { dat=content://com.android.contacts/contacts/lookup/0r1-3333332F2F3737373733/1 flg=0x1 }} to activity {braindevs.other/braindevs.other.RegistrationActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
            at android.app.ActivityThread.deliverResults(ActivityThread.java:3539)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3582)
            at android.app.ActivityThread.access$1300(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1327)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
            at braindevs.other.RegistrationActivity.onActivityResult(RegistrationActivity.java:71)
            at android.app.Activity.dispatchActivityResult(Activity.java:6139)
            at android.app.ActivityThread.deliverResults(ActivityThread.java:3535)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3582)
            at android.app.ActivityThread.access$1300(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1327)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

The problem is caused by an NPE ( NullPointerException ) when attempting to set the text of a null text view. From your code this may be name or num . I suggest you to add this to your onCreate:

name = (TextView) findViewById(R.id.yourNameTextView);
num = (TextView) findViewById(R.id.yourNumberTextView);

It was silly mistake but i figure it out and thanks for matei trandafir for helping. i was using num to get contact phone number but it was a textview i used to display but when i pass number to database i forgot to remove it sorry here is the corrected code part.Hope it helps

if (hasPhone.equalsIgnoreCase("1")) {
                                Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + fnameValue, null, null);
                                phones.moveToFirst();
                                String cNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                                // Toast.makeText(getApplicationContext(), cNumber, Toast.LENGTH_SHORT).show();
                                //num.setText(cNumber);
                                //number=num.getText().toString();
                                long val = adapter.insertDetails(fnameValue, cNumber);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM