2014-12-27 8 views
3

Android에서 Firebase 데이터를 설정하는 방법을 배우는 중입니다. 데이터베이스에 쓸 수 있지만 읽을 수 없어 다시 내 응용 프로그램에 표시 할 수 없습니다. 내 응용 프로그램은 매우 간단합니다 (단지 현재 하나의 기본 화면이 있습니다). 나는 배움으로써 데이터가 페이지에 어떻게 표시되는지는 신경 쓰지 않습니다. 지금은 텍스트보기로 표시하려고합니다. 나는 응용 프로그램을 실행하면Firebase로 Android에서 데이터를 검색하는 데 문제가 있음

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" 
android:layout_height="match_parent"   android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
android:paddingBottom="@dimen/activity_vertical_margin" 
tools:context=".MainActivity"> 


<TextView 
    android:id="@+id/sampleTextView" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/hello_world"/> 


</LinearLayout> 

, 그것은 충돌 :

package com.example.ispotrachel.myapplication; 

import android.support.v7.app.ActionBarActivity; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.TextView; 

import com.firebase.client.DataSnapshot; 
import com.firebase.client.Firebase; 
import com.firebase.client.FirebaseError; 
import com.firebase.client.ValueEventListener; 

import java.util.HashMap; 
import java.util.Map; 


public class MainActivity extends ActionBarActivity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Firebase.setAndroidContext(this); 

    Firebase ref = new Firebase("https://blistering-torch-9015.firebaseio.com"); 

    class User { 
     private int birthYear; 
     private String fullName; 

     public User() { 
     } 

     public User(String fullName, int birthYear) { 
      this.fullName = fullName; 
      this.birthYear = birthYear; 
     } 

     public long getBirthYear() { 
      return birthYear; 
     } 

     public String getFullName() { 
      return fullName; 
     } 
    } 

    User user1 = new User("Name 1", 1982); 
    User user2 = new User("Name 2", 1972); 

    Firebase usersRef = ref.child("users"); 

    Map<String, User> users = new HashMap<String, User>(); 
    users.put("user1", user1); 
    users.put("user 2", user2); 

    usersRef.setValue(users); 

    Firebase postRef = ref.child("posts"); 

    Map<String, String> post1 = new HashMap<String, String>(); 
    post1.put("author", "user1"); 
    post1.put("title", "Announcing COBOL, a New Programming Language"); 
    postRef.push().setValue(post1); 

    Map<String, String> post2 = new HashMap<String, String>(); 
    post2.put("author", "user2"); 
    post2.put("title", "The Turing Machine"); 
    postRef.push().setValue(post2); 
    ref.addValueEventListener(new ValueEventListener() { 


    @Override 
    public void onDataChange(DataSnapshot arg0) { 
      //System.out.println(arg0.getValue()); 
      TextView textViewSample = (TextView) findViewById(R.id.sampleTextView); 
      textViewSample.setText(arg0.getValue(String.class)); 
     } 

     @Override 
     public void onCancelled(FirebaseError firebaseError) { 
      System.out.println("the read failed"); 
     } 

    }); 
}} 

여기 내 activity_main.xml입니다 :

은 여기 내 주 활동 자바입니다. 여기에 로그 캣 오류 메시지는 다음과 같습니다

12-27 12:15:02.678 1895-1895/com.example.ispotrachel.myapplication I/art﹕ Not late  enabling -Xcheck:jni (already on) 
12-27 12:15:02.946 1895-1907/com.example.ispotrachel.myapplication I/art﹕ Background  sticky concurrent mark sweep GC freed 3867(286KB) AllocSpace objects, 0(0B) LOS objects, 11% free, 1009KB/1135KB, paused 2.595ms total 117.910ms 
12-27 12:15:03.317 1895-1926/com.example.ispotrachel.myapplication D/OpenGLRenderer﹕ Render dirty regions requested: true 
12-27 12:15:03.320 1895-1895/com.example.ispotrachel.myapplication D/﹕ HostConnection::get() New Host Connection established 0xa6667e80, tid 1895 
12-27 12:15:03.327 1895-1895/com.example.ispotrachel.myapplication D/Atlas﹕ Validating map... 
12-27 12:15:03.391 1895-1926/com.example.ispotrachel.myapplication D/﹕ HostConnection::get() New Host Connection established 0xa66ef3b0, tid 1926 
12-27 12:15:03.405 1895-1926/com.example.ispotrachel.myapplication I/OpenGLRenderer﹕ Initialized EGL, version 1.4 
12-27 12:15:03.422 1895-1926/com.example.ispotrachel.myapplication D/OpenGLRenderer﹕ Enabling debug mode 0 
12-27 12:15:03.439 1895-1926/com.example.ispotrachel.myapplication W/EGL_emulation﹕ eglSurfaceAttrib not implemented 
12-27 12:15:03.439 1895-1926/com.example.ispotrachel.myapplication W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa66b7880, error=EGL_SUCCESS 
12-27 12:15:07.474 1895-1926/com.example.ispotrachel.myapplication W/EGL_emulation﹕ eglSurfaceAttrib not implemented 
12-27 12:15:07.474 1895-1926/com.example.ispotrachel.myapplication W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa66b7880, error=EGL_SUCCESS 
12-27 12:15:13.993 1895-1895/com.example.ispotrachel.myapplication D/AndroidRuntime﹕ Shutting down VM 

