Image 向Firebase添加图像

Image 向Firebase添加图像,image,listview,firebase-storage,Image,Listview,Firebase Storage,我有一个firebase数据库,用户可以在其中添加名称和描述。然后,名称和说明将显示在列表视图中。我想添加第三个元素,用户可以在其中添加照片并在图像视图中显示。 我不知道如何在firebase中添加照片,有人能帮我吗 以下是我到目前为止的情况: 我的模型课:(我应该在这里添加图像吗?) 我的listview类 public class RecipeList extends ArrayAdapter<Recipe> { private Activity context;

我有一个firebase数据库,用户可以在其中添加名称和描述。然后,名称和说明将显示在列表视图中。我想添加第三个元素,用户可以在其中添加照片并在图像视图中显示。 我不知道如何在firebase中添加照片,有人能帮我吗

以下是我到目前为止的情况:

我的模型课:(我应该在这里添加图像吗?)

我的listview类

public class RecipeList extends ArrayAdapter<Recipe> {
    private Activity context;
    List<Recipe> recipes;

public RecipeList(Activity context, List<Recipe> recipes) {
    super(context, R.layout.layout_recipe_list, recipes);
    this.context = context;
    this.recipes = recipes;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();
    View listViewItem = inflater.inflate(R.layout.layout_recipe_list, null, true);

    TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
    TextView textViewDescription = (TextView) listViewItem.findViewById(R.id.textViewDescription);

    Recipe recipe = recipes.get(position);
    textViewName.setText(recipe.getRecipeName());
    textViewDescription.setText(recipe.getRecipeDescription());

    return listViewItem;
}
公共类RecipeList扩展了ArrayAdapter{
私人活动语境;
列出食谱;
公共RecipeList(活动上下文、食谱列表){
超级(上下文,R.layout.layout\u配方列表,配方);
this.context=上下文;
这个。菜谱=菜谱;
}
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图){
LayoutInflater充气器=上下文。getLayoutInflater();
View listViewItem=充气机。充气(R.layout.layout\u配方\u列表,null,true);
TextView textViewName=(TextView)listViewItem.findViewById(R.id.textViewName);
TextView textViewDescription=(TextView)listViewItem.findViewById(R.id.textViewDescription);
配方=配方。获取(位置);
textViewName.setText(recipe.getRecipeName());
textViewDescription.setText(recipe.getRecipeDescription());
返回listViewItem;
}
}

我想上传图片的主要片段

public class AddRecipeFragment extends Fragment {

//we will use these constants later to pass the artist name and id to another activity
public static final String RECIPE_NAME = "net.simplifiedcoding.firebasedatabaseexample.artistname";
public static final String RECIPE_ID = "net.simplifiedcoding.firebasedatabaseexample.artistid";

//view objects
EditText editTextName;
EditText editTextDescription;
Button buttonAddRecipe;
ListView listViewRecipes;

ProgressBar progressBar;


FirebaseAuth mAuth;


//a list to store all the foods from firebase database
List<Recipe> recipes;

//our database reference object
DatabaseReference databaseRecipes;


public AddRecipeFragment() {
    // Required empty public constructor
}

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment AddRecipeFragment.
 */
// TODO: Rename and change types and number of parameters
public static AddRecipeFragment newInstance(String param1, String param2) {
    AddRecipeFragment fragment = new AddRecipeFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }


    //getting the reference of artists node
    databaseRecipes = FirebaseDatabase.getInstance().getReference("recipes");


    databaseRecipes.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            //clearing the previous artist list
            recipes.clear();

            //iterating through all the nodes
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                //getting artist
                Recipe recipe = postSnapshot.getValue(Recipe.class);
                //adding artist to the list
                //     recipes.add(recipe);
            }

            //creating adapter
            RecipeList recipeAdapter = new RecipeList(getActivity(), recipes);
            //attaching adapter to the listview
            listViewRecipes.setAdapter(recipeAdapter);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}



public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {

    //getting views
    editTextName = (EditText) view.findViewById(R.id.editTextName);
    editTextDescription= (EditText) view.findViewById(R.id.editTextDescription);
    listViewRecipes = (ListView) view.findViewById(R.id.listViewRecipes);
    buttonAddRecipe = (Button) view.findViewById(R.id.buttonAddRecipe);

    //list to store artists
    recipes = new ArrayList<>();

    //adding an onclicklistener to button
    buttonAddRecipe.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //calling the method addArtist()
            //the method is defined below
            //this method is actually performing the write operation
            addRecipe();
        }
    });


}



