简体   繁体   中英

How to get the registration id in android by using gcm?

Hi,

In my application I am using the gcm push notifications for sending notifications. I had implemented the following code in my project. For that, i created local database by using sq-lite in which i created one table.

But, now the problem is after running my application I wanted to get the registration id but registration id is not being stored. It shows as a null. Can anyone please help me?

DatabaseHandlers.java:

public class DatabaseHandlers extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;

    private static final String DATABASE_NAME = "FristRegistrationManager";

    private static final String TABLE_CONTACTS = "firstregistration";

    private static final String KEY_ID = "id";
    private static final String KEY_STUDENTNAME = "studentname";
    private static final String KEY_CLASSID = "classid";
    private static final String KEY_ROLL_NO = "rollno";
    private static final String KEY_PARENTNAME = "parentname";
    private static final String KEY_PH_NO = "phno";
    private static final String KEY_GCM_REGID = "gcm_regid";

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

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_STUDENTNAME + " TEXT,"
                + KEY_CLASSID + " TEXT," + KEY_ROLL_NO + " TEXT," + KEY_PARENTNAME + " TEXT,"+ KEY_PH_NO +" TEXT,"+ KEY_GCM_REGID +" TEXT)";
        db.execSQL(CREATE_CONTACTS_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

        onCreate(db);
    }

    void addGSfeedback(GSfeedback contact) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_STUDENTNAME, contact.getStudentname());
        values.put(KEY_CLASSID, contact.getClassid());
        values.put(KEY_ROLL_NO, contact.getRollno());
        values.put(KEY_PARENTNAME, contact.getParentname());
        values.put(KEY_PH_NO, contact.getPhnumber());   
        values.put(KEY_GCM_REGID, contact.getGcm_regid());  
        db.insert(TABLE_CONTACTS, null, values);
        db.close();
    }

    @SuppressWarnings("unused")
    private Context getApplicationContext() {

        return null;
    }


    GSfeedback getGSfeedback(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
                KEY_STUDENTNAME,KEY_CLASSID,KEY_ROLL_NO,KEY_PARENTNAME,KEY_PH_NO,KEY_GCM_REGID}, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        GSfeedback contact = new GSfeedback(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2),cursor.getString(3),cursor.getString(4),cursor.getString(5),cursor.getString(6));
        return contact;
    }

    public ArrayList<GSfeedback> getAllGSfeedbacks() {
        ArrayList<GSfeedback> contactList = new ArrayList<GSfeedback>();

        String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst()) {
            do {
                GSfeedback contact = new GSfeedback();
                contact.setID(Integer.parseInt(cursor.getString(0)));
                contact.setStudentname(cursor.getString(1));
                contact.setClassid(cursor.getString(2));
                contact.setRollno(cursor.getString(3)); 
                contact.setParentname(cursor.getString(4)); 
                contact.setPhnumber(cursor.getString(5));
                contact.setGcm_regid(cursor.getString(6));  
                contactList.add(contact);
            } while (cursor.moveToNext());
        }

        return contactList;
    }

    public int updateGSfeedback(GSfeedback contact) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_STUDENTNAME, contact.getStudentname());
        values.put(KEY_CLASSID, contact.getClassid());
        values.put(KEY_ROLL_NO, contact.getRollno());
        values.put(KEY_PARENTNAME, contact.getParentname());
        values.put(KEY_PH_NO, contact.getPhnumber());
        values.put(KEY_GCM_REGID, contact.getGcm_regid());  

        return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });
    }

    public void deleteGSfeedback(GSfeedback contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_CONTACTS, null, null);
        db.close();
    }

    public int getGSfeedbacksCount() {
        String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();
        return cursor.getCount();
    }   
}

PopupRegistration.java:

public class PopupRegistration extends Activity implements OnItemSelectedListener {
private String[] state = { "class", "1", "2", "3", "4", "5", "6", "7", "8",
        "9" };


public String log;
public DatabaseHandlers db;
List<String> list;

 EditText etName,etClass,etrollno,etparentname,etphno;

Button btnregister;

Spinner spinnerOsversions;

String PHONE_REGEX;

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

