2017-08-17 31 views
1

最初,在設置自定義列表視圖之後,不再添加更多項目,即在列表視圖中顯示,儘管從FirebaseMessagingService添加了對象項目。 我已經聲明listView爲靜態,以便可以將Object添加到其他類或服務的列表中。 這裏是我的代碼:無法將對象添加到FirebaseMessagingService的自定義列表視圖

FirebaseMessagingService:

@Override 
public void onMessageReceived(final RemoteMessage remoteMessage) { 

    //Toast.makeText(getApplicationContext(), remoteMessage.getData().get("transaction"),Toast.LENGTH_SHORT).show(); 
    Handler handler = new Handler(Looper.getMainLooper()); 
    handler.post(new Runnable() { 

     @Override 
     public void run() { 

      Gson gson = new Gson(); 
      Block b = gson.fromJson(remoteMessage.getData().get("transaction"), Block.class); 
      OpenChain.arrayList.add(b); 
     } 
    }); 
} 

的ListView活動代碼:

public static ArrayList<Block> arrayList; 

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

    arrayList = new ArrayList<>(); 

    getSupportActionBar().setTitle("Vote Ledger"); 
    getSupportActionBar().setDisplayHomeAsUpEnabled(true); 

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

    BlockchainAdap adap = new BlockchainAdap(this, arrayList); 

    listView.setAdapter(adap); 
    adap.notifyDataSetChanged(); 

} 

**我收到的對象從雲JSON格式 **也能從中添加對象listview活動,但不是來自FirebaseMessagingSerivce

回答

1

I已聲明listView爲靜態,因此Object可以從其他類或服務添加到 列表中。

沒有,很好的解決方案,你是泄漏的ArrayList在這裏,因爲它不會當活動被銷燬被垃圾收集。

在這種情況下,更好的方法是使用LocalBroadCast

結帳的鏈接信息

https://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager.html

現在,你在做什麼錯。您正在修改陣列列表,但您並未通知適配器。

試試這個..

private ArrayList<Block> arrayList = new ArrayList<>(); 
private BlockchainAdap adap; 

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

    getSupportActionBar().setTitle("Vote Ledger"); 
    getSupportActionBar().setDisplayHomeAsUpEnabled(true); 

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

    adap = new BlockchainAdap(this, arrayList); 

    listView.setAdapter(adap); 
} 

public static void updateList(Block b){ 
    arrayList.add(b); 
    adap.swap(arrayList); 
} 

在FirebaseMessagingService

@Override 
public void onMessageReceived(final RemoteMessage remoteMessage) { 
      Gson gson = new Gson(); 
      Block b = gson.fromJson(remoteMessage.getData().get("transaction"), Block.class); 
      OpenChain.updateList(b); 
} 

此外,在您的** ** BlockchainAdap公開了一種交換。

class BlockchainAdap { 
    ArrayList<Block> arrayList; 
    BlockchainAdap(ArrayList<Block> arrayList){ 
    this.arrayList = arrayList; 
    } 

    public void swap(ArrayList<Block> arrayList){ 
    this.arrayList = arrayList; 
    notifydatasetChanged(); 
    } 

    // other methods 

} 

這是可行的,但使用

  • LocalBroadcastReceiver從消息服務開鏈活動。
  • 使用RecyclerView而不是ListView。
相關問題