我为这个java类获得了android运行时异常: 我没有得到问题发生的地方,我已经尝试了几乎所有类似的问题'答案但没有帮助!另外,我试图通过评论几乎所有不相关的函数来运行代码,但是也没有排除错误。
public class MainActivity extends AppCompatActivity
implements GoogleApiClient.OnConnectionFailedListener {
private String intentsChild;
private String curFirebaseLocation;
public static final String ANONYMOUS = "anonymous";
private static final String TAG = "MainActivity";
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;
private String mUsername;
private String mPhotoUrl;
private GoogleApiClient mGoogleApiClient;
private Button mSendButton;
private RecyclerView mMessageRecyclerView;
private LinearLayoutManager mLinearLayoutManager;
private ProgressBar mProgressBar;
private EditText mMessageEditText;
private DatabaseReference mFirebaseDatabaseReference;
private FirebaseRecyclerAdapter<FriendlyMessage, MessageViewHolder>
mFirebaseAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setStatusBarTranslucent(true);
// Set default username is anonymous.
mUsername = ANONYMOUS;
// Initialize Firebase Auth
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
//initialize facebook app activation
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(getApplication());
if (mFirebaseUser == null) {
// Not signed in, launch the Sign In activity
startActivity(new Intent(this, SignInActivity.class));
finish();
return;
} else {
mUsername = mFirebaseUser.getDisplayName();
if (mFirebaseUser.getPhotoUrl() != null) {
mPhotoUrl = mFirebaseUser.getPhotoUrl().toString();
}
}
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API)
.build();
// Initialize ProgressBar and RecyclerView.
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mMessageRecyclerView = (RecyclerView) findViewById(R.id.messageRecyclerView);
mLinearLayoutManager = new LinearLayoutManager(this);
mLinearLayoutManager.setStackFromEnd(true);
mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
curFirebaseLocation = "users/" + mFirebaseAuth.getCurrentUser().getUid().trim() + "/messages";
intentsChild = "users/" + mFirebaseAuth.getCurrentUser().getUid().trim() + "/intents";
Toast.makeText(this, "users/" + mFirebaseAuth.getCurrentUser().getUid().trim(), Toast.LENGTH_SHORT).show();
// if(mFirebaseDatabaseReference.child(curFirebaseLocation).getParent() == null){
// Toast.makeText(this, curFirebaseLocation + " already exists.", Toast.LENGTH_SHORT).show();
IntentMessage tempintent = new IntentMessage("", "");
FriendlyMessage tempmessage = new FriendlyMessage("Hello, I'm Ed, your personal assistant cum friend",
"Ed", "https://cdn1.iconfinder.com/data/icons/user-pictures/100/male3-512.png", "1476880306");
mFirebaseDatabaseReference.child(curFirebaseLocation).setValue(tempmessage);
mFirebaseDatabaseReference.child(intentsChild).setValue(tempintent);
// }
Toast.makeText(this, curFirebaseLocation, Toast.LENGTH_SHORT).show();
// New child entries
mFirebaseAdapter = new FirebaseRecyclerAdapter<FriendlyMessage,
MessageViewHolder>(
FriendlyMessage.class,
R.layout.item_message,
MessageViewHolder.class,
mFirebaseDatabaseReference.child(curFirebaseLocation)) {
@Override
protected void populateViewHolder(MessageViewHolder viewHolder,
FriendlyMessage friendlyMessage, int position) {
mProgressBar.setVisibility(ProgressBar.INVISIBLE);
viewHolder.messageTextView.setText(friendlyMessage.getText());
viewHolder.messengerTextView.setText(friendlyMessage.getName());
if (friendlyMessage.getPhotoUrl() == null) {
viewHolder.messengerImageView
.setImageDrawable(ContextCompat
.getDrawable(MainActivity.this,
tod));
} else {
Glide.with(MainActivity.this)
.load(friendlyMessage.getPhotoUrl())
.into(viewHolder.messengerImageView);
}
if (friendlyMessage.getName().equals("Ed")){
//TODO : Do this as it is necessary
// viewHolder.diffForRecSend.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.white));
// viewHolder.diffForRecSend.setBackgroundResource(R.drawable.abcd123);
}
else {
//TODO : Do this as it is necessary
// viewHolder.diffForRecSend.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.colorAccent));
// viewHolder.diffForRecSend.setBackgroundResource(R.drawable.abcd1234);
}
}
};
mFirebaseDatabaseReference.child(intentsChild).addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
IntentMessage newIntentMessage = dataSnapshot.getValue(IntentMessage.class);
String name = newIntentMessage.getIntentName();
String fields = newIntentMessage.getIntentFields();
if (name.equals("") || fields.equals(""))
return;
IntentMessage temp = new IntentMessage("", "");
mFirebaseDatabaseReference.child(intentsChild).child("-KUWmGwxVe0HCYtYWfdI").setValue(temp);
// IntentFiringActivity newIntentFiringActivity;
Log.d(TAG, "onChildUpdated: " + name + fields);
System.out.println("onChildUpdated: " + name + fields);
if (name.equals("gmail"))
fireGmailIntent(fields.split("\\$"));
else if (name.equals("alarm1"))
fireAlarmIntent(fields.split("\\$"));
else if (name.equals("alarm2"))
fireAlarmIntent2(fields.split("\\$"));
// newIntentFiringActivity = new IntentFiringActivity(name, fields);
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
IntentMessage newIntentMessage = dataSnapshot.getValue(IntentMessage.class);
Log.d(TAG, "onChildRemoved: " + newIntentMessage.getIntentName() + newIntentMessage.getIntentFields());
System.out.println("onChildRemoved: " + newIntentMessage.getIntentName() + newIntentMessage.getIntentFields());
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
int friendlyMessageCount = mFirebaseAdapter.getItemCount();
int lastVisiblePosition =
mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
// If the recycler view is initially being loaded or the
// user is at the bottom of the list, scroll to the bottom
// of the list to show the newly added message.
if (lastVisiblePosition == -1 ||
(positionStart >= (friendlyMessageCount - 1) &&
lastVisiblePosition == (positionStart - 1))) {
mMessageRecyclerView.scrollToPosition(positionStart);
}
}
});
mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
mMessageRecyclerView.setAdapter(mFirebaseAdapter);
mMessageEditText = (EditText) findViewById(R.id.messageEditText);
mMessageEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().trim().length() > 0) {
mSendButton.setEnabled(true);
} else {
mSendButton.setEnabled(false);
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
mSendButton = (Button) findViewById(R.id.sendButton);
mSendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Long tsLong = (System.currentTimeMillis() / 1000);
String ts = tsLong.toString();
FriendlyMessage friendlyMessage = new
FriendlyMessage(mMessageEditText.getText().toString(),
mUsername,
mPhotoUrl,
ts);
mFirebaseDatabaseReference.child(curFirebaseLocation)
.push().setValue(friendlyMessage);
mMessageEditText.setText("");
}
});
}
private void fireAlarmIntent(String[] intentFields) {
int hours = Integer.parseInt(intentFields[0].trim());
int minutes;
if(intentFields[1].trim().equals("")){
minutes = 0;
}
else {
minutes = Integer.parseInt(intentFields[1].trim());
}
Intent i = new Intent(AlarmClock.ACTION_SET_ALARM);
i.putExtra(AlarmClock.EXTRA_SKIP_UI, true);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra(AlarmClock.EXTRA_HOUR, hours);
i.putExtra(AlarmClock.EXTRA_MINUTES, minutes);
int temp1 = 1;
startActivityForResult(i, temp1);
String temp = "Alarm set for " + hours + " : " + minutes;
Log.d(TAG, temp);
// Toast.makeText(this, temp, Toast.LENGTH_SHORT).show();
}
private void fireAlarmIntent2(String[] intentFields) {
int hours = Integer.parseInt(intentFields[0].trim());
int curhours = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
int finalhours = (hours + curhours) % 24;
int curmin = Calendar.getInstance().get(Calendar.MINUTE);
Intent i = new Intent(AlarmClock.ACTION_SET_ALARM);
i.putExtra(AlarmClock.EXTRA_SKIP_UI, true);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra(AlarmClock.EXTRA_HOUR, finalhours);
i.putExtra(AlarmClock.EXTRA_MINUTES, curmin);
int temp1 = 1;
startActivityForResult(i, temp1);
String temp = "Alarm set for " + finalhours + " : " + curmin;
Log.d(TAG, temp);
Log.d(TAG, "currentHours: " + curhours + " and received from server : " + hours + " hence total is : " + finalhours);
// Toast.makeText(this, temp, Toast.LENGTH_SHORT).show();
}
private void fireGmailIntent(String[] intentFields) {
String[] email = new String[1];
email[0] = intentFields[0];
Log.d(TAG, "My unique log " + email[0]);
String subject = intentFields[1];
String body = intentFields[2];
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setType("message/rfc822");
intent.setData(Uri.parse("mailto:"));
intent.putExtra(Intent.EXTRA_EMAIL, email);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, body);
Log.d(TAG, "My unique log " + email[0] + "__" + subject + "__" + body);
if (intent.resolveActivity(getPackageManager()) != null) {
int temp = 4;
startActivityForResult(intent, temp);
Log.d(TAG, "My unique log " + email[0] + "__" + subject + "__" + body + "again");
}
}
protected void setStatusBarTranslucent(boolean makeTranslucent) {
if (makeTranslucent) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
}
// Firebase instance variables
@Override
public void onStart() {
super.onStart();
// Check if user is signed in.
// TODO: Add code to check if user is signed in.
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
startActivity(new Intent(this, SignInActivity.class));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.sign_out_menu:
mFirebaseAuth.signOut();
LoginManager.getInstance().logOut();
FirebaseAuth.getInstance().signOut();
Auth.GoogleSignInApi.signOut(mGoogleApiClient);
mUsername = ANONYMOUS;
startActivity(new Intent(this, SignInActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
// An unresolvable error has occurred and Google APIs (including Sign-In) will not
// be available.
Log.d(TAG, "onConnectionFailed:" + connectionResult);
Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
}
public static class MessageViewHolder extends RecyclerView.ViewHolder {
public TextView messageTextView;
public TextView messengerTextView;
public CircleImageView messengerImageView;
public LinearLayout diffForRecSend;
public MessageViewHolder(View v) {
super(v);
messageTextView = (TextView) itemView.findViewById(R.id.messageTextView);
messengerTextView = (TextView) itemView.findViewById(R.id.messengerTextView);
messengerImageView = (CircleImageView) itemView.findViewById(R.id.messengerImageView);
diffForRecSend = (LinearLayout) itemView.findViewById(R.id.message_main_id);
}
}
}
这是logcat错误:
Process: com.google.firebase.codelab.friendlychat, PID: 20107
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.google.firebase.codelab.friendlychat.FriendlyMessage
at com.google.android.gms.internal.zzaln.zzd(Unknown Source)
at com.google.android.gms.internal.zzaln.zzb(Unknown Source)
at com.google.android.gms.internal.zzaln.zza(Unknown Source)
at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
at com.firebase.ui.database.FirebaseRecyclerAdapter.parseSnapshot(FirebaseRecyclerAdapter.java:147)
at com.firebase.ui.database.FirebaseRecyclerAdapter.getItem(FirebaseRecyclerAdapter.java:136)
at com.firebase.ui.database.FirebaseRecyclerAdapter.onBindViewHolder(FirebaseRecyclerAdapter.java:176)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:5453)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:5486)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4723)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4599)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1988)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1384)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1347)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:549)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3003)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:2881)
at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3265)
at android.view.View.layout(View.java:16969)
at android.view.ViewGroup.layout(ViewGroup.java:5583)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1189)
at android.view.View.layout(View.java:16969)
at android.view.ViewGroup.layout(ViewGroup.java:5583)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:396)
at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
at android.view.View.layout(View.java:16969)
at android.view.ViewGroup.layout(ViewGroup.java:5583)
at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:437)
at android.view.View.layout(View.java:16969)
at android.view.ViewGroup.layout(ViewGroup.java:5583)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:396)
at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
at android.view.View.layout(View.java:16969)
at android.view.ViewGroup.layout(ViewGroup.java:5583)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:2001)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1844)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1753)
at android.view.View.layout(View.java:16969)
at android.view.ViewGroup.layout(ViewGroup.java:5583)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:396)
at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
at com.android.internal.policy.PhoneWindow$DecorView.onLayout(PhoneWindow.java:2728)
at android.view.View.layout(View.java:16969)
at android.view.ViewGroup.layout(ViewGroup.java:5583)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2552)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2255)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1321)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6708)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:894)
at android.view.Choreographer.doCallbacks(Choreographer.java:696)
at android.view.Choreographer.doFrame(Choreographer.java:631)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:880)
at android.os.Handler.handleCallback(Handler.java:822)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Loop
以下是我的json结构的快照供参考:
{
"users" : {
"ERyWg81WxrXUb0sjsu9hv9T7K0E3" : {
"intents" : {
"intentName" : "",
"intentValue" : ""
},
"messages" : {
"-KViVgc7ZG051eMXP0-5" : {
"name" : "Ed",
"text" : "Hello, I'm Ed, your personal assistant cum friend",
"timestamp" : "1476880306"
}
}
},
"Y9UNlizDSobddO8cdq7K4ChipYa2" : {
"intents" : {
"intentName" : "",
"intentValue" : ""
},
"messages" : {
"-KViVgc7ZG051eMXP0-5" : {
"name" : "Ed",
"text" : "Hello, I'm Ed, your personal assistant cum friend",
"timestamp" : "1476880306"
}
}
}
}
}
修改 好的,经过调试,我发现问题出在以下几行: 所以,问题现在缩小了。请帮我找出其余的错误:
mFirebaseAdapter = new FirebaseRecyclerAdapter<FriendlyMessage,
MessageViewHolder>(
FriendlyMessage.class,
R.layout.item_message,
MessageViewHolder.class,
mFirebaseDatabaseReference.child(curFirebaseLocation)) {
@Override
protected void populateViewHolder(MessageViewHolder viewHolder,
FriendlyMessage friendlyMessage, int position) {
//...//
}
编辑2 :
我注意到一个重要的方面:在没有数据连接的情况下运行应用程序时,应用程序仍然显示错误&#34;不幸的是Ed已经停止&#34;,这是不自然的,就像我的应用程序工作时(当我的应用程序是在一个阶段(比现在少),它首先用于从firebase数据库加载一些数据,然后显示错误。但是这一次,它甚至在加载数据库中的数据之前就显示出错误,这导致了一个结论,即错误并不在问题的snapshot
部分,就好像它会有在这种情况下,应用程序在离线状态下不会显示错误,直到数据加载为止,它应该一直显示进度对话框。
编辑3 我发现为什么会收到错误消息:
这一行:
mFirebaseAdapter =新的FirebaseRecyclerAdapter(
FriendlyMessage.class,
R.layout.item_message,
MessageViewHolder.class,
mFirebaseDatabaseReference.child(curFirebaseLocation)){...
在这一行中,当我传递一些其他字符串而不是curFirebaseLocation
时,没有错误,我的应用程序加载正常,但是当我传递curFirebaseLocation
变量时,我得到错误,如上面的LogCat中所示。现在,我只需要知道为什么我收到错误unable to convert java.lang.String to ...FriendlyMessage
,即使curFirebaseLocation
和我传递的字符串(我没有得到错误)的值完全相同。我认为它与FirebaseRecyclerAdapter有很大关系。请帮忙!!
注意:我记录了curFirebaseLocation
和intentsMessage
字符串的输出,发现它们完全正常。当我复制它们并将它们粘贴到浏览器中时,它们将我带到了预期的位置。
如果需要进一步澄清,请提及。
提前谢谢!
答案 0 :(得分:0)
Firebase
在类中需要一个空构造函数。确保在FriendlyMessage
类中明确定义了一个空构造函数。
答案 1 :(得分:0)
Firebase的身份验证和数据库同步存在问题,正在访问数据库的用户未在auth部分注册,也有一些小故障,代码现在工作正常,我得到了子节点正确。