    db = new DatabaseHandlers(this);

    etName = (EditText) findViewById(R.id.etName);
    etClass = (EditText) findViewById(R.id.etClass);
    etrollno = (EditText) findViewById(R.id.etrollno);
    etparentname = (EditText) findViewById(R.id.etparentname);
    etphno = (EditText) findViewById(R.id.etphno);

    btnregister = (Button) findViewById(R.id.registerbutton);

    PHONE_REGEX = "[0-9]+";
    // spinner = (Spinner) findViewById(R.id.spinner);

    etClass.setVisibility(View.GONE);



    spinnerOsversions = (Spinner) findViewById(R.id.spinner);



    ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, state);

    adapter_state
            .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spinnerOsversions.setAdapter(adapter_state);
    spinnerOsversions.setOnItemSelectedListener(this);
    GCMRegistrar.checkDevice(this);

    // Make sure the manifest was properly set - comment out this line
    // while developing the app, then uncomment it when it's ready.
    GCMRegistrar.checkManifest(this);
    final String gcm_regid = GCMRegistrar.getRegistrationId(this);

    btnregister.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (validate()) {
                 String studentname = etName.getText().toString();
                    String classid = spinnerOsversions.getSelectedItem().toString();
                    String rollno = etrollno.getText().toString();
                    String parentname = etparentname.getText().toString();
                    String phno = etphno.getText().toString();

                // Save the Data in Database
                db.addGSfeedback(new GSfeedback(studentname,classid,rollno,parentname,phno,gcm_regid));
                Toast.makeText(
                        getApplicationContext(),
                        "Thanks for Registration, Welcome to Lilttle Flowers Public School Android App.",
                        Toast.LENGTH_LONG).show();
                etName.setText("");
                etClass.setText("");
                etrollno.setText("");
                etparentname.setText("");
                etphno.setText("");

                finish();

                Intent nextScreen = new Intent(getApplicationContext(), Splashscreen.class);
                startActivity(nextScreen);
            }
        }

    });

}

public void onItemSelected(AdapterView<?> parent, View view, int position,
        long id) {

    switch (view.getId()) {
    case R.id.spinner:
        spinnerOsversions.setSelection(position);
        String selState = (String) spinnerOsversions.getSelectedItem();
        etClass.setText("" + selState);
        break;

    default:
        break;
    }

}

private boolean validate() {
    String studentname = etName.getText().toString();
    String classid = spinnerOsversions.getSelectedItem().toString();
    String rollno = etrollno.getText().toString();
    String parentname = etparentname.getText().toString();
    String phno = etphno.getText().toString();

    if (TextUtils.isEmpty(studentname) || TextUtils.isEmpty(classid)
            || TextUtils.isEmpty(rollno) || TextUtils.isEmpty(parentname)
            || TextUtils.isEmpty(phno)) {
        Toast.makeText(getApplicationContext(),
                "pls fill the empty fields", Toast.LENGTH_SHORT).show();
        return false;
    } else if (etName.getText().toString().length() > 30
            && etparentname.getText().toString().length() > 30) {
        etName.setError("pls enter less the 30 charachter");
        return true;

    } else if (etphno.getText().toString().length() < 6
            || etphno.getText().toString().length() > 13) {
        Toast.makeText(getApplicationContext(), "Enter valid Phone Number",
                Toast.LENGTH_SHORT).show();
        return false;
    } else {
        if (etphno.getText().toString().trim().matches(PHONE_REGEX)) {
            return true;
        } else {
            Toast.makeText(getApplicationContext(),
                    "Enter Valid Phone Number", Toast.LENGTH_SHORT).show();
            return false;
        }
    }
}


@Override
public void onNothingSelected(AdapterView<?> arg0) {

}
}

GCMRegistrar.getRegistrationId(this) will return the registration ID only if you previously called GCMRegistrar.register and your broadcast receiver received the Registration ID in the async response and stored it in shared preferences. I don't see anywhere in your code where you actually register, so of course it will be null.

That said, it will be better not to use GCMRegistrar at all (it's deprecated) and instead use GoogleCloudMessaging.register . That's a blocking method, so you don't have to handle the response in a separate place.

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