【问题标题】:Adding an image to Firebase将图像添加到 Firebase
【发布时间】:2018-08-22 10:23:41
【问题描述】:

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

这是我目前所拥有的:

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

public class Recipe {
    private String recipeId;
    private String recipeName;
    private String recipeDescription;

public String getRecipeId() {
    return recipeId;
}

public void setRecipeId(String recipeId) {
    this.recipeId = recipeId;
}

public void setRecipeName(String recipeName) {
    this.recipeName = recipeName;
}

public void setRecipeDescription(String recipeDescription) {
    this.recipeDescription = recipeDescription;
}

public Recipe(String recipeId, String recipeName, String recipeDescription) {
    this.recipeId = recipeId;

    this.recipeName = recipeName;
    this.recipeDescription = recipeDescription;
}



public String getRecipeName() {
    return recipeName;
}

public String getRecipeDescription() {
    return recipeDescription;
}

public Recipe(){

    //this constructor is required
}

我的列表视图类

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;
}

}

我要上传图片的主要片段

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);
}

    }
}

【问题讨论】:

    标签: image listview firebase-storage


    【解决方案1】:

    关注this教程,它会给你一个好的开始。

    这包含所需的基本代码。您需要将图片的文件路径分配给代码段中提到的“filepath”变量并调用上传图片方法。

    //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+"%");
                  }
                });
      }
    }
    

    【讨论】:

    • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
    • 感谢您的建议。我会改变答案:)
    猜你喜欢
    • 2017-07-11
    • 2020-12-09
    • 2020-10-03
    • 2020-07-21
    • 2019-08-18
    • 2020-08-18
    • 2021-03-22
    • 2021-07-04
    • 2014-06-03
    相关资源
    最近更新 更多