未能将java.lang.String类型的值转换为int

我想我已经在Firebase或Android Studio中发现了一个错误。
我添加的代码(FIG1)至ChatActivity.java,我得到一个错误:未能将java.lang.String类型的值转换为int

(com.google.firebase.database.DatabaseException: Failed to convert a value of type java.lang.String to int)

但是,当我删除代码(FIG1),我仍然在包含每个脚本(fig2)接收消息。
为什么在删除它之后将它引用到整数而不是字符串?

FIG1(代码)

private FirebaseDatabase database; 

private DatabaseReference myConnectionsRef;

...

protected void onCreate(Bundle savedInstanceState) {...` database = FirebaseDatabase.getInstance();

myConnectionsRef = database.getReference("users/" + FirebaseAuth.getInstance().getCurrentUser().getUid() + "/n_newmessages_c");` fab.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view) {

if (input.getText().toString().trim().equals("")) {

Toast.makeText(ChatActivity.this, "Please enter some texts!", Toast.LENGTH_SHORT).show();

} else {.... myConnectionsRef.addListenerForSingleValueEvent(new ValueEventListener() {

@Override

public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {

try{

notifMcount = (long) dataSnapshot.getValue();

Log.e(TAG, "onDataChange: NOTIFICATION COUNT MESSAGES--------------------- = " + notifMcount);

long newNotifAmount = notifMcount + 1;

myRef.child(getString(R.string.dbname_users))

.child(mUser.getUser_id())

.child("n_newmessages_c")

.setValue(newNotifAmount);

}catch (NullPointerException e){

Log.e(TAG, "onDataChange: NullPointerException" + e.getMessage());

}

}

@Override

public void onCancelled(DatabaseError databaseError) {

}

});

fig2(代码)(从MessengerFriendsOnline.java)

private void updateUserslist(){ 

Log.d(TAG, "updateUsersList: updating users list");

mAdapter = new MessagesListAdapter(getActivity(), R.layout.layout_friend_listitem, mUserList);

mListView.setAdapter(mAdapter);

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

@Override

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

Log.d(TAG, "onItemClick: selected user: " + mUserList.get(position).toString());

//navigate to profile activity

Intent intent = new Intent(getActivity(), ChatActivity.class);

intent.putExtra(getString(R.string.intent_user), mUserList.get(position));

startActivity(intent);

}

});

}

private void updateFriendsList(){

Log.d(TAG, "getPhotos: getting Friend(s)");

DatabaseReference reference = FirebaseDatabase.getInstance().getReference();

for(int i = 0; i < mFriends.size(); i++){

final int count = i;

Query query = reference

.child(getString(R.string.dbname_users))

.orderByChild(getString(R.string.field_user_id))

.equalTo(mFriends.get(i));

query.addListenerForSingleValueEvent(new ValueEventListener() {

@Override

public void onDataChange(DataSnapshot dataSnapshot) {

for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){

//boolean is_Online = singleSnapshot.getValue(User.class).isOnline();

// Log.w(TAG, "onDataChange: FRIEND IS ONLINE ********************** = " + is_Online);

//if(is_Online == true) {

mUserList.add(singleSnapshot.getValue(User.class));

//}

}

if(count >= mFriends.size() - 1){

updateUserslist();

}

}

@Override

public void onCancelled(DatabaseError databaseError) {

}

});

}

}

private void getFriends(){

Log.d(TAG, "getFollowing: searching for FRIENDS **************************************");

mFriends.clear();

mUserList.clear();

DatabaseReference reference = FirebaseDatabase.getInstance().getReference();

Query query = reference

.child(getString(R.string.dbname_friends))

.child(FirebaseAuth.getInstance().getCurrentUser().getUid());

query.addListenerForSingleValueEvent(new ValueEventListener() {

@Override

public void onDataChange(DataSnapshot dataSnapshot) {

for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {

Log.d(TAG, "onDataChange: found friend----------------**: " + singleSnapshot.getValue(User.class).toString());

mFriends.add(singleSnapshot.child(getString(R.string.field_user_id)).getValue().toString());

Log.d(TAG, "onDataChange: Freinds user id: " + mFriends.toString() );

}

//get the photos

updateFriendsList();

}

@Override

public void onCancelled(DatabaseError databaseError) {

}

});

}

ChatActivity.java

