如何从片段中的java类调用方法?

时间:2016-12-22 20:14:49

标签: android android-fragments

嗨我对android的东西很新。首先,我无法从stackoverflow上的相关问题中找到答案。我有一个DbHelper类,如下所示

      public class DbHelper extends SQLiteOpenHelper {

        public static final String DB_NAME = "emergencydb";
        public static final int DB_VERSION = 2;

        public DbHelper(Context context) {
            super(context, DB_NAME, null, DB_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            //   db.execSQL(UserDb.getSql());
            db.execSQL(ContactDb.getSql());
            Log.v("DatabaseCr", "OLUSTU");
            //    db.execSQL(UserMessages.getSql());
        }

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

        @Override
        public void onOpen(SQLiteDatabase db) {
            // Foreign key desteğini açmak için
            super.onOpen(db);

        }



        public List<Contact> getAllContacts() {
        List<Contact> contacts = new ArrayList<Contact>();
            SQLiteDatabase db = this.getReadableDatabase();
            String getQuery = "SELECT * FROM " + ContactDb.TABLE_NAME;
            Cursor cursor = db.rawQuery(getQuery, null);
            Log.e("DbHelper", "while üstünde");
            while (cursor.moveToNext()) {
                //System.out.print("while içinde cursor");
                Log.e("DbHelper", "while içinde");
                Contact contact = new Contact();
                contact.setContactId(cursor.getInt(0));
                Log.v("ContactId", "" + cursor.getInt(0));
                contact.setContactName(cursor.getString(1));
                contact.setContactSurname(cursor.getString(2));
                contact.setPhone(cursor.getString(3));
                contact.setEmail(cursor.getString(4));
                contacts.add(contact);

                Collections.sort(contacts, new Comparator<Contact>() {
                    @Override
                    public int compare(Contact lhs, Contact rhs) {
                        return lhs.getContactName().compareTo(rhs.getContactName());
                    }
                });
            }
            return contacts;
        }
 public String insertContactToSQLite(Contact contact) {
        try {
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put(ContactDb.COL_CONTACTNAME, contact.getContactName());
            values.put(ContactDb.COL_CONTACTSURNAME, contact.getContactSurname());
            values.put(ContactDb.COL_CONTACTPHONE, contact.getPhone());
            values.put(ContactDb.COL_CONTACTEMAIL, contact.getEmail());

            db.insert(ContactDb.TABLE_NAME, null, values);
            db.close();
            Log.e("insertIcınde", "insert basarılı");
            return "İşlem başarılı";
        } catch (SQLiteAbortException e) {
            e.printStackTrace();
            return "İşlem Başarısız";
        }

    }

当我在activity中调用 getAllContacts 方法时没有错误。但是我必须在调用片段im获取空指针异常后在片段中调用此方法。我的片段类在

之下
public class AddContactFragment extends Fragment {

public Contact c1 = new Contact();
public Contact c2 = new Contact();
EditText etName, etSurname, etPhone, etEmail;
DbHelper dbHelper;
Button button;

public AddContactFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_add_contact,
            container, false);
    button = (Button) view.findViewById(R.id.add_button);
    etName = (EditText) view.findViewById(R.id.editTextName);
    etSurname = (EditText) view.findViewById(R.id.editTextSurname);
    etPhone = (EditText) view.findViewById(R.id.editTextPhone);
    etEmail = (EditText) view.findViewById(R.id.editTextEMail);
    // dbHelper =new DbHelper(this.getContext());
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            try {

                int a = dbHelper.getAllContacts().size();
                Log.e("ContactSize", "" + a);
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
            try {
                if (dbHelper.getAllContacts() == null || dbHelper.getAllContacts().size() <= 5) {
                    //    dbHelper.addContactToLocalDb(etName.getText().toString(),etSurname.getText().toString(),etPhone.getText().toString(),etEmail.getText().toString());


                     etName.getText().toString());
                    c1.setContactName(etName.getText().toString());
                    c1.setContactSurname(etSurname.getText().toString());
                    c1.setPhone(etPhone.getText().toString());
                    Log.e("kullanıcıId", "" + getUserServerId());
                    c1.setUserId(getUserServerId());

                    Log.e("AddContactFragment", "icinde");
                    c2.setContactName(etName.getText().toString());
                    c2.setContactSurname(etSurname.getText().toString());
                    c2.setPhone(etPhone.getText().toString());
                    c2.setEmail(etEmail.getText().toString());

                    dbHelper.insertContactToSQLite(c2);
                    try {
                        new MyClient().PostContact(c1);

                        Contact c = dbHelper.getAllContacts().get(0);
                        Log.e("isim", c.getContactName());
                        Log.e("AddContactFragmentPost", "postEdildi");
                        Intent newIntent = new Intent(getActivity().getApplicationContext(), NavigationActivity.class);
                        startActivity(newIntent);
                    } catch (JSONException e) {
                        Toast.makeText(getActivity().getApplicationContext(), "You can not add contact more than 5", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getActivity().getApplicationContext(), "You can not add contact more than 5", Toast.LENGTH_SHORT).show();
                }
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }
    });


    return view;
}

我将不胜感激任何帮助。

1 个答案:

答案 0 :(得分:2)

您的dbHelper实例为null,因为它尚未初始化。在您尝试使用它之前,请致电dbHelper = new DbHelper(getActivity())