2016-11-19 14 views
0

データベースが更新されるたびにフラグメントを更新したいと考えました。 [連絡先を設定してデータベースに保存する]がうまくいけば、データも取得できます。しかし、毎回新しい連絡先を設定しようとすると、データベースは更新されましたが、取得部分は更新されません。それは私が他の断片や活動に切り替えた後にのみ更新することができます。新しいデータを設定した後にフラグメントをリフレッシュするには?データを取得することはできますが、新しい連絡先を設定した後は自動的に更新することはできません

// Javaクラスファイル

public class UserProfile extends AppCompatActivity implements OnMenuItemClickListener, OnMenuItemLongClickListener { 

private final int PICK_CONTACT = 0; 

private Toolbar mToolbar; 
private TextView mTxtToolbarTitle; 

private FragmentManager fragmentManager; 
private ContextMenuDialogFragment mMenuDialogFragment; 
private FirebaseAuth firebaseAuth; 
private DatabaseReference databaseReference; 
private Button btn_msgD; 
private String eName,eTel,userID; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_m); 

    if (android.os.Build.VERSION.SDK_INT >= 21) { 
     Window window = this.getWindow(); 
     window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); 
     window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);   window.setStatusBarColor(this.getResources().getColor(R.color.appbar_color)); 
    } 
    fragmentManager = getSupportFragmentManager(); 
    initToolBar(); 
    initMenuFragment(); 
    addFragment(new Fragment_US(), true, R.id.fragment); 

    databaseReference = FirebaseDatabase.getInstance().getReference(); 
    firebaseAuth = FirebaseAuth.getInstance(); 
    userID = firebaseAuth.getCurrentUser().getUid(); 
    if (firebaseAuth.getCurrentUser() == null) { 
     finish(); 
     startActivity(new Intent(this, LoginActivity.class)); 
    } 

    displayUserInfo(); 
} 

//別のページへのボタンの意図

public void initMyAccount(View view) { 

    Intent intent = new Intent(UserProfile.this, MyAccount.class); 
    startActivity(intent); 
} 

//ボタンの設定連絡先

public void initSetEmergencyContact(View view){ 
    Intent it = new Intent (Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI); 
    startActivityForResult(it,PICK_CONTACT); 
} 

//データベースとディスプレイからデータを取得しますin textView

public void displayUserInfo(){ 

    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() { 
     @Override 
     public void onDataChange(DataSnapshot dataSnapshot) { 
      for (DataSnapshot users:dataSnapshot.getChildren()) 
      { 
       for (DataSnapshot user:users.getChildren()) 
       { 
        if (user.getKey().equals(userID)) 
        { 
         for (DataSnapshot EmergencyContact:user.getChildren()) 
         { 
          if (EmergencyContact.getKey().equals("EmergencyContact")) 
          { 
           EmergencyContact ec = EmergencyContact.getValue(EmergencyContact.class); 
           TextView uInfoTV = (TextView)findViewById(R.id.textView_kNameTV); 
           TextView uInfoTV2 = (TextView)findViewById(R.id.textView_kNoTV); 
           uInfoTV.setText(ec.getkName()); 
           uInfoTV2.setText(ec.getkTel()); 
          } 
         } 
        } 
       } 
      } 
     } 

     @Override 
     public void onCancelled(DatabaseError databaseError) { 
      Toast.makeText(getApplicationContext(), "Something went wrong", Toast.LENGTH_SHORT).show(); 
     } 
    }); 
} 
public void onActivityResult(int reqCode, int resultCode, Intent data){ 
    super.onActivityResult(reqCode, resultCode, data); 

    switch(reqCode) 
    { 
     case (PICK_CONTACT): 
      if (resultCode == Activity.RESULT_OK) 
      { 
       Uri contactData = data.getData(); 
       Cursor c = managedQuery(contactData, null, null, null, null); 
       if (c.moveToFirst()) 
       { 
        String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID)); 

        String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)); 

        if (hasPhone.equalsIgnoreCase("1")) 
        { 
         Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null, 
           ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,null, null); 
         phones.moveToFirst(); 
         String cNumber =phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 
         Toast.makeText(getApplicationContext(), cNumber, Toast.LENGTH_SHORT).show(); 

         String nameContact = phones.getString(phones.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); 
         String numContact = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 

         eName = nameContact; 
         eTel = numContact; 

         Toast.makeText(getApplicationContext(), nameContact, Toast.LENGTH_SHORT).show(); 
         FirebaseUser user = firebaseAuth.getCurrentUser(); 

         EmergencyContact eCon = new EmergencyContact(eName,eTel); 
         eCon.setkName(eName); 
         eCon.setkTel(eTel); 
         databaseReference = FirebaseDatabase.getInstance().getReference(); 
         databaseReference.child("users").child(userID).child("EmergencyContact").setValue(eCon); 
         //editText.setText(nameContact+ " "+ cNumber); 
        } 
       } 
      } 
    } 
} 

//断片コンテンツ

