我試圖從MainActivity中設置一個值,並將其設置爲FirebaseInstance類。在Android Studio中獲取和設置Firebase實例的值
,但我得到這個錯誤,
Process: com.administrator.mosbeau, PID: 17713
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.administrator.mosbeau/com.example.administrator.mosbeau.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.administrator.mosbeau.FirebaseSetGet.setCountryid(java.lang.String)' on a null object reference
這裏就是我所做的。
我創建了一個FirebaseSetGet類
public class FirebaseSetGet extends Application {
private String countryid;
private String customerid;
public String getCountryid() {
return countryid;
}
public void setCountryid(String acountryid) {
countryid = acountryid;
}
public String getCustomerid() {
return customerid;
}
public void setCustomerid(String acustomerid) {
customerid = acustomerid;
}
}
那我就在我的MainActivity中添加此代碼。
private void displayUserDetails() {
User user = userLocalStore.getLoggedInUser();
customersid = user.customers_id;
countrycode = user.customers_countryid;
stateid = user.customers_stateid;
if (customersid == "") {
Intent myIntent = new Intent(MainActivity.this, IndexActivity.class);
startActivity(myIntent);
}
if (checkPlayServices()) {
idsvar.setCountryid(countrycode);
idsvar.setCustomerid(customersid);
FirebaseMessaging.getInstance().subscribeToTopic("test");
FirebaseInstanceId.getInstance().getToken();
} else {
Log.i(TAG, "No valid Google Play Services APK found.");
}
if (productId != null){
if (productFragment != null) {
if (productFragment.equals("productItem")) {
ProductFragment productfragment = ProductFragment.newInstance(productId, productName, countrycode, customersid, categoryName, stateid, categoryId);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, productfragment)
.addToBackStack(null)
.commit();
}
}
}
}
然後讓我的FirebaseInstance
public class FirebaseInstanceIDService extends FirebaseInstanceIdService {
FirebaseSetGet idsvar = new FirebaseSetGet();
@Override
public void onTokenRefresh() {
String token = FirebaseInstanceId.getInstance().getToken();
final String country_id = idsvar.getCountryid();
final String customer_id = idsvar.getCustomerid();
registerToken(token,country_id,customer_id);
}
private void registerToken(String token, String country_id, String customer_id) {
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("Token",token)
.add("Countryid",country_id)
.add("Customerid",customer_id)
.build();
Request request = new Request.Builder()
.url("http://shop.mosbeau.com.ph/FCM/register.php")
.post(body)
.build();
try {
client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}
,但它給我的錯誤。
嗨Chintan,謝謝你的幫助..對不起,即時通訊新的android ..你能幫助莫構建我的代碼?我更新我的代碼..謝謝..我試過你的代碼,但即時獲取SharedPreferenceUtils錯誤。 – Joehamir
@Joehamir更新回答。請檢查。 –
無法解析符號firebase_cloud_messaging_token – Joehamir