private void addRecipe() {

    //getting the values to save
    String name = editTextName.getText().toString().trim();
    String description = editTextDescription.getText().toString().trim();

    //checking if the value is provided
    if (!TextUtils.isEmpty(name)) {

        //getting a unique id using push().getKey() method
        //it will create a unique id and we will use it as the Primary Key for our Artist
        String id = databaseRecipes.push().getKey();

        //creating an Artist Object
        Recipe recipe = new Recipe(id, name, description);

        //Saving the Artist
        databaseRecipes.child(id).setValue(recipe);

        //setting edittext to blank again
        editTextName.setText("");

        //displaying a success toast
        Toast.makeText(getActivity(), "recipe added", Toast.LENGTH_LONG).show();
    } else {
        //if the value is not given displaying a toast
        Toast.makeText(getActivity(), "Please enter a recipe", Toast.LENGTH_LONG).show();
    }
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_add_recipe, container, false);
}

    }
}
public类AddRecipeFragment扩展片段{
//稍后我们将使用这些常量将艺术家名称和id传递给另一个活动
public static final String RECIPE_NAME=“net.simplifiedcoding.firebasedatabaseexample.artistname”;
public static final String RECIPE_ID=“net.simplifiedcoding.firebasedatabaseexample.artistid”;
//查看对象
编辑文本编辑文本名称;
编辑文本编辑文本描述;
按钮和密码;
ListView listViewRecipes;
ProgressBar ProgressBar;
FirebaseAuth mAuth;
//存储firebase数据库中所有食物的列表
列出食谱;
//我们的数据库引用对象
数据库参考数据库配方;
public AddRecipeFragment(){
//必需的空公共构造函数
}
/**
*使用此工厂方法创建的新实例
*使用提供的参数创建此片段。
*
*@param param1参数1。
*@param param2参数2。
*@return fragment AddRecipeFragment的新实例。
*/
//TODO:重命名和更改参数的类型和数量
public static AddRecipeFragment newInstance(字符串param1,字符串param2){
AddRecipeFragment片段=新的AddRecipeFragment();
Bundle args=新Bundle();
args.putString(ARG_PARAM1,PARAM1);
args.putString(ARG_PARAM2,PARAM2);
fragment.setArguments(args);
返回片段;
}
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
如果(getArguments()!=null){
mParam1=getArguments().getString(ARG_PARAM1);
mParam2=getArguments().getString(ARG_PARAM2);
}
//获取“艺术家”节点的引用
databaseRecipes=FirebaseDatabase.getInstance().getReference(“recipes”);
databaseRecipes.addValueEventListener(新的ValueEventListener(){
@凌驾
公共void onDataChange(DataSnapshot DataSnapshot){
//清除上一个艺术家列表
食谱;
//遍历所有节点
对于(DataSnapshot postSnapshot:DataSnapshot.getChildren()){
//获得艺术家
Recipe Recipe=postSnapshot.getValue(Recipe.class);
//将艺术家添加到列表中
//配方。添加(配方);
}
//创建适配器
RecipeList recipeAdapter=新的RecipeList(getActivity(),recipes);
//将适配器附加到listview
setAdapter(recipeAdapter);
}
@凌驾
已取消的公共void(DatabaseError DatabaseError){
}
});
}
已创建公用void onview(@NonNull视图,@Nullable Bundle savedInstanceState){
//获取视图
editTextName=(EditText)view.findViewById(R.id.editTextName);
editTextDescription=(EditText)view.findViewById(R.id.editTextDescription);
listViewRecipes=(ListView)view.findViewById(R.id.listViewRecipes);
buttonAddRecipe=(Button)视图.findViewById(R.id.buttonAddRecipe);
//存储艺术家的列表
recipes=新的ArrayList();
//向按钮添加onclicklistener
buttonAddRecipe.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
//调用addArtist()方法
//该方法定义如下
//此方法实际上正在执行写入操作
addRecipe();
}
});
}
私有void addRecipe(){
//获取要保存的值
字符串名称=editTextName.getText().toString().trim();
字符串描述=editTextDescription.getText().toString().trim();
//检查是否提供了该值
如果(!TextUtils.isEmpty(名称)){
//使用push().getKey()方法获取唯一id
//它将创建一个唯一的id,我们将使用它作为艺术家的主键
String id=databaseRecipes.push().getKey();
//创建艺术家对象
配方=新配方(id、名称、说明);
//拯救艺术家
databaseRecipes.child(id).setValue(recipe);
//再次将edittext设置为空白
editTextName.setText(“”);
//展示成功祝酒词
Toast.makeText(getActivity(),“添加配方”,Toast.LENGTH_LONG.show();
}否则{
//如果未给出该值,则显示toast
Toast.makeText(getActivity(),“请输入食谱”,Toast.LENGTH_LONG.show();
}
}
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
//为该碎片膨胀布局
返回充气机。充气(R.layout.fragment\u add\u reci
public class AddRecipeFragment extends Fragment {

//we will use these constants later to pass the artist name and id to another activity
public static final String RECIPE_NAME = "net.simplifiedcoding.firebasedatabaseexample.artistname";
public static final String RECIPE_ID = "net.simplifiedcoding.firebasedatabaseexample.artistid";

//view objects
EditText editTextName;
EditText editTextDescription;
Button buttonAddRecipe;
ListView listViewRecipes;

ProgressBar progressBar;


FirebaseAuth mAuth;


//a list to store all the foods from firebase database
List<Recipe> recipes;

//our database reference object
DatabaseReference databaseRecipes;


public AddRecipeFragment() {
    // Required empty public constructor
}

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment AddRecipeFragment.
 */
// TODO: Rename and change types and number of parameters
public static AddRecipeFragment newInstance(String param1, String param2) {
    AddRecipeFragment fragment = new AddRecipeFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }


    //getting the reference of artists node
    databaseRecipes = FirebaseDatabase.getInstance().getReference("recipes");


    databaseRecipes.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            //clearing the previous artist list
            recipes.clear();

            //iterating through all the nodes
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                //getting artist
                Recipe recipe = postSnapshot.getValue(Recipe.class);
                //adding artist to the list
                //     recipes.add(recipe);
            }

            //creating adapter
            RecipeList recipeAdapter = new RecipeList(getActivity(), recipes);
            //attaching adapter to the listview
            listViewRecipes.setAdapter(recipeAdapter);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}



public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {

    //getting views
    editTextName = (EditText) view.findViewById(R.id.editTextName);
    editTextDescription= (EditText) view.findViewById(R.id.editTextDescription);
    listViewRecipes = (ListView) view.findViewById(R.id.listViewRecipes);
    buttonAddRecipe = (Button) view.findViewById(R.id.buttonAddRecipe);

    //list to store artists
    recipes = new ArrayList<>();

    //adding an onclicklistener to button
    buttonAddRecipe.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //calling the method addArtist()
            //the method is defined below
            //this method is actually performing the write operation
            addRecipe();
        }
    });


}



