Я использую оболочку для диалога под названием LovelyDialog, которая позволяет настраивать диалог. Я пытаюсь ввести пользовательский ввод из этого диалогового окна и передать его sh в мою базу данных Firebase Realtime. В проекте нет ошибок времени выполнения, но данные не записываются в базу данных. Нет проблем, когда я жестко кодирую строки и передаю их в базу данных, это происходит только тогда, когда я имею дело с EditTexts и макетом, как мне кажется. Для обоих моих правил установлено значение true.
В базу данных загружается только пустая строка, например эта "". Я думаю, что это может иметь какое-то отношение к тому, как я раздуваю свое мнение, но я не уверен, и я исчерпал все возможные решения. Я новичок в Android Studio.
Вот моя база данных:
введите описание изображения здесь
Вот моя основная деятельность
public class MainActivity extends AppCompatActivity {
private String mUsername;
private String mPhotoUrl;
private SharedPreferences mSharedPreferences;
private GoogleSignInClient mSignInClient;
private static final String MESSAGE_URL = "http://pantryapp.firebase.google.com/message/";
public static final String ANONYMOUS = "anonymous";
public static final String FOODS_CHILD = "Pantry2";
private DrawerLayout mDrawerLayout;
private EditText mName, mQuantity, mLifecycle;
// Firebase instance variables
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;
private DatabaseReference mFirebaseDatabaseReference;
FirebaseDatabase database = FirebaseDatabase.getInstance();
private DatabaseReference mRef = database.getReference("foods");
// private FirebaseRecyclerAdapter<Cheeses, CheeseListFragment.SimpleStringRecyclerViewAdapter.ViewHolder> mFirebaseAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//remove below if it breaks
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
// Set default username as anonymous.
mUsername = ANONYMOUS;
// Initialize Firebase Auth
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
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();
}
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
//new child entries
mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
if (viewPager != null) {
setupViewPager(viewPager);
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
//menu version
// final PopupMenu menu = new PopupMenu(this, fab);
// menu.getMenu().add("Add Item To Pantry Inventory");
// menu.getMenu().add("Add Item To Grocery List");
// menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){
// public boolean onMenuItemClick(MenuItem item){
// Log.d("menu title: ", item.getTitle().toString());
// return true;
// }
// });
fab.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
showEditDialog();
}
});
//old version
// fab.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// Snackbar.make(view, "Add a ", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
// }
// });
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void showEditDialog(){
final Context context = this;
final LovelyCustomDialog mDialog = new LovelyCustomDialog(context);
mDialog.setView(R.layout.item_donate_option);
mDialog.setTopColorRes(R.color.PINK);
mDialog.setTitle(R.string.text_input_title);
// .setMessage(R.string.text_input_message)
mDialog.setIcon(R.drawable.ic_forum);
mDialog.show();
mDialog.setListener(R.id.ld_btn_confirm, new View.OnClickListener() {
@Override
public void onClick(View view) {
final View v = getLayoutInflater().inflate(R.layout.item_donate_option, null);
final EditText name =(EditText) v.findViewById(R.id.item_name);
final EditText quantity = (EditText) v.findViewById(R.id.item_quantity);
final EditText lifecycle = (EditText) v.findViewById(R.id.item_lifecycle);
String mName = name.getText().toString();
String mQuantity = quantity.getText().toString();
String mLifecycle = lifecycle.getText().toString();
String id = "1";
// DatabaseReference postsRef = mRef.child("posts");
//
// DatabaseReference newPostRef = postsRef.push();
// newPostRef.setValueAsync(new Foods("gracehop", "Announcing COBOL, a New Programming Language", "adf"));
//// We can also chain the two calls together
// postsRef.push().setValueAsync(new Foods("alanisawesome", "The Turing Machine", "yes"));
//
Foods food = new Foods(mName, mQuantity, mLifecycle);
// FirebaseDatabase.getInstance().getReference("Pantry")
// .child(name.getText().toString())
// .setValue(new Foods(name.getText().toString(), quantity.getText().toString(), lifecycle.getText().toString()));
//
////
DatabaseReference foodRef = mRef.child("Pantry");
DatabaseReference newFoodRef = foodRef.push();
newFoodRef.setValue(food);
mRef.child("Pantry").setValue(food);
Snackbar.make(view, "Added a " + food.getmName(), Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
//writeNewFood(mName, mQuantity, mLifecycle);
// Cheeses foods = new Cheeses(name, quantity, lifecycle);
//// mRef.setValue(name);
// mRef.child("foods").child(name).setValue(foods);
// mName.setText("");
// mQuantity.setText("");
// mLifecycle.setText("");
// result.setText
// mRef.setValue(name);
mDialog.dismiss();
}
});
// .configureView(new LovelyCustomDialog.ViewConfigurator(){
// @Override
// public void configureView(View v){
//
// }
// })
// .configureView(/* ... */)
// .setListener(R.id.ld_btn_yes, /* ... */)
// .setInstanceStateManager(/* ... */)
// .setListener(R.id.btn_confirm, new View.OnClickListener(){
// @Override
// public void onClick(View view) {
// mEdit = (EditText)findViewById(R.id.item_name);
// Log.v("EditText", mEdit.getText().toString());
// }
// })
}
public void writeNewFood(String name, String quantity, String lifecycle) {
Foods foods = new Foods(name, quantity, lifecycle);
mRef.child(name).setValue(foods);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.sample_actions, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
switch (AppCompatDelegate.getDefaultNightMode()) {
case AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM:
menu.findItem(R.id.menu_night_mode_system).setChecked(true);
break;
case AppCompatDelegate.MODE_NIGHT_AUTO:
menu.findItem(R.id.menu_night_mode_auto).setChecked(true);
break;
case AppCompatDelegate.MODE_NIGHT_YES:
menu.findItem(R.id.menu_night_mode_night).setChecked(true);
break;
case AppCompatDelegate.MODE_NIGHT_NO:
menu.findItem(R.id.menu_night_mode_day).setChecked(true);
break;
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.sign_out_menu:
mFirebaseAuth.signOut();
mSignInClient.signOut();
mUsername = ANONYMOUS;
startActivity(new Intent(this, SignInActivity.class));
finish();
return true;
default:
return super.onOptionsItemSelected(item);
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
case R.id.menu_night_mode_system:
setNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
break;
case R.id.menu_night_mode_day:
setNightMode(AppCompatDelegate.MODE_NIGHT_NO);
break;
case R.id.menu_night_mode_night:
setNightMode(AppCompatDelegate.MODE_NIGHT_YES);
break;
case R.id.menu_night_mode_auto:
setNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
break;
}
return super.onOptionsItemSelected(item);
}
Вот мой макет для R.layout.item_donate_option
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="@layout/view_color_area" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Space
android:layout_width="wrap_content"
android:layout_height="12dp" />
<include layout="@layout/view_title_and_message" />
<EditText
android:id="@+id/item_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ems="20"
android:hint="@string/food_name"
android:padding="22dp" />
<EditText
android:id="@+id/item_quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ems="20"
android:hint="@string/item_quantity"
android:padding="22dp" />
<EditText
android:id="@+id/item_lifecycle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ems="20"
android:hint="@string/item_lifecycle_in_days"
android:padding="22dp" />
<!-- <TextView-->
<!-- android:id="@+id/ld_error_message"-->
<!-- android:layout_width="wrap_content"-->
<!-- android:layout_height="wrap_content"-->
<!-- android:layout_marginLeft="@dimen/ld_side_margin"-->
<!-- android:layout_marginRight="@dimen/ld_side_margin"-->
<!-- android:textColor="@color/ld_textInputError"-->
<!-- android:visibility="gone" />-->
<Space
android:layout_width="wrap_content"
android:layout_height="8dp" />
</LinearLayout>
</ScrollView>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:orientation="horizontal">
<TextView
android:id="@+id/ld_btn_confirm"
style="@style/DialogButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="@android:string/ok"/>
</LinearLayout>
</LinearLayout>
А вот моя модель.
public class Foods {
private String name;
private String lifecycle; //in days
private String quantity;
public Foods(){
}
public Foods(String name, String quantity, String lifecycle){
this.name = name;
this.quantity = quantity;
this.lifecycle = lifecycle;
}
public String getmName() {
return name;
}
public void setmName(String name) {
this.name = name;
}
public String getmLifecycle() {
return lifecycle;
}
public void setmLifecycle(String mLifecycle) {
this.lifecycle = mLifecycle;
}
public String getmQuantity() {
return quantity;
}
public void setmQuantity(String mQuantity) {
this.quantity = mQuantity;
}
private static final Random RANDOM = new Random();
public static int getRandFoodImage() {
switch (RANDOM.nextInt(13)) {
default:
case 0:
return R.drawable.foods_1;
case 1:
return R.drawable.foods_2;
case 2:
return R.drawable.foods_3;
case 3:
return R.drawable.foods_4;
case 4:
return R.drawable.foods_5;
case 5:
return R.drawable.foods_6;
case 6:
return R.drawable.foods_7;
case 7:
return R.drawable.foods_8;
case 8:
return R.drawable.foods_9;
case 9:
return R.drawable.foods_10;
case 10:
return R.drawable.foods_11;
case 11:
return R.drawable.foods_12;
case 12:
return R.drawable.foods_13;
case 13:
return R.drawable.foods_14;
}
}
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("Pantry");
DatabaseReference mRef = ref.child("Food Items");
@Exclude
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("name", name);
result.put("quantity", quantity);
result.put("lifecycle", lifecycle);
return result;
}
Мне просто нужно выяснить, почему мой ввод мой диалог не попадает в базу данных, а вместо этого просто вставляет пустые строки, подобные этой "". Я сделал что-то не так, когда раздул свое мнение? Нужно ли мне расширять представление И макет для доступа к моему R.id.item_name, R.id.item_quantity и т. Д.?