Я получаю сообщение об ошибке:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable com.rengwuxian.materialedittext.MaterialEditText.getText()' on a null object reference
at com.example.batangasbeachhousesfinalserver.HomeFragment$16$1.onSuccess(HomeFragment.java:318)
at com.example.batangasbeachhousesfinalserver.HomeFragment$16$1.onSuccess(HomeFragment.java:312)
at com.google.android.gms.tasks.zzn.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6816)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1567)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1455)
Я обновил код * не могу добавить в него никаких деталей. ниже приведен код onCreateView и код загрузки в мою базу данных. Пожалуйста, помогите очень нужно для моего проекта. Я пытался искать другие решения, которые на самом деле не работают.
Вот код в домашнем фрагменте:
imageFolder.putFile(saveUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mDialog.dismiss();
Toast.makeText(getActivity(), "Uploaded", Toast.LENGTH_SHORT).show();
imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
newBeach = new Beach();
newBeach.setDescription(beach_description.getText().toString());
newBeach.setImage(uri.toString());
newBeach.setName(beach_name.getText().toString());
newBeach.setPrice(beach_price.getText().toString());
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
mDialog.dismiss();
Toast.makeText(getActivity(),""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
mDialog.setMessage("Uploaded " + progress + "%");
}
});
Вот onCreateView:
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
getActivity().setTitle("HOME");
homeView= inflater.inflate(R.layout.fragment_home, container, false);
recycler_menu = (RecyclerView)homeView.findViewById(R.id.recycler_menu);
recycler_menu.setLayoutManager(new LinearLayoutManager(getContext()));
database = FirebaseDatabase.getInstance();
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
beach =database.getReference("Beach Houses");
cottages =database.getReference("Cottages");
bigvenues =database.getReference("Big Venues");
glamping =database.getReference("Glamping");
beachHouseBTN = (Button) homeView.findViewById(R.id.beachHouseBTN);
beachHouseBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
menuID.equals("01");
loadMenuBeach();
}
});
cottagesBTN = (Button) homeView.findViewById(R.id.cottagesBTN);
cottagesBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
menuID.equals("02");
loadMenuCottages();
}
});
bigVenuesBTN = (Button) homeView.findViewById(R.id.bigVenuesBTN);
bigVenuesBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
menuID.equals("03");
loadMenuBigVenues();
}
});
return homeView;
}
add_new_item_layout.xml:
<?xml version = "1.0" encoding = "utf-8"?>
<android.support.v7.widget.CardView
xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:fbutton = "http://schemas.android.com/apk/res-auto"
android:orientation = "vertical"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
app:cardElevation = "4dp">
<LinearLayout
android:layout_margin = "20dp"
android:orientation = "vertical"
android:layout_width = "match_parent"
android:layout_height = "wrap_content">
<com.rengwuxian.materialedittext.MaterialEditText
android:id = "@+id/beach_item"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:hint = "name"
android:text = ""
android:textColor = "@color/colorPrimary"
android:textColorHint = "@color/colorPrimary"
android:textSize = "18sp"
app:met_baseColor = "@color/colorPrimary"
app:met_floatingLabel = "highlight"
app:met_primaryColor = "@color/colorPrimary"
app:met_singleLineEllipsis = "true" />
<com.rengwuxian.materialedittext.MaterialEditText
android:id = "@+id/beach_description"
android:layout_width = "match_parent"
android:layout_height = "250dp"
android:gravity = "fill_horizontal"
android:hint = "description"
android:inputType = "textMultiLine"
android:text = ""
android:textColor = "@color/colorPrimary"
android:textColorHint = "@color/colorPrimary"
android:textSize = "18sp"
app:met_baseColor = "@color/colorPrimary"
app:met_floatingLabel = "highlight"
app:met_primaryColor = "@color/colorPrimary"
app:met_singleLineEllipsis = "true" />
<com.rengwuxian.materialedittext.MaterialEditText
android:id = "@+id/beach_price"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:hint = "price"
android:inputType = "number"
android:text = ""
android:textColor = "@color/colorPrimary"
android:textColorHint = "@color/colorPrimary"
android:textSize = "18sp"
app:met_baseColor = "@color/colorPrimary"
app:met_floatingLabel = "highlight"
app:met_primaryColor = "@color/colorPrimary"
app:met_singleLineEllipsis = "true" />
<LinearLayout
android:weightSum = "2"
android:orientation = "horizontal"
android:layout_width = "match_parent"
android:layout_height = "wrap_content">
<Button
android:id = "@+id/btnSelect"
android:text = "SELECT"
android:textColor = "@android:color/white"
android:layout_marginRight = "8dp"
android:layout_marginLeft = "8dp"
android:layout_alignParentBottom = "true"
android:layout_height = "wrap_content"
android:layout_width = "0dp"
android:layout_weight = "1"
android:layout_margin = "8dp"
/>
<Button
android:id = "@+id/btnUpload"
android:text = "UPLOAD"
android:textColor = "@android:color/white"
android:layout_marginRight = "8dp"
android:layout_marginLeft = "8dp"
android:layout_alignParentBottom = "true"
android:layout_height = "wrap_content"
android:layout_width = "0dp"
android:layout_weight = "1"
android:layout_margin = "8dp"
/>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
HomeFragment расширяет фрагмент:
public class HomeFragment extends Fragment
{
private View homeView;
private RecyclerView recycler_menu;
Button beachHouseBTN, cottagesBTN, bigVenuesBTN, glampingBTN;
String menuID = "";
FirebaseDatabase database;
FirebaseStorage storage;
StorageReference storageReference;
DatabaseReference beach, glamping, bigvenues, cottages;
FirebaseRecyclerAdapter<Beach, MenuViewHolder> adapter1;
FirebaseRecyclerAdapter<Cottages, MenuViewHolder> adapter2;
FirebaseRecyclerAdapter<BigVenues, MenuViewHolder> adapter3;
FirebaseRecyclerAdapter<Glamping, MenuViewHolder> adapter4;
//Add New Item Layout
MaterialEditText beach_name, beach_description, beach_price;
Button btnSelect, btnUpload;
FloatingActionButton fab;
Beach newBeach;
Cottages newCottage;
BigVenues newBigVenues;
Uri saveUri;
DrawerLayout drawer;
}
У меня есть add_new_item.xml с описанием пляжа. также у меня есть один на модели Beach.java.
на модели Beach.java: public Beach () { } public Beach (описание строки, изображение строки, имя строки, цена строки) { this.description = описание; это.изображение = изображение; это.имя = имя; эта.цена = цена; }
Не думайте, что ошибка исходит от модели, если это не та строка, на которую вас направляет трассировка стека? Не могу сказать, только прочитав ваш пост. Я чувствую, что могу исходить из несоответствия между вашими идентификаторами или какой-то проблемы с инициализацией вашего представления, но мне нужно, чтобы вы опубликовали свой метод onCreate и макет, чтобы быть уверенным.
открытый класс HomeFragment расширяет фрагмент { MaterialEditText beach_name, beach_description, beach_price; Кнопка btnSelect, btnUpload; }
add_new_layout.xml. У меня есть MaterialEditText с такими идентификаторами, как beach_item, beach_description и beach_price.
Я обновил свой пост. проверьте код. :)
Спасибо. Мне нужно посмотреть, где вы инициируете эти переменные, пожалуйста? Ваш полный onCreate, если вы можете обновить свой код с помощью этого? Я считаю, что проблема именно в этом.
Я снова обновил пост
Как сказал @FrancislainyCampos, обычно это происходит потому, что вы не привязываете представление к своему фрагменту.
Почему вы удалили свой xml? Нам нужно сравнить его с вашим onCreate..
я положил его обратно
Спасибо. Да, это то, что происходит. Вы не инициируете переменную beach_description
что значит я не инициирую? В HomeFragment расширяет фрагмент, где я его фактически объявил. Я не смогу вызвать его, когда я объявлю его внутри onCreateView
Вы не привязываете идентификатор представления к переменной
Возможный дубликат Что такое исключение NullPointerException и как его исправить?
Переменная описания пляжа не запускается внутри вашего onCreate.
Вам нужно иметь что-то вроде
MaterialEditText beach_description = (MaterialEditText) getActivity().findViewByID(R.id.beach_description);
И это должно решить вашу проблему.
MaterialEditText beach_name = (MaterialEditText) getActivity().findViewById(R.id.beach_name); дает мне ошибку неожиданного приведения к MaterialEditText
Что ж, нулевая ошибка решена. Что еще говорит вам трассировка стека?
У меня нет ошибок в этих двух: MaterialEditText beach_description = (MaterialEditText) getActivity().findViewById(R.id.beach_description); MaterialEditText beach_price = (MaterialEditText) getActivity().findViewById(R.id.beach_price); но не будет работать с MaterialEditText beach_name = (MaterialEditText) getActivity().findViewById(R.id.beach_name); дает мне ошибку неожиданного приведения к MaterialEditText, почему это так? когда декларация все равно?
Неожиданное приведение к MaterialEditText: тег макета был TextView (идентификатор привязан к TextView в activity_details.xml)
Я новичок в этом деле. так что мне немного жаль, что я не понимаю большую часть этого
Это нормально. Я просто думаю, что, возможно, стоит посмотреть несколько руководств по привязке представлений к макетам и тому, как использовать фрагменты. Я не знаю, почему ваша ошибка говорит о текстовом представлении в activity_details.xml, если вы используете макет fragment_home, но затем вы опубликовали здесь как add_new_item_layout.xml. Если мы не знаем точно, как называется макет, который вы используете, может быть немного сложно оказать большую помощь.
Привет, где вы инициализируете beach_description, пожалуйста, поскольку я считаю, что проблема может исходить из этого? Этот идентификатор исходит из раздутого макета?