public class ChatActivity extends AppCompatActivity { 

private static final String TAG = "ChatActivity";

private static final int SIGN_IN_REQUEST_CODE = 111;

private FirebaseListAdapter<ChatMessage> adapter;

private ListView listView;

private String loggedInUserName = "";

private int messagesCount = 0;

private DatabaseReference myRef;

private long notifMcount;

Map data;

private FirebaseDatabase database;

private DatabaseReference myConnectionsRef;

private User mUser;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_chat);

myRef = FirebaseDatabase.getInstance().getReference();

//find views by Ids

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

final EditText input = (EditText) findViewById(R.id.input);

listView = (ListView) findViewById(R.id.list);

data = new HashMap();

try {

mUser = getUserFromBundle();

//init();

}catch (NullPointerException e){

Log.e(TAG, "NullPointerException: " + e.getMessage());

Toast.makeText(this, "Something went wrong", Toast.LENGTH_SHORT).show();

getSupportFragmentManager().popBackStack();

}

if (FirebaseAuth.getInstance().getCurrentUser() == null) {

// Start sign in/sign up activity

startActivityForResult(AuthUI.getInstance()

.createSignInIntentBuilder()

.build(), SIGN_IN_REQUEST_CODE);

} else {

// User is already signed in, show list of messages

showAllOldMessages();

}

database = FirebaseDatabase.getInstance();

myConnectionsRef = database.getReference("users/" + FirebaseAuth.getInstance().getCurrentUser().getUid() + "/n_newmessages_c");

Log.d(TAG, "onCreate: USER SELECT TO CHAT WITH********************** " + mUser.getUser_id());

fab.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view) {

if (input.getText().toString().trim().equals("")) {

Toast.makeText(ChatActivity.this, "Please enter some texts!", Toast.LENGTH_SHORT).show();

} else {

Log.d(TAG, "onDataChange: Messages -- BEFORE 2 *******************************" + messagesCount);

myRef.child(getString(R.string.dbname_messages))

.child(FirebaseAuth.getInstance().getCurrentUser().getUid())

.child(mUser.getUser_id())

.child("Chat")

.push()

.setValue(new ChatMessage(input.getText().toString(),

FirebaseAuth.getInstance().getCurrentUser().getEmail(),

FirebaseAuth.getInstance().getCurrentUser().getUid())

);

Log.d(TAG, "onDataChange: Messages AFTER 1 --- *******************************" + messagesCount);

myRef.child(getString(R.string.dbname_messages))

.child(mUser.getUser_id())

.child(FirebaseAuth.getInstance().getCurrentUser().getUid())

.child("Chat")

.push()

.setValue(new ChatMessage(input.getText().toString(),

FirebaseAuth.getInstance().getCurrentUser().getEmail(),

FirebaseAuth.getInstance().getCurrentUser().getUid())

);

myRef.child(getString(R.string.dbname_messages))

.child(mUser.getUser_id())

.child(FirebaseAuth.getInstance().getCurrentUser().getUid())

.child("ChatSettings")

.child("new_message_n")

.setValue(true);

myConnectionsRef.addListenerForSingleValueEvent(new ValueEventListener() {

@Override

public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {

try{

notifMcount = (long) dataSnapshot.getValue();

Log.e(TAG, "onDataChange: NOTIFICATION COUNT MESSAGES--------------------- = " + notifMcount);

long newNotifAmount = notifMcount + 1;

myRef.child(getString(R.string.dbname_users))

.child(mUser.getUser_id())

.child("n_newmessages_c")

.setValue(newNotifAmount);

}catch (NullPointerException e){

Log.e(TAG, "onDataChange: NullPointerException" + e.getMessage());

}

}

@Override

public void onCancelled(DatabaseError databaseError) {

}

});

long newNotifAmount = notifMcount + 1;

myRef.child(getString(R.string.dbname_users))

.child(mUser.getUser_id())

.child("n_newmessages_c")

.setValue(newNotifAmount);

Log.d(TAG, "onDataChange: Messages AFTER 2 --- *******************************" + messagesCount);

}

}

});

}

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data)

{

super.onActivityResult(requestCode, resultCode, data);

if (requestCode == SIGN_IN_REQUEST_CODE) {

if (resultCode == RESULT_OK) {

Toast.makeText(this, "Signed in successful!", Toast.LENGTH_LONG).show();

showAllOldMessages();

} else {

Toast.makeText(this, "Sign in failed, please try again later", Toast.LENGTH_LONG).show();

finish();

}

}

}

