请查看我的代码和所需的快照,我创建了一个新活动,可以在其中更新我的产品详细信息(注意:我将在稍后的活动中添加图片上传功能)。但是从我的代码中,我得到的结果就像附上快照的快照一样,该快照用红色标记了我想要的内容。我以管理员身份添加产品,并尝试以管理员身份进行更新,但是从另一个活动中我想更新我的数据。请帮助我
这是我正在尝试的活动代码
package com.commerce.daily.dailycommerce;
import android.app.ProgressDialog;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import com.commerce.daily.dailycommerce.ViewHolder.ProductViewHolder;
import com.commerce.daily.dailycommerce.model.Products;
import com.commerce.daily.dailycommerce.prevalent.prevalent;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.HashMap;
public class AdminUpdatingProductsActivity extends AppCompatActivity {
private String UpdateDescription, updatePrice, updatePName;
private TextView updateTxtBtn, changeImageTxt, closeTxtBtn;
private EditText productUpdateName, productUpdateDescription, productUpdatePrice;
private DatabaseReference updateProductRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_updating_products);
updateProductRef = FirebaseDatabase.getInstance().getReference().child("Products");
updateTxtBtn = (TextView) findViewById(R.id.update_product_details_btn2);
changeImageTxt = (TextView) findViewById(R.id.product_image_update_txt);
closeTxtBtn = (TextView) findViewById(R.id.close_update_product_btn);
productUpdateName = (EditText) findViewById(R.id.update_product_name);
productUpdateDescription = (EditText) findViewById(R.id.update_product_description);
productUpdatePrice = (EditText) findViewById(R.id.update_product_price);
updateTxtBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
updateinformation();
}
});
}
private void updateinformation() {
updatePName = productUpdateName.getText().toString();
UpdateDescription = productUpdateDescription.getText().toString();
updatePrice = productUpdatePrice.getText().toString();
HashMap<String, Object> ProductMap = new HashMap<>();
ProductMap.put("pname", updatePName);
ProductMap.put("price", updatePrice);
ProductMap.put("description", UpdateDescription);
updateProductRef.updateChildren(ProductMap);
}
}
这是xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.commerce.daily.dailycommerce.AdminUpdatingProductsActivity">
<android.support.design.widget.AppBarLayout
android:id="@+id/app_bar_update_product"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="@color/colorPrimary">
<android.support.v7.widget.Toolbar
android:id="@+id/tollbar_update_product"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/close_update_product_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Close"
android:textColor="@android:color/white"
android:textSize="17sp"
android:textStyle="bold"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"/>
<TextView
android:id="@+id/update_product_details_btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Update"
android:textColor="@android:color/white"
android:textSize="17sp"
android:textStyle="bold"
android:layout_marginRight="10dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"/>
</RelativeLayout>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<ImageView
android:id="@+id/product_image_update"
android:layout_below="@+id/app_bar_update_product"
android:layout_width="250dp"
android:layout_height="150dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:src="@drawable/ic_menu_camera"/>
<TextView
android:id="@+id/product_image_update_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/product_image_update"
android:text="Change Image"
android:layout_marginTop="4dp"
android:textColor="@android:color/black"
android:textSize="17sp"
android:textStyle="bold"
android:layout_marginRight="10dp"
android:layout_centerHorizontal="true"/>
<EditText
android:id="@+id/update_product_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/product_image_update_txt"
android:inputType="textMultiLine"
android:layout_marginTop="30dp"
android:padding="20dp"
android:hint="Product Name..."
android:layout_marginLeft="45dp"
android:layout_marginRight="45dp"
android:background="@drawable/input_design"/>
<EditText
android:id="@+id/update_product_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/update_product_name"
android:inputType="textMultiLine"
android:layout_marginTop="6dp"
android:padding="20dp"
android:hint="Product Description..."
android:layout_marginLeft="45dp"
android:layout_marginRight="45dp"
android:background="@drawable/input_design"/>
<EditText
android:id="@+id/update_product_price"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/update_product_description"
android:inputType="textMultiLine"
android:layout_marginTop="6dp"
android:padding="20dp"
android:hint="Product Price..."
android:layout_marginLeft="45dp"
android:layout_marginRight="45dp"
android:background="@drawable/input_design"/>
</RelativeLayout>
package com.commerce.daily.dailycommerce;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;
import com.commerce.daily.dailycommerce.Interface.ItemClickListner;
import com.commerce.daily.dailycommerce.ViewHolder.ProductViewHolder;
import com.commerce.daily.dailycommerce.model.Products;
import com.commerce.daily.dailycommerce.prevalent.prevalent;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.squareup.picasso.Picasso;
import java.util.HashMap;
public class AdminListedProductActivity extends AppCompatActivity
{
private DatabaseReference AdminProductsRef;
private RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_listed_product);
AdminProductsRef = FirebaseDatabase.getInstance().getReference().child("Products");
recyclerView = findViewById(R.id.productlist_recycler);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
}
@Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<Products> options =
new FirebaseRecyclerOptions.Builder<Products>()
.setQuery(AdminProductsRef, Products.class)
.build();
final FirebaseRecyclerAdapter<Products, ProductViewHolder> adapter =
new FirebaseRecyclerAdapter<Products, ProductViewHolder>(options)
{
@Override
protected void onBindViewHolder(@NonNull ProductViewHolder holder, final int position, @NonNull final Products model)
{
holder.txtProductName.setText(model.getPname());
holder.txtProductDescription.setText(model.getDescription());
holder.txtProductPrice.setText("Price = "+ model.getPrice());
Picasso.get().load(model.getImage()).into(holder.imageView);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
CharSequence options[] = new CharSequence[]
{
"Edit",
"Remove"
};
AlertDialog.Builder builder = new AlertDialog.Builder(AdminListedProductActivity.this);
builder.setTitle("Edit/Delete");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
if(which == 0)
{
updateProducts();
}
if(which == 1)
{
FirebaseDatabase.getInstance().getReference().child("Products")
.child(model.getDate() + model.getTime())
.removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task)
{
if(task.isSuccessful())
{
Toast.makeText(AdminListedProductActivity.this, "Item Removed Successfully.", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(AdminListedProductActivity.this, AdminCategoryActivity.class);
startActivity(intent);
}
}
});
}
}
});
builder.show();
}
});
}
@NonNull
@Override
public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_items_layout, parent, false);
ProductViewHolder holder = new ProductViewHolder(view);
return holder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
private void updateProducts()
{
finish();
}
@Override
public void onBackPressed()
{
super.onBackPressed();
}
}
这是我的产品类,位于名为model的程序包下
package com.commerce.daily.dailycommerce.model;
/**
* Created by Romen on 2/10/2019.
*/
public class Products
{
private String pname, description, price,image, category, pid, date, time;
public Products()
{
}
public Products(String pname, String description, String price, String image, String category, String pid, String date, String time)
{
this.pname = pname;
this.description = description;
this.price = price;
this.image = image;
this.category = category;
this.pid = pid;
this.date = date;
this.time = time;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
答案 0 :(得分:0)
您无法以这种方式更新所需的特定节点,因为未指定要更新其数据的节点。
在updateProductRef.updateChildren(ProductMap);
行中,您指定“产品”节点,然后在其中添加数据,而不是应指定要更新它的节点。
要实现此目的,您应该为每个节点放置一个唯一的ID(例如数据库中的“ pid”属性),然后将其与当前活动中的“ pid”进行比较。
putExtra()
方法,将其有意图地发送。pid
属性进行比较,然后获取该产品的密钥并将其设置为子级。修改
实际上,我无法正确理解您的代码,或者这是一个错误,因此,我构建了另一个完全不同的代码。
public class AdapterProducts extends RecyclerView.Adapter<AdapterProducts.HolderProuducts> {
Context context;
List<products> listProuducts;
private AdapterProducts.OnItemClickListener mListener;
//This interface for handle clicked on an item in recyclerview
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(AdapterProducts.OnItemClickListener listener) {
mListener = listener;
}
//constrouctor
public AdapterProducts(Context context,List<products> listProuducts)
{
this.listProuducts = listProuducts;
this.context = context;
}
@Override
public AdapterProducts.HolderProuducts onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View row = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.row_item_products, viewGroup, false);
AdapterProducts.HolderProuducts holder = new AdapterProducts.HolderProuducts(row, mListener);
return holder;
}
@Override
public void onBindViewHolder(@NonNull AdapterProducts.HolderProuducts holderProuducts, int i) {
holderProuducts.txtProductName.setText(model.getPname());
holderProuducts.txtProductDescription.setText(model.getDescription());
holderProuducts.txtProductPrice.setText("Price = "+ model.getPrice());
Picasso.get().load(model.getImage()).into(holderProuducts.imageView);
}
@Override
public int getItemCount() {
return listProuducts.size();
}
public class HolderProuducts extends RecyclerView.ViewHolder{
TextView txtProductName,txtProductDescription,txtProductPrice;
ImageView imageView;
public HolderProuducts(@NonNull View itemView, final AdapterProducts.OnItemClickListener listener) {
super(itemView);
txtProductName = (TextView) itemView.findViewById(R.id.name_product);
txtProductDescription = (TextView) itemView.findViewById(R.id.description_product);
txtProductPrice = (TextView) itemView.findViewById(R.id.price_product);
imageView = (ImageView) itemView.findViewById(R.id.image_view);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
}
}
});
}
}
}
在您的AdminListedProductActivity
中:
`
公共类AdminListedProductActivity扩展了AppCompatActivity {
RecyclerView mRecyclerProducts;
List<Products> listProducts;
LinearLayoutManager layoutManager;
AdapterProducts mAdapterProducts;
DatabaseReference AdminProductsRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_listed_product);
AdminProductsRef = FirebaseDatabase.getInstance().getReference().child("Products");
listProducts = new ArrayList();
mRecyclerProducts = findViewById(R.id.productlist_recycler);
mRecyclerProducts.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
mRecyclerProducts.setLayoutManager(layoutManager);
listProducts = displayProuductsInList();
mAdapterProducts.setOnItemClickListener(new AdapterProducts.OnItemClickListener() {
@Override
public void onItemClick(int position) {
Products productsClicked = listProducts.get(position);
//This pid for the item that clicked on it
String pid = productsClicked.getPid();
Intent intent = new Intent(AdminListedProductActivity .this,AdminUpdatingProductsActivity.class);
//send it with intent to activity update
intent.putExtra("pid",pid);
startActivity(intent);
}
});
}
//This method for get all products from database
private List<Products> displayProuductsInList() {
List<Products> list = new ArrayList();
AdminProductsRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
Products products = data.getValue(Products.class);
list.add(products);
}
mRecyclerProducts.setLayoutManager(new LinearLayoutManager(AdminListedProductActivity .this));
mAdapterProducts.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
} `
在您的AdminUpdatingProductsActivity
中:
public class AdminUpdatingProductsActivity extends AppCompatActivity {
private String UpdateDescription, updatePrice, updatePName;
private TextView updateTxtBtn, changeImageTxt, closeTxtBtn;
private EditText productUpdateName, productUpdateDescription, productUpdatePrice;
DatabaseReference updateProductRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_listed_product);
updateProductRef = FirebaseDatabase.getInstance().getReference().child("Products");
updateTxtBtn = (TextView) findViewById(R.id.update_product_details_btn2);
changeImageTxt = (TextView) findViewById(R.id.product_image_update_txt);
closeTxtBtn = (TextView) findViewById(R.id.close_update_product_btn);
productUpdateName = (EditText) findViewById(R.id.update_product_name);
productUpdateDescription = (EditText) findViewById(R.id.update_product_description);
productUpdatePrice = (EditText) findViewById(R.id.update_product_price);
updateTxtBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
updateinformation();
}
});
}
private void updateinformation() {
Intent intent = getIntent();
String pidFromPriveosActivity = intent.getStringExtra("pid");
updatePName = productUpdateName.getText().toString();
UpdateDescription = productUpdateDescription.getText().toString();
updatePrice = productUpdatePrice.getText().toString();
HashMap<String, Object> ProductMap = new HashMap<>();
ProductMap.put("pname", updatePName);
ProductMap.put("price", updatePrice);
ProductMap.put("description", UpdateDescription);
updateProductRef.addListenerForSingleValueEvent(new ValueEventListener() {
String currentKey;
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren())
{
//get each "pid" in database for all products
String pidsInDataBase = data.child("pid").getValue(String.class);
//compare "pid" from previous activity with each "pid" in database
if (pidFromPriveosActivity.equals(pidsInDataBase)){
//get key for product that clicke on it in recyclerview
currentKey = data.getKey();
}
}
//update data for this item
updateProductRef.child(currentKey).updateChildren(ProductMap);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}}