--------- beginning of crash 
12-27 12:15:13.993 1895-1895/com.example.ispotrachel.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main 
Process: com.example.ispotrachel.myapplication, PID: 1895 com.firebase.client.FirebaseException: Failed to bounce to type 
     at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:196) 
     at com.example.ispotrachel.myapplication.MainActivity$1.onDataChange(MainActivity.java:79) 
     at com.firebase.client.core.ValueEventRegistration$1.run(ValueEventRegistration.java:48) 
     at android.os.Handler.handleCallback(Handler.java:739) 
     at android.os.Handler.dispatchMessage(Handler.java:95) 
     at android.os.Looper.loop(Looper.java:135) 
     at android.app.ActivityThread.main(ActivityThread.java:5221) 
     at java.lang.reflect.Method.invoke(Native Method) 
     at java.lang.reflect.Method.invoke(Method.java:372) 
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 

Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token 
     at [Source: [email protected]; line: 1, column: 1] 
     at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:575) 
     at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:46) 
     at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:11) 
     at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2888) 
     at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2034) 
     at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:192) 
     at com.example.ispotrachel.myapplication.MainActivity$1.onDataChange(MainActivity.java:79) 
     at com.firebase.client.core.ValueEventRegistration$1.run(ValueEventRegistration.java:48) 
     at android.os.Handler.dispatchMessage(Handler.java:95) 
     at android.os.Looper.loop(Looper.java:135) 
     at android.app.ActivityThread.main(ActivityThread.java:5221) 
     at java.lang.reflect.Method.invoke(Native Method) 
     at java.lang.reflect.Method.invoke(Method.java:372) 
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)device not found 
+0

오류 메시지가 있습니까? – emecas

+0

일하는 대신에 어떤 일이 발생합니까? (예 : 오류 메시지) –

+0

@ispotrachel : 아래에있는 편집 링크를 클릭하여 질문에 스택 추적을 추가하십시오. 그렇게하면 더 쉽게 읽을 수있는 형식으로 서식을 지정할 수 있습니다. –

답변

2

TL; DR

당신이 문자열로 JSON 객체를로드하려는 것 같습니다.

오류 메시지는 Firebase 클라이언트가 일부 데이터를 가져 왔지만 지정한 유형으로 변환 할 수 없음을 나타냅니다. 그 값 이벤트 리스너에서