private void initMenuFragment() { 

    MenuParams menuParams = new MenuParams(); 
    menuParams.setActionBarSize((int) getResources().getDimension(R.dimen.tool_bar_height)); 
    menuParams.setMenuObjects(getMenuObjects()); 
    menuParams.setClosableOutside(false); 
    mMenuDialogFragment = ContextMenuDialogFragment.newInstance(menuParams); 
    mMenuDialogFragment.setItemClickListener(this); 
    mMenuDialogFragment.setItemLongClickListener(this); 
} 

private List<MenuObject> getMenuObjects() { 

    List<MenuObject> menuObjects = new ArrayList<>(); 

    MenuObject close = new MenuObject(); 
    close.setResource(R.drawable.icn_close); 

    MenuObject accPage = new MenuObject("UserProfile"); 
    accPage.setResource(R.drawable.icn_3); 

    MenuObject chat = new MenuObject("PPChat"); 
    BitmapDrawable bd = new BitmapDrawable(getResources(), 
      BitmapFactory.decodeResource(getResources(), R.drawable.icn_1)); 
    chat.setDrawable(bd); 

    MenuObject contact = new MenuObject("ContactDoctor"); 
    contact.setResource(R.drawable.icn_4); 

    menuObjects.add(close); 
    menuObjects.add(accPage); 
    menuObjects.add(chat); 
    menuObjects.add(contact); 
    return menuObjects; 
} 

//ツールバー

private void initToolBar() { 

    mToolbar = (Toolbar) findViewById(R.id.appbar); 
    mTxtToolbarTitle = (TextView) mToolbar.findViewById(R.id.txtTitle); 
    setSupportActionBar(mToolbar); 
    //mTxtToolbarTitle.setText(""); 
    if (getSupportActionBar() != null) { 
     getSupportActionBar().setHomeButtonEnabled(true); 
     getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
     getSupportActionBar().setDisplayShowTitleEnabled(false); 
    } 

    mToolbar.setNavigationIcon(R.drawable.btn_back); 
    mToolbar.setNavigationOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Intent intent = new Intent (UserProfile.this, MainActivity.class); 
      startActivity(intent); 
     } 
    }); 
    mTxtToolbarTitle.setText("User Profile"); 
} 

protected void addFragment(Fragment fragment, boolean addToBackStack, int containerId) { 

    invalidateOptionsMenu(); 
    String backStackName = fragment.getClass().getName(); 
    boolean fragmentPopped = fragmentManager.popBackStackImmediate(backStackName, 0); 
    if (!fragmentPopped) { 
     FragmentTransaction transaction = fragmentManager.beginTransaction(); 
     transaction.add(containerId, fragment, backStackName) 
       .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); 
     if (addToBackStack) 
      transaction.addToBackStack(backStackName); 
     transaction.commit(); 
    } 
} 

@Override 
public boolean onCreateOptionsMenu(final Menu menu) { 

    MenuInflater inflater = getMenuInflater(); 
    inflater.inflate(R.menu.menu_main, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 

    switch (item.getItemId()) { 
     case R.id.context_menu: 
      if (fragmentManager.findFragmentByTag(ContextMenuDialogFragment.TAG) == null) { 
       mMenuDialogFragment.show(fragmentManager, ContextMenuDialogFragment.TAG); 
      } 
      //Toast.makeText(this, "Clicked on position: " , Toast.LENGTH_SHORT).show(); 
      break; 
    } 
    return super.onOptionsItemSelected(item); 
} 

@Override 
public void onBackPressed() { 

    if (mMenuDialogFragment != null && mMenuDialogFragment.isAdded()) { 
     mMenuDialogFragment.dismiss(); 
    } else { 
     finish(); 
    } 
} 

//フラグメント位置のすべての

@Override 
public void onMenuItemClick(View clickedView, int position) { 
    if(position == 1){ 
     Intent intent = new Intent(UserProfile.this, UserProfile.class); 
     startActivity(intent); 
    } 

    if(position == 2){ 
     Intent intent = new Intent(UserProfile.this, PPChat.class); 
     startActivity(intent); 
    } 

    if(position == 3){ 
     Intent intent = new Intent(UserProfile.this, ContactDoctor.class); 
     startActivity(intent); 
    } 
    // Toast.makeText(this, "Clicked on position: " + position, Toast.LENGTH_SHORT).show(); 
} 

@Override 
public void onMenuItemLongClick(View clickedView, int position) { 
    //Toast.makeText(this, "Long clicked on position: " + position, Toast.LENGTH_SHORT).show(); 
} 
} 

答えて

0

まず、5秒、原因よりも長持ちすることができますすべてのアクションANRでは、ServiceまたはIntentServiceを使用して別のスレッドで実行する必要があります。その後、ExtReceiverのクラスを使用して、ビュー内の情報を更新します。あなたがDBからデータを要求し、そこから

フラグメント:

@EFragment(R.layout.fragment_statistics) 
public class StatisticsFragment extends Fragment { 

DbResultReceiver dbResultReceiver; 

final static String TAG = "Debug_StatFragment"; 

class DbResultReceiver extends ResultReceiver { 