private void showAllOldMessages() {

loggedInUserName = FirebaseAuth.getInstance().getCurrentUser().getUid();

Log.d("Main", "user id: " + loggedInUserName);

adapter = new MessageAdapter(this, ChatMessage.class, R.layout.item_in_message,

FirebaseDatabase.getInstance().getReference().child(getString(R.string.dbname_messages))

.child(FirebaseAuth.getInstance().getCurrentUser().getUid())

.child(mUser.getUser_id())

.child("Chat"));

listView.setAdapter(adapter);

}

private User getUserFromBundle(){

Bundle bundle = getIntent().getExtras();

if(bundle != null){

return bundle.getParcelable(getString(R.string.intent_user));

}else{

return null;

}

}

@Override

public void onStart() {

super.onStart();

myRef.child(getString(R.string.dbname_messages))

.child(FirebaseAuth.getInstance().getCurrentUser().getUid())

.child(mUser.getUser_id())

.child("ChatSettings")

.child("new_message_n")

.setValue(false);

}

@Override

public void onStop() {

super.onStop();

myRef.child(getString(R.string.dbname_messages))

.child(FirebaseAuth.getInstance().getCurrentUser().getUid())

.child(mUser.getUser_id())

.child("ChatSettings")

.child("new_message_n")

.setValue(false);

}

错误消息:

12-02 18:04:39.200 19657-19657/com.example.user.someapp E/MessengerMessagesFragme: getFollowing: searching for FRIENDS ************************************** 

12-02 18:04:40.106 3829-530/? E/ctxmgr: [AppIntervalImpl]closeInterval: ongoing

12-02 18:04:41.046 1472-1561/? E/TaskPersister: File error accessing recents directory (directory doesn't exist?).

12-02 18:04:49.056 1472-1485/? E/memtrack: Couldn't load memtrack module

12-02 18:05:00.002 1472-1485/? E/memtrack: Couldn't load memtrack module

12-02 18:05:06.403 1472-1485/? E/memtrack: Couldn't load memtrack module

12-02 18:05:06.419 1472-1485/? E/memtrack: Couldn't load memtrack module

12-02 18:05:09.294 1472-1485/? E/memtrack: Couldn't load memtrack module

12-02 18:05:09.298 1472-1489/? E/BatteryStatsService: modem info is invalid: ModemActivityInfo{ mTimestamp=0 mSleepTimeMs=0 mIdleTimeMs=0 mTxTimeMs[]=[0, 0, 0, 0, 0] mRxTimeMs=0 mEnergyUsed=0}

12-02 18:05:11.297 19657-19657/com.example.user.someapp E/libEGL: call to OpenGL ES API with no current context (logged once per thread)

12-02 18:05:11.408 19657-19657/com.example.user.someapp E/AndroidRuntime: FATAL EXCEPTION: main

Process: com.example.user.someapp, PID: 19657

com.google.firebase.database.DatabaseException: Failed to convert a value of type java.lang.String to int

at com.google.android.gms.internal.zzekp.zzb(Unknown Source:180)

at com.google.android.gms.internal.zzekp.zza(Unknown Source:312)

at com.google.android.gms.internal.zzekp.zzb(Unknown Source:0)

at com.google.android.gms.internal.zzekq.zze(Unknown Source:153)

at com.google.android.gms.internal.zzekp.zzb(Unknown Source:772)

at com.google.android.gms.internal.zzekp.zza(Unknown Source:0)

at com.google.firebase.database.DataSnapshot.getValue(Unknown Source:10)

at com.example.user.someapp.MessengerFriendsOnline$2.onDataChange(MessengerFriendsOnline.java:146)

at com.google.firebase.database.zzp.onDataChange(Unknown Source:7)

at com.google.android.gms.internal.zzeex.zza(Unknown Source:13)

at com.google.android.gms.internal.zzegs.zzbwg(Unknown Source:2)

at com.google.android.gms.internal.zzegy.run(Unknown Source:65)

at android.os.Handler.handleCallback(Handler.java:789)

at android.os.Handler.dispatchMessage(Handler.java:98)

at android.os.Looper.loop(Looper.java:164)

at android.app.ActivityThread.main(ActivityThread.java:6541)

at java.lang.reflect.Method.invoke(Native Method)

at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

回答:

首先,这是从DataSnapshot弄了半天

notifMcount = dataSnapshot.getValue(Long.class) 

其次,正确的方法,你的用户类有一个错误的数据类型

mUserList.add(singleSnapshot.getValue(User.class)); 

东西是一个字符串,但实际上一个int在Firebase中。查看您的代码,并将字符串字段与不包含引号的值进行比较。Firebase

以上是 未能将java.lang.String类型的值转换为int 的全部内容, 来源链接: utcz.com/qa/259133.html

回到顶部