private void addRecipe() {

    //getting the values to save
    String name = editTextName.getText().toString().trim();
    String description = editTextDescription.getText().toString().trim();

    //checking if the value is provided
    if (!TextUtils.isEmpty(name)) {

        //getting a unique id using push().getKey() method
        //it will create a unique id and we will use it as the Primary Key for our Artist
        String id = databaseRecipes.push().getKey();

        //creating an Artist Object
        Recipe recipe = new Recipe(id, name, description);

        //Saving the Artist
        databaseRecipes.child(id).setValue(recipe);

        //setting edittext to blank again
        editTextName.setText("");

        //displaying a success toast
        Toast.makeText(getActivity(), "recipe added", Toast.LENGTH_LONG).show();
    } else {
        //if the value is not given displaying a toast
        Toast.makeText(getActivity(), "Please enter a recipe", Toast.LENGTH_LONG).show();
    }
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_add_recipe, container, false);
}

    }
}
//Firebase
FirebaseStorage storage;
StorageReference storageReference;

storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();

private void uploadImage() {

  if(filePath != null)
  {

    StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
    ref.putFile(filePath)
            .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
              @Override
              public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                progressDialog.dismiss();
                Toast.makeText(MainActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
              }
            })
            .addOnFailureListener(new OnFailureListener() {
              @Override
              public void onFailure(@NonNull Exception e) {
                progressDialog.dismiss();
                Toast.makeText(MainActivity.this, "Failed "+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());
                progressDialog.setMessage("Uploaded "+(int)progress+"%");
              }
            });
  }
}