    private static final String TAG = "Debug_DbResultReceiver"; 

    DbResultReceiver(Handler handler) { 
     super(handler); 
    } 

    @Override 
    protected void onReceiveResult(int resultCode, Bundle resultData) { 
     Log.d(TAG, "Result code : " + resultCode); 

     switch(resultCode){ 
      case AppConstants.RESULT_CURRENT_WEEK : 
       writeRows(resultData); 
       break; 
     } 
    } 
} 

@ViewById(R.id.tv_ex_stat) 
TextView tvExampleText; 

@Override 
public void onAttach(Context context) { 
    super.onAttach(context); 
    Log.d(TAG, "onAttach()"); 

    // Register receiver for get response from intent service 
    dbResultReceiver = new DbResultReceiver(new Handler()); 

} 

@Override 
public void onCreate(@Nullable Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    Log.d(TAG, "Starting service.. "); 

    refreshStatistics(); 
} 


private void refreshStatistics(){ 
    Log.d(TAG, "Refreshing statistics table .. "); 
    Intent intent = new Intent(getContext(), DbIntentService.class); 
    intent.setAction(ACTION_GET_WEEK_DATA); 
    intent.putExtra(EXTRAS_INTENT_RESULT, dbResultReceiver); 
    getActivity().startService(intent); 
} 

private void writeRows(Bundle data){ 

    Log.d(TAG, "Writing rows.."); 

    int rowCount = data.getInt(EXTRAS_DB_ROWS_COUNT); 
    String text = ""; 

    Log.d(TAG, "amount of rows: " + rowCount); 

    for(int i = 0; i < rowCount; i++){ 
     text += "Date : " + data.getString(AppConstants.EXTRAS_DB_DATE + i) + 
       "Amount : " + data.getLong(AppConstants.EXTRAS_DB_AMOUNT + i) + 
       "Drunk : " + data.getDouble(AppConstants.EXTRAS_DB_DRUNK + i) + "\n"; 

    } 

    tvExampleText.setText(text); 
} 

}

そして実際IntentService:

public class DbIntentService extends IntentService { 

private Intent mIntent; 
private DbAdapter db; 

private Bundle data = null; 

private static final String TAG = "Debug_DBIntentService"; 

public DbIntentService() { 
    super(DbIntentService.class.getSimpleName()); 
    Log.d(TAG, "Start thread : " + Thread.currentThread().getName()); 
    db = new DbAdapter(this); 
} 

@Override 
protected void onHandleIntent(Intent intent) { 
    Log.d(TAG, "onHandleIntent()"); 

    int resultCode; 
    mIntent = intent; 

//  Open connection with DB 
    Log.d(TAG, "Opening database.."); 
    db.open(); 

//  Proceed request to the database 
    resultCode = proceedRequest(mIntent.getAction()); 

//  Close connection with DB 
    Log.d(TAG, "Closing database.."); 
    db.close(); 

//  Sending result back to an Activity 
    Log.d(TAG, "Sending result back to an activity.."); 
    sendResult(resultCode, data); 
} 


private int proceedRequest(String action){ 
    switch (action){ 
     case ACTION_IS_CURRENT_DAY: 
      return isCurrentDay(); 
     case ACTION_GET_DAY_DATA : 
      return getCurrentDayData(); 
     case ACTION_GET_WEEK_DATA : 
      return getCurrentWeekData(); 
    } 
    throw new IllegalArgumentException(); 
} 

/* Get the data for the current week */ 
private int getCurrentWeekData(){ 
    Log.d(TAG, "Getting data for the week.."); 

    Cursor rows = db.getCurWeekRows(); 

    int rowsCount = rows.getCount(); 
    Bundle weekData = new Bundle(); 

    int count = 0; 
    weekData.putInt(AppConstants.EXTRAS_DB_ROWS_COUNT, rowsCount); 

    if(rows.moveToFirst()){ 
     do { 
      weekData.putString(AppConstants.EXTRAS_DB_DATE + count, rows.getString(0)); 
      weekData.putLong(AppConstants.EXTRAS_DB_AMOUNT + count, rows.getLong(1)); 
      weekData.putDouble(AppConstants.EXTRAS_DB_DRUNK + count, rows.getDouble(2)); 

      Log.d(TAG, "ROW [" + count + "] date : " + rows.getString(0) + " amount : " + rows.getLong(1) + " drink : "+ rows.getDouble(2)); 

      count++; 
     } 
     while(rows.moveToNext()); 
    } 

    data = weekData; 
    return AppConstants.RESULT_CURRENT_WEEK; 
} 

private void sendResult(int resultCode, Bundle data){ 
    ResultReceiver resultReceiver = mIntent.getParcelableExtra(AppConstants.EXTRAS_INTENT_RESULT); 
    if(resultReceiver != null) { 
     resultReceiver.send(resultCode, data); 
    } 
} 
} 
ここ

は、私はそれをやっている方法の例であります
関連する問題