Хотите улучшить этот вопрос? Обновите вопрос так, чтобы он вписывался в тематику Stack Overflow на русском.
Закрыт 1 год назад.
Пожалуйста помогите! 3 день не могу понять причину)
CreatePost - здесь изображения отправляются в FireBase и добавляются в data класс Upload.
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.MimeTypeMap;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatEditText;
import com.bumptech.glide.Glide;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.StorageTask;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class CreatePost extends AppCompatActivity {
@BindView(R.id.for_all)
TextView all;
@BindView(R.id.for_first)
TextView first;
@BindView(R.id.for_second)
TextView second;
@BindView(R.id.for_third)
TextView third;
@BindView(R.id.for_fourth)
TextView fourth;
@BindView(R.id.mini)
ImageView mini;
@BindView(R.id.appCompatEditText)
AppCompatEditText text;
private Uri mImageUri;
private StorageReference storage;
private DatabaseReference data;
private String choose;
private StorageTask mUploadTask;
String uploadId;
Upload upload;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_post);
ButterKnife.bind(this);
TeacherFeed teacherFeed = new TeacherFeed();
teacherFeed.UnderlineSettings(all, first, second, third, fourth);
storage = FirebaseStorage.getInstance().getReference("uploads");
data = FirebaseDatabase.getInstance().getReference("uploads");
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == RESULT_OK && data.getData() != null && data != null){
mImageUri = data.getData();
//Picasso.get().load(mImageUri).into(mini);
Glide.with(this).load(mImageUri).into(mini);
mini.setImageURI(mImageUri);
}
}
@OnClick(R.id.image_select)
public void OpenGallery(){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 1);
}
@OnClick(R.id.info_help)
public void Help(){
new CustomBottomHelperGroup().show(getSupportFragmentManager(),"Dialog");
}
@OnClick(R.id.close_post)
public void ClosePostCreater(){
finish();
}
@OnClick(R.id.add_post)
public void AddPost(){
Upload();
finish();
}
@OnClick(R.id.for_all)
public void FilterAll(){
choose = "0";
}
@OnClick(R.id.for_first)
public void FilterFirst(){
choose = "1";
}
@OnClick(R.id.for_second)
public void FilterSecond(){
choose = "2";
}
@OnClick(R.id.for_third)
public void FilterThird(){
choose = "3";
}
@OnClick(R.id.for_fourth)
public void FilterFourth(){
choose = "4";
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void Upload(){
if (mImageUri != null) {
StorageReference fileReference = storage.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
mUploadTask = fileReference.putFile(mImageUri).addOnSuccessListener(taskSnapshot -> {
upload = new Upload(text.getText().toString().trim(),
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString());
uploadId = data.push().getKey();
data.child(uploadId).setValue(upload);
}).addOnFailureListener(e -> Toast.makeText(this, "error", Toast.LENGTH_SHORT).show());
} else {
Toast.makeText(this, "Не выбрано фото!", Toast.LENGTH_SHORT).show();
}
}
}
RecyclerAdapter - отображает посты из базы данных FireBase
class RecyclerAdapter(private val context: Context, private val data: List<Upload>): RecyclerView.Adapter<RecyclerAdapter.ViewHolder>() {
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val uploadCurrent = data[position]
holder.mainText.text = uploadCurrent.name
//Picasso.get().load(data[position].imageUrl).fit().centerCrop().placeholder(R.mipmap.ic_launch).into(holder.imageFeed)
Glide.with(context).load(uploadCurrent.imageUrl).placeholder(R.drawable.scedule).centerCrop().into(holder.imageFeed)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.recycler_content, parent, false)
return ViewHolder(view)
}
override fun getItemCount() = data.size
class ViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
val mainText: AppCompatTextView = view.findViewById(R.id.MainText)
val imageFeed: ImageView = view.findViewById(R.id.ImageFeed)
}
}
AdministratorFeed - добавляет в список посты и отображает их
public class AdministratorFeed extends AppCompatActivity {
@BindView(R.id.all_post)
TextView all;
@BindView(R.id.first_post)
TextView first;
@BindView(R.id.second_post)
TextView second;
@BindView(R.id.third_post)
TextView third;
@BindView(R.id.fourth_post)
TextView fourth;
@BindView(R.id.toolbar)
Toolbar toolbar;
int check = 0;
int like_count;
AlertDialog.Builder ad;
boolean mode = false;
int num = 0;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
String MODE = "MODE";
private RecyclerView recyclerView;
private DatabaseReference databaseReference;
private List<Upload> uploads;
private Upload upload;
private RecyclerAdapter adapter;
private ArrayList<Upload> list;
private FirebaseStorage mStorage;
private DatabaseReference mDatabaseRef;
private ValueEventListener mDBListener;
@Override
public void onBackPressed() {
ad.show();
}
@Override
public boolean onCreateOptionsMenu (Menu menu){
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected (MenuItem item){
switch (item.getItemId()) {
case R.id.dark_theme:
if(num == 0){
sharedPreferences = getSharedPreferences(MODE, MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putBoolean("MODE", mode = true);
editor.apply();
Handler handler = new Handler();
handler.postDelayed(() -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES), 1000);
num++;
}else{
sharedPreferences = getSharedPreferences(MODE, MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putBoolean("MODE", mode = false);
editor.apply();
Handler handler = new Handler();
handler.postDelayed(() -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO), 1000);
num--;
}
break;
case R.id.error:
new BottomError().show(getSupportFragmentManager(),"Dialog");
break;
case R.id.about:
Intent intent = new Intent(this, AboutApp.class);
startActivity(intent);
break;
}
return true;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_administrator_feed);
ButterKnife.bind(this);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
toolbar.setTitle(" ");
setSupportActionBar(toolbar);
showDialog();
list = new ArrayList<>();
recyclerView = findViewById(R.id.recycler);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
SharedPreferences sharedPreferences = getSharedPreferences(MODE, MODE_PRIVATE);
mode = sharedPreferences.getBoolean(MODE, mode);
adapter = new RecyclerAdapter(AdministratorFeed.this, list);
recyclerView.setAdapter(adapter);
mStorage = FirebaseStorage.getInstance();
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
if(mode){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}else{
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
TeacherFeed teacherFeed = new TeacherFeed();
teacherFeed.UnderlineSettings(all, first, second, third, fourth);
mDBListener = mDatabaseRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
list.clear();
for(DataSnapshot snapshot: dataSnapshot.getChildren()){
Upload upload = snapshot.getValue(Upload.class);
list.add(upload);
}
adapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
Upload - data класс
public class Upload {
private String mName;
private String mImageUrl;
public Upload() {
}
public Upload(String name, String imageUrl) {
if (name.trim().equals("")) {
name = "No Name";
}
mName = name;
mImageUrl = imageUrl;
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public String getImageUrl() {
return mImageUrl;
}
public void setImageUrl(String imageUrl) {
mImageUrl = imageUrl;
}
}
Лог ошибок:
W/Glide: Load failed for com.google.android.gms.tasks.zzu@76e2bd2 with size [640x339]
class com.bumptech.glide.load.engine.GlideException: Failed to load resource
There were 3 causes:
java.io.FileNotFoundException(/com.google.android.gms.tasks.zzu@76e2bd2 (No such file or directory))
java.io.FileNotFoundException(open failed: ENOENT (No such file or directory))
java.io.FileNotFoundException(open failed: ENOENT (No such file or directory))
call GlideException#logRootCauses(String) for more detail
Cause (1 of 3): class com.bumptech.glide.load.engine.GlideException: Fetching data failed, class java.io.InputStream, LOCAL
There was 1 cause:
java.io.FileNotFoundException(/com.google.android.gms.tasks.zzu@76e2bd2 (No such file or directory))
call GlideException#logRootCauses(String) for more detail
Cause (1 of 1): class com.bumptech.glide.load.engine.GlideException: Fetch failed
There was 1 cause:
java.io.FileNotFoundException(/com.google.android.gms.tasks.zzu@76e2bd2 (No such file or directory))
call GlideException#logRootCauses(String) for more detail
Cause (1 of 1): class java.io.FileNotFoundException: /com.google.android.gms.tasks.zzu@76e2bd2 (No such file or directory)
Cause (2 of 3): class com.bumptech.glide.load.engine.GlideException: Fetching data failed, class android.os.ParcelFileDescriptor, LOCAL
There was 1 cause:
java.io.FileNotFoundException(open failed: ENOENT (No such file or directory))
call GlideException#logRootCauses(String) for more detail
Cause (1 of 1): class com.bumptech.glide.load.engine.GlideException: Fetch failed
There was 1 cause:
java.io.FileNotFoundException(open failed: ENOENT (No such file or directory))
call GlideException#logRootCauses(String) for more detail
Cause (1 of 1): class java.io.FileNotFoundException: open failed: ENOENT (No such file or directory)
Cause (3 of 3): class com.bumptech.glide.load.engine.GlideException: Fetching data failed, class android.content.res.AssetFileDescriptor, LOCAL
There was 1 cause:
java.io.FileNotFoundException(open failed: ENOENT (No such file or directory))
call GlideException#logRootCauses(String) for more detail
Cause (1 of 1): class java.io.FileNotFoundException: open failed: ENOENT (No such file or directory)
I/Glide: Root cause (1 of 3)
java.io.FileNotFoundException: /com.google.android.gms.tasks.zzu@76e2bd2 (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:200)
at java.io.FileInputStream.<init>(FileInputStream.java:150)
at java.io.FileInputStream.<init>(FileInputStream.java:103)
at android.content.ContentResolver.openInputStream(ContentResolver.java:971)
at com.bumptech.glide.load.data.StreamLocalUriFetcher.loadResourceFromUri(StreamLocalUriFetcher.java:74)
at com.bumptech.glide.load.data.StreamLocalUriFetcher.loadResource(StreamLocalUriFetcher.java:50)
at com.bumptech.glide.load.data.StreamLocalUriFetcher.loadResource(StreamLocalUriFetcher.java:13)
at com.bumptech.glide.load.data.LocalUriFetcher.loadData(LocalUriFetcher.java:44)
at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.loadData(MultiModelLoader.java:100)
at com.bumptech.glide.load.engine.SourceGenerator.startNext(SourceGenerator.java:63)
at com.bumptech.glide.load.engine.DecodeJob.runGenerators(DecodeJob.java:310)
at com.bumptech.glide.load.engine.DecodeJob.runWrapped(DecodeJob.java:279)
at com.bumptech.glide.load.engine.DecodeJob.run(DecodeJob.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
at com.bumptech.glide.load.engine.executor.GlideExecutor$DefaultThreadFactory$1.run(GlideExecutor.java:431)
I/Glide: Root cause (2 of 3)
java.io.FileNotFoundException: open failed: ENOENT (No such file or directory)
at android.os.ParcelFileDescriptor.openInternal(ParcelFileDescriptor.java:313)
at android.os.ParcelFileDescriptor.open(ParcelFileDescriptor.java:211)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1248)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1176)
at com.bumptech.glide.load.data.FileDescriptorLocalUriFetcher.loadResource(FileDescriptorLocalUriFetcher.java:20)
at com.bumptech.glide.load.data.FileDescriptorLocalUriFetcher.loadResource(FileDescriptorLocalUriFetcher.java:12)
at com.bumptech.glide.load.data.LocalUriFetcher.loadData(LocalUriFetcher.java:44)
at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.loadData(MultiModelLoader.java:100)
at com.bumptech.glide.load.engine.SourceGenerator.startNext(SourceGenerator.java:63)
at com.bumptech.glide.load.engine.DecodeJob.runGenerators(DecodeJob.java:310)
at com.bumptech.glide.load.engine.DecodeJob.onDataFetcherFailed(DecodeJob.java:408)
at com.bumptech.glide.load.engine.SourceGenerator.onLoadFailed(SourceGenerator.java:130)
at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.startNextOrFail(MultiModelLoader.java:167)
at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.onLoadFailed(MultiModelLoader.java:154)
at com.bumptech.glide.load.data.LocalUriFetcher.loadData(LocalUriFetcher.java:49)
at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.loadData(MultiModelLoader.java:100)
at com.bumptech.glide.load.engine.SourceGenerator.startNext(SourceGenerator.java:63)
at com.bumptech.glide.load.engine.DecodeJob.runGenerators(DecodeJob.java:310)
at com.bumptech.glide.load.engine.DecodeJob.runWrapped(DecodeJob.java:279)
at com.bumptech.glide.load.engine.DecodeJob.run(DecodeJob.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
at com.bumptech.glide.load.engine.executor.GlideExecutor$DefaultThreadFactory$1.run(GlideExecutor.java:431)
I/Glide: Root cause (3 of 3)
java.io.FileNotFoundException: open failed: ENOENT (No such file or directory)
at android.os.ParcelFileDescriptor.openInternal(ParcelFileDescriptor.java:313)
at android.os.ParcelFileDescriptor.open(ParcelFileDescriptor.java:211)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1248)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1176)
at com.bumptech.glide.load.data.AssetFileDescriptorLocalUriFetcher.loadResource(AssetFileDescriptorLocalUriFetcher.java:20)
at com.bumptech.glide.load.data.AssetFileDescriptorLocalUriFetcher.loadResource(AssetFileDescriptorLocalUriFetcher.java:11)
at com.bumptech.glide.load.data.LocalUriFetcher.loadData(LocalUriFetcher.java:44)
at com.bumptech.glide.load.engine.SourceGenerator.startNext(SourceGenerator.java:63)
at com.bumptech.glide.load.engine.DecodeJob.runGenerators(DecodeJob.java:310)
at com.bumptech.glide.load.engine.DecodeJob.onDataFetcherFailed(DecodeJob.java:408)
at com.bumptech.glide.load.engine.SourceGenerator.onLoadFailed(SourceGenerator.java:130)
at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.startNextOrFail(MultiModelLoader.java:167)
at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.onLoadFailed(MultiModelLoader.java:154)
at com.bumptech.glide.load.data.LocalUriFetcher.loadData(LocalUriFetcher.java:49)
at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.loadData(MultiModelLoader.java:100)
at com.bumptech.glide.load.engine.SourceGenerator.startNext(SourceGenerator.java:63)
at com.bumptech.glide.load.engine.DecodeJob.runGenerators(DecodeJob.java:310)
at com.bumptech.glide.load.engine.DecodeJob.onDataFetcherFailed(DecodeJob.java:408)
at com.bumptech.glide.load.engine.SourceGenerator.onLoadFailed(SourceGenerator.java:130)
at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.startNextOrFail(MultiModelLoader.java:167)
at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.onLoadFailed(MultiModelLoader.java:154)
at com.bumptech.glide.load.data.LocalUriFetcher.loadData(LocalUriFetcher.java:49)
at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.loadData(MultiModelLoader.java:100)
at com.bumptech.glide.load.engine.SourceGenerator.startNext(SourceGenerator.java:63)
at com.bumptech.glide.load.engine.DecodeJob.runGenerators(DecodeJob.java:310)
at com.bumptech.glide.load.engine.DecodeJob.runWrapped(DecodeJob.java:279)
at com.bumptech.glide.load.engine.DecodeJob.run(DecodeJob.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
at com.bumptech.glide.load.engine.executor.GlideExecutor$DefaultThreadFactory$1.run(GlideExecutor.java:431)
Чтобы получить конкретное изображение можно сделать так:
lateinit var dataBase: DatabaseReference
dataBase = FirebaseDatabase.getInstance().getReference("Database").child("User1")
val listener = object :ValueEventListener{
override fun onCancelled(p0: DatabaseError) {
}
override fun onDataChange(dataSnapshot: DataSnapshot) {
val user1_image = dataSnapshot.child("user1_image").getValue().toString()
Picasso.get().load(user1_image ).into(user1_img)
}
}
dataBase.addValueEventListener(listener)
Если выводить данные в recyclerView, то нужен немного другой код.
upd: для recyclerView
// Переменные
lateinit var recyclerView: RecyclerView
lateinit var dataBase: DatabaseReference
lateinit var layout: LinearLayoutManager
// Загрузка данных с локального хранилища, если нет доступа к сети.
// FirebaseDatabase.getInstance().setPersistenceEnabled(true)
dataBase = FirebaseDatabase.getInstance().getReference("Database")
recyclerView = findViewById<RecyclerView>(R.id.recyclerview)
layout = LinearLayoutManager(context)
recyclerView.layoutManager = layout
// Основной метод
firebaseData()
fun firebaseData() {
// Настройки. Этот вариант выводит все данные сразу. Есть еще немного другой вариант, который выводит конкретное кол-во значений в recyclerView и при прокрутке подгружает следующие элементы.
val options = FirebaseRecyclerOptions.Builder<Model>()
.setLifecycleOwner(this)
.setQuery(dataBase, Model::class.java)
.build()
val firebaseRecyclerAdapter =
object : FirebaseRecyclerAdapter<Model, CurrentNewsViewHolder>(options) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CurrentViewHolder {
val itemView = LayoutInflater.from(baseContext).inflate(R.layout.item, parent, false)
return CurrentViewHolder(itemView)
}
override fun onBindViewHolder(p0: CurrentViewHolder, p1: Int, p2: Model) {
dataBase.child(id).addValueEventListener(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
toast("Error")
}
override fun onDataChange(p: DataSnapshot) {
// Работа с элементами. p2 - это значения, которые мы получаем с БД. p0 - это значения, которые мы изменяем. К прмиеру p0.text.setText(p2.text).
}
})
}
}
recyclerView.adapter = firebaseRecyclerAdapter
firebaseRecyclerAdapter.startListening()
}
// Тут пишем все элементы xml файла.
class CurrentViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val view = itemView
val text1:TextView = itemView.find(R.id.text1)
}
// Модель данных. Если у Вас в БД есть поле text1, значит в моделе должна быть переменная text1. Регистр учитывается. Также, если у Вас String формат переменной, а в БД эта переменная со значением без " ", то будет ошибка.
class Model_for_Current_News {
var text1: String? = null
constructor() {
}
constructor(
text1: String?
) {
this.text1 = text1
}
}
Айфон мало держит заряд, разбираемся с проблемой вместе с AppLab
Как в log4jxml изменять название файла, куда будут сохраняться логи, во время программы?
Цель: Правильно прописать путь в applicationproperties для возможности отправки данных в базу данных MS SQL
Есть таблица в которой есть номер лота и ценаУсловие: нужно собрать цену из той строки таблицы где есть номер ЕИС
Я получаю от php-сервера запрос на обработку данных, которые в формате json хранятся в body, как я могу достать именно эту json-строчку из request Post-запроса?