ref.addValueEventListener(new ValueEventListener() { ... 

당신이 전체 중포 기지를로드 중포 기지를 말하는 것 : 당신은 여기에서 중포 기지의 루트에 ValueEventListener을 추가하는

문제에 대한

세부 사항 예 : String :

textViewSample.setText(arg0.getValue(String.class)); 

매우 간단하게 처리하면 정상적으로 작동합니다. 단일 문자열 만 포함 된 Firebase.

  1. : 당신의 중포 기지가 하나 이상의 String

    당신은 몇 가지 옵션을 가지고 그것을 를 해결하는 방법 :)을 많이 가지고 같이하지만, 코드의 나머지 부분을 기반으로, 그것은 본다

    이벤트 수신기를 트리 아래쪽에 부착하십시오.

    ref.child("users/user1/fullName").addValueEventListener(new ValueEventListener() { 
    
        @Override 
        public void onDataChange(DataSnapshot arg0) { 
         TextView textViewSample = (TextView) findViewById(R.id.sampleTextView); 
         textViewSample.setText(arg0.getValue(String.class)); 
        } 
        ... 
    } 
    
  2. 를 또는, 전체 사용자를 얻을 수 있지만, User 대신 String의로 해석 : 당신은 문자열로 사용자의 전체 이름을 얻을 수

    ref.child("users/user1/fullName").addValueEventListener(new ValueEventListener() { 
    
        @Override 
        public void onDataChange(DataSnapshot arg0) { 
         User tempUser = arg0.getValue(User.class); 
         TextView textViewSample = (TextView) findViewById(R.id.sampleTextView); 
         textViewSample.setText(tempUser.getFullName()); 
        } 
        ... 
    } 
    
0

내가 가진 비슷한 문제.

DatabaseReference chatRef = database.getReference("chats"); 
    chatRef.keepSynced(true); 
    Query queryRef = chatRef.orderByChild("id"); 

    queryRef.addChildEventListener(new ChildEventListener() { 
     // Retrieve new posts as they are added to the database 
     @Override 
     public void onChildAdded(DataSnapshot snapshot, String previousChildKey) { 
      ChatPost newPost = snapshot.getValue(ChatPost.class); 
      ChatPost topic = new ChatPost(newPost.id, newPost.topic); 
      addChatTopic(topic); 
      System.out.println("NEW Child Topic: " + newPost.topic); 

      chatAdapter.addItem(newPost); 
     } 

     @Override 
     public void onChildChanged(DataSnapshot dataSnapshot, String s) { 
      ChatPost newPost = dataSnapshot.getValue(ChatPost.class); 
      ChatPost topic = new ChatPost(newPost.id, newPost.topic); 
      addChatTopic(topic); 
      System.out.println("CHANGED Child Topic: " + newPost.topic); 

      chatAdapter.updateItem(newPost); 
     } 

     @Override 
     public void onChildRemoved(DataSnapshot dataSnapshot) { 
      ChatPost newPost = dataSnapshot.getValue(ChatPost.class); 
      ChatPost topic = new ChatPost(newPost.id, newPost.topic); 
      chatTopicsList.add(topic); 
      System.out.println("REMOVED Child Topic: " + newPost.topic); 

      chatAdapter.removeItem(newPost); 
     } 

     @Override 
     public void onChildMoved(DataSnapshot dataSnapshot, String s) { 

     } 

     @Override 
     public void onCancelled(DatabaseError databaseError) { 

     } 
    }); 

그것은 내가 푸시를 사용하지 않은 때까지 일을() 새로운 항목을 추가하기위한 :

내가 중포 기지에서 데이터를 검색하는 방법을 코드입니다. firebase 콘솔의 데이터는 here입니다.

예외 텍스트 :

07-05 16 : 45 : 07.097 29997-29997/com.skl.bingofire E/AndroidRuntime : FATAL EXCEPTION : 메인 프로세스 : com.skl.bingofire, PID : 29997 com.google.firebase.database.DatabaseException : 은 비 직렬화이지만 목록은 java.util.HashMap com.google.android.gms.internal.zzaix.zza (알 수없는 출처) 에있는 동안 목록이 필요합니다. com.google.android.gms.internal.zzaix.zza (알 수없는 출처) com.google.android.gms.internal.zzaix.zzb (알 수없는 출처) com.google.android.gms.internal.zzaix $ zza.zze (알 수없는 출처) com.google.android.gms.internal .zzaix $ zza.zzaC (알 수없는 출처) com.google.android.gms.internal.zzaix.zzd (알 수없는 출처) com.google.android.gms.internal.zzaix.zzb (알 수없는 출처) at com.google.android.gms.internal.zzaix.zza (알 수없는 출처) at com.google.firebase.database.DataSnapshot.getValue (알 수없는 출처) com.skl.bingofire.activities.MainActivity $ 7.onChildAdded (MainActivity.java:228) (com.google.android.gms.internal) zzaer.zza (알 수없는 출처) at com.google.android.gms.internal.zzagp.zzSu (알 수없는 출처) com.google.android.gms.internal.zzags $ 1.run (알 수없는 출처) android. os.Handler.handleCallback (Handler.java:739) android.os.Handler.dispatchMessage (Handler.java:95) at android.os.Looper.loop (Looper.java:148) android.app에 있습니다. com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run (ZygoteInit.java:726) 에서에서 java.lang.reflect.Method.invoke (기본 방법) 에서 ActivityThread.main (ActivityThread.java:5417) com.android.inter nal.os.ZygoteInit.main (ZygoteInit.java:616) 07-05 16 : 45 : 16.924 29997-30029/com.skl.bingofire E/DynamiteModule : 실패했습니다 로드 모듈 설명자 클래스 : 클래스를 찾지 못했습니다 "com.google.android.gms.dynamite.descriptors.com.google.firebase.auth.ModuleDescriptor"경로상의 : DexPathList [[zip 파일 "/data/app/com.skl.bingofire-1/base.apk

class ChatPost { 
    public String id; 
    public String topic; 
    public String color; 
    public ArrayList<Message> messages; 
} 
"] nativeLibraryDirectories =/데이터/애플리케이션/com.skl.bingofire-1/LIB/암 /벤더/LIB/시스템/LIB]

I는이 모델을 사용

나는 데이터의 목록에 "-KLdskjdkjkjdjksjdksjdjsdjsjk"와 같은 데이터 목록이 있으면 firebase가 구멍 목록을 "HashMap"을 "ArrayList"로 인식하는 것으로 나타났습니다. 나는이 구조 내 모델 변경 :

class ChatPost { 
    public String id; 
    public String topic; 
    public String color; 
    public HashMap<String, Message> messages; 
} 

을 그리고 "-KLdskjdkjkjdjksjdksjdjsdjsjk"와 같은 키와 채팅 메시지의 나머지 부분에 추가됩니다. 그리고 지금 제 코드가 작동 중입니다. 그러나 나는 그것이 분명하지 않다고 생각한다.

관련 문제