I have a problem to write a code to delete database.
I would like to delete this:
I don't know how to use .child() in this situation. My code for now is:
private void deleteKryterium(String kryteriumId) {
DatabaseReference drKryteria = FirebaseDatabase.getInstance().getReference().child(kryteriumId);
drKryteria.child(kryteriumId).removeValue();
Toast.makeText(this,"Kryterium zostało usunięte", Toast.LENGTH_LONG).show();
}
But it is wrong. Can you help me? Most of the code I wrote from tutorials, so it's very green.
On the other side code which is designated to update this child, is working fine:
private boolean updateKryterium(String id, String name, int rating){
Kryterium kryterium = new Kryterium(id, name, rating);
databaseKryteria.child(id).setValue(kryterium);
Toast.makeText(this, "Nazwa kryterium zaktualizowana", Toast.LENGTH_LONG).show();
return true;
You are not pointing to the correct reference you want to remove.
The path to that child should start from:
DatabaseReference drKryteria = FirebaseDatabase.getInstance().getReference().child("piwo_kryteria");
Then at that point, you should move to the child with key -LI785bPiLU9Z2qEe35o and then finally to the child you want to remove (with id kryteriumId).
You should know the value of the intermediate key as you do for the kyteriumId.
Notice that you can also use 1 single child() function passing to it the entire path in which each node is separated by forward-slashes like:
.child("piwo_kryteria/" + intermediate_key + "/" + kryteriumId)
On that reference you will call removeValue() or even setValue(null).
this is a code for now, ofcourse it is not working correctly in deleting items:
public class Piwo_AddKryterium extends AppCompatActivity {
TextView textViewAlkoholName, textViewRating;
SeekBar seekBarRating;
Spinner spinnerKryteria;
Button buttonAddKryterium;
ListView listViewKryteria;
DatabaseReference databaseKryteria;
List<Kryterium> kryteria;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.piwo_activity_add_kryterium);
textViewAlkoholName = (TextView) findViewById(R.id.textViewAlkoholName);
seekBarRating = (SeekBar) findViewById(R.id.seekBarRating);
textViewRating = (TextView) findViewById(R.id.textViewRating);
buttonAddKryterium = (Button) findViewById(R.id.buttonAddKryterium);
listViewKryteria = (ListView) findViewById(R.id.listViewKryteria);
spinnerKryteria = (Spinner) findViewById(R.id.spinnerKryteria);
Intent intent = getIntent();
kryteria = new ArrayList<>();
String id = intent.getStringExtra(Piwo_Program.ALKOHOL_ID);
String name = intent.getStringExtra(Piwo_Program.ALKOHOL_NAME);
textViewAlkoholName.setText(name);
databaseKryteria = FirebaseDatabase.getInstance().getReference("piwo_kryteria").child(id);
buttonAddKryterium.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveKryterium();
}
});
seekBarRating.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
textViewRating.setText(String.valueOf(i));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
listViewKryteria.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
});
listViewKryteria.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
Kryterium kryterium = kryteria.get(i);
showUpdateDialog(kryterium.getKryteriumId(), kryterium.getKryteriumName());
return true;
}
});
}
#Override
protected void onStart() {
super.onStart();
databaseKryteria.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
kryteria.clear();
for(DataSnapshot kryteriumSnapshot : dataSnapshot.getChildren()){
Kryterium kryterium = kryteriumSnapshot.getValue(Kryterium.class);
kryteria.add(kryterium);
}
KryteriumList kryteriumListAdapter = new KryteriumList(Piwo_AddKryterium.this, kryteria);
listViewKryteria.setAdapter(kryteriumListAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void saveKryterium(){
String kryteriumName = spinnerKryteria.getSelectedItem().toString();
int rating = seekBarRating.getProgress();
if(!TextUtils.isEmpty(kryteriumName)){
String id = databaseKryteria.push().getKey();
Kryterium kryterium = new Kryterium(id, kryteriumName, rating);
databaseKryteria.child(id).setValue(kryterium);
Toast.makeText(this, "Kryterium zapisane poprawnie", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, "Nazwa kryterium nie może pozostać pusta", Toast.LENGTH_SHORT).show();
}
}
private void showUpdateDialog(final String kryteriumId, String kryteriumName){
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.piwo_update_dialog_kryterium, null);
dialogBuilder.setView(dialogView);
final Spinner spinnerKryteria = (Spinner) dialogView.findViewById(R.id.spinnerKryteria);
final Button buttonUpdate = (Button) dialogView.findViewById(R.id.buttonUpdate);
final SeekBar seekBarRating = (SeekBar) dialogView.findViewById(R.id.seekBarRating);
final Button buttonDelete = (Button) dialogView.findViewById(R.id.buttonDelete);
dialogBuilder.setTitle("Aktualizacja Kryterium: " + kryteriumName);
final AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
buttonUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String kryteriumName = spinnerKryteria.getSelectedItem().toString();
int rating = seekBarRating.getProgress();
updateKryterium(kryteriumId, kryteriumName, rating);
alertDialog.dismiss();
}
});
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deleteKryterium(kryteriumId);
alertDialog.dismiss();
}
});
}
private void deleteKryterium(String kryteriumId) {
DatabaseReference drKryteria = FirebaseDatabase.getInstance().getReference().child(kryteriumId);
drKryteria.child(kryteriumId).removeValue();
Toast.makeText(this,"Kryterium zostało usunięte", Toast.LENGTH_LONG).show();
}
private boolean updateKryterium(String id, String name, int rating){
Kryterium kryterium = new Kryterium(id, name, rating);
databaseKryteria.child(id).setValue(kryterium);
Toast.makeText(this, "Nazwa kryterium zaktualizowana", Toast.LENGTH_LONG).show();
return true;
}
}
Related
i have a problem and my problem is : when i kill the app or shutting down the device , all the information was erased and i can find it , first of all and what i want to do in the first place is: i want to check if this is the first time of the user to use this app or not , if that is the first time then save what he chosen in the sharedPreference xml and if not , then retrieve was chosen and show it , sorry for my bad english , it's not my mother tongue
this is the main activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quran);
readers= (CardView)findViewById(R.id.readers);
readers_name=(TextView)findViewById(R.id.readers_name);
rewaya=(TextView)findViewById(R.id.rewaya);
count=(TextView)findViewById(R.id.count);
Intent i = getIntent();
String txtData = i.getStringExtra("reciters_name");
String txtData1 = i.getStringExtra("reciters_rewaya");
String txtData2 = i.getStringExtra("reciters_count");
shareRef=getSharedPreferences("myPref", MODE_PRIVATE);
SharedPreferences.Editor myedit = shareRef.edit();
boolean firstRun = shareRef.getBoolean("firstRun", true);
if(firstRun) {
myedit.clear();
myedit.putString("reciters", txtData);
myedit.putBoolean("firstRun", false);
myedit.putString("rewaya", txtData1);
myedit.putString("count", txtData2);
myedit.commit();
readers_name.setText(txtData);
rewaya.setText(txtData1);
count.setText(txtData2);
}else {
readers_name.setText(shareRef.getString("reciters", ""));
rewaya.setText(shareRef.getString("rewaya", ""));
count.setText(shareRef.getString("count", ""));
}
fav_suras=(RecyclerView)findViewById(R.id.fav_suras);
fav_suras.setLayoutManager(new LinearLayoutManager(this));
suras=(RecyclerView)findViewById(R.id.suras);
suras.setHasFixedSize(true);
suras.setLayoutManager(new LinearLayoutManager(this));
suras.setAdapter(Mquraan_adapter);
//mSuras_api = new ArrayList<>();
getRetrofit();
readers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent (quran.this, Readers.class);
startActivity(intent);
}
});
}
public void getRetrofit() {
RequestInterface requestInterface = PostClient.getApiClient().create(RequestInterface.class);
Call<FomCombine> call = requestInterface.getPosts();
call.enqueue(new Callback <FomCombine>() {
#Override
public void onResponse(Call<FomCombine> call, retrofit2.Response <FomCombine> response) {
Toast.makeText(quran.this, "success", Toast.LENGTH_SHORT).show();
mSuras_api = response.body().getfom_combine();
Mquraan_adapter= new quran_adapter(quran.this, (ArrayList<suras_api>) mSuras_api);
suras.setAdapter(Mquraan_adapter);
Mquraan_adapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<FomCombine> call, Throwable t) {
Log.d("Tag", t.getMessage());
}
});
}}
this is the adapter
private Context mContext ;
private ArrayList<Reciters_api> mReciters_api;
public Reciters_adapter(Context context, ArrayList<Reciters_api> mmReciters_api) {
mContext=context;
mReciters_api=mmReciters_api;
}
#NonNull
#Override
public Reciters_adapter.ReadersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.single_row,parent,false);
return new ReadersViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ReadersViewHolder holder, int position) {
Reciters_api reciters = mReciters_api.get(position);
String ID_number = reciters.getId1();
String Name =reciters.getName1();
String Rewaya = reciters.getRewaya();
String count =reciters.getCount();
holder.readers_names.setText(Name);
holder.countt.setText(count);
holder.rewayya.setText(Rewaya);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent Reciters = new Intent(context, quran.class);
Reciters.putExtra("reciters_name", Name);
Reciters.putExtra("reciters_rewaya", Rewaya);
Reciters.putExtra("reciters_count", count);
context.startActivity(Reciters);
}
});
}
#Override
public int getItemCount() {
return mReciters_api.size();
}
public class ReadersViewHolder extends RecyclerView.ViewHolder{
public TextView readers_names ,rewayya ,countt;
public ReadersViewHolder(#NonNull View itemView) {
super(itemView);
readers_names=itemView.findViewById(R.id.readers_names);
rewayya=itemView.findViewById(R.id.rewayya);
countt=itemView.findViewById(R.id.countt);
}
}
}
I want to open one fragment from another. But as the result I get this (two mixed fragments):
Here is code of the fragment from which I want to go to the next fragment:
public class ChatRoomFragment extends Fragment implements View.OnClickListener in l1.setOnItemClickListener {
DatabaseReference reference;
static HashMap<String, String> dataHashMap = new HashMap<String, String>();
ArrayList<String> arrayList;
EditText e1;
ListView l1;
ArrayAdapter<String> adapter;
String name;
EditText ee;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.chatroom_fragment, container, false);
Button button = view.findViewById(R.id.button);
button.setOnClickListener(this);
super.onCreate(savedInstanceState);
e1 = (EditText)view.findViewById(R.id.editText);
l1 = (ListView)view.findViewById(R.id.listView);
arrayList = new ArrayList<>();
adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,arrayList);
l1.setAdapter(adapter);
FirebaseOptions options = new FirebaseOptions.Builder()
.../setting options
FirebaseApp.initializeApp(getActivity(), options, "secondary");
FirebaseApp app = FirebaseApp.getInstance("secondary");
reference = FirebaseDatabase.getInstance(app).getReference().getRoot();
request_username();
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Set<String> set = new HashSet<String>();
Iterator i = dataSnapshot.getChildren().iterator();
while (i.hasNext()) {
set.add(((DataSnapshot) i.next()).getKey());
}
arrayList.clear();
arrayList.addAll(set);
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Toast.makeText(NavigationDrawerActivity.this, "No network connectivity", Toast.LENGTH_SHORT).show();
}
});
ChatFragment fragment = new ChatFragment();
l1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
dataHashMap.put("room_name", ((TextView) view).getText().toString());
dataHashMap.put("user_name", name);
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
}
});
return view;
}
public void request_username()
{
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Enter your name?");
ee = new EditText(getActivity());
builder.setView(ee);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
name = ee.getText().toString();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
request_username();
}
});
builder.show();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
insert_data(v);
break;
}
}
public void insert_data(View v)
{
switch (v.getId()) {
case R.id.button :
Map<String, Object> map = new HashMap<>();
map.put(e1.getText().toString(), "");
reference.updateChildren(map);
}
}
}
Here is the code of the Fragment to which I want to go:
EditText e1;
TextView t1;
private String user_name,room_name;
DatabaseReference reference;
String temp_key;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.chat_fragment, container, false);
Button button = view.findViewById(R.id.button2);
button.setOnClickListener(this);
super.onCreate(savedInstanceState);
e1= view.findViewById(R.id.editText2);
t1= view.findViewById(R.id.textView);
if(((AppCompatActivity)getActivity()).getSupportActionBar()!=null)
{
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);
}
Log.d("checkintent", getActivity().getIntent().toString());
//user_name = getActivity().getIntent().getExtras().get("user_name").toString();
user_name = ChatRoomFragment.dataHashMap.get("user_name").toString();
//room_name = getActivity().getIntent().getExtras().get("room_name").toString();
room_name = ChatRoomFragment.dataHashMap.get("room_name").toString();
FirebaseApp app = FirebaseApp.getInstance("secondary");
reference = FirebaseDatabase.getInstance(app).getReference().getRoot();
getActivity().setTitle(" Room - "+room_name);
reference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
append_chat(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
append_chat(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
append_chat(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return view;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home)
getActivity().finish();
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button2:
send(v);
break;
}
}
public void send(View v)
{
Map<String,Object> map = new HashMap<String,Object>();
temp_key = reference.push().getKey();
reference.updateChildren(map);
DatabaseReference child_ref = reference.child(temp_key);
Map<String,Object> map2 = new HashMap<>();
map2.put("name",user_name);
map2.put("msg", e1.getText().toString());
child_ref.updateChildren(map2).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(Exception e) {
Toast.makeText(getActivity().getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
});
e1.setText("");
}
public void append_chat(DataSnapshot ss)
{
String chat_msg,chat_username;
Iterator i = ss.getChildren().iterator();
while(i.hasNext())
{
chat_msg = ((DataSnapshot)i.next()).getValue().toString();
chat_username = ((DataSnapshot)i.next()).getValue().toString();
t1.append(chat_username + ": " +chat_msg + " \n");
}
}
}
What should I change to have the ChatFragment opened only, but not both fragments at the same time? (I need pink items to be on the screen only)
I can get key and show in Log.d but it don't show in RecyclerView. What's wrong with it?
HistoryActivity.java it contains my recyclerView:
public class HistoryActivity extends AppCompatActivity {
FirebaseFirestore mFirestore;
FirebaseAuth firebaseAuth;
FirebaseDatabase database;
RecyclerView mHisList;
ArrayList<PreviousLst> history;
adt_rv_HisList adtRvHisList;
TextView ptName;
TextView ptPort;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
getSupportActionBar().setSubtitle("History");
Intent it = getIntent();
String patName = it.getStringExtra("nm");
String patID = it.getStringExtra("idpat");
String portNum = it.getStringExtra("pNum");
String regisDate = it.getStringExtra("rdate");
ptName = findViewById(R.id.txName);
ptPort = findViewById(R.id.portpassValue);
ptName.setText(patName);
ptPort.setText(portNum);
history = new ArrayList<>();
setupRecyclerView();
setupFireBase();
loadDataFromDatabase(portNum);
}
private void setupFireBase() {
mFirestore = FirebaseFirestore.getInstance();
firebaseAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
}
private void setupRecyclerView() {
mHisList = findViewById(R.id.rv_prev_lst);
mHisList.setHasFixedSize(true);
mHisList.setLayoutManager(new LinearLayoutManager(this));
mHisList.setAdapter(adtRvHisList);
}
public void loadDataFromDatabase(String portNum) {
if(history.size()>0)
history.clear();
DatabaseReference myRef;
DatabaseReference passref;
switch (portNum){
case "Huang-Yai0002":
String p2 = "NETEKG-Huang-Yai0002";
myRef = database.getReference("MACHINE");
passref = myRef.child(p2).child("value");
passref.addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
String keydate = postSnapshot.getKey();
Log.d(TAG, "Child are: " + keydate );
PreviousLst previousLst = new PreviousLst(keydate);
history.add(previousLst);
}
adtRvHisList = new adt_rv_HisList(HistoryActivity.this, history);
mHisList.setAdapter(adtRvHisList);
}
#Override
public void onCancelled(DatabaseError error) {
Log.w(TAG, "Failed to read value.", error.toException());
}
});
break;
case "Huang-Yai0003":
String p3 = "NETEKG-Huang-Yai0003";
myRef = database.getReference("MACHINE");
passref = myRef.child(p3).child("value");
passref.addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
String keydate = postSnapshot.getKey();
Log.d(TAG, "Child are: " + keydate );
PreviousLst previousLst = new PreviousLst(postSnapshot.getKey());
history.add(previousLst);
}
adtRvHisList = new adt_rv_HisList(HistoryActivity.this, history);
mHisList.setAdapter(adtRvHisList);
}
#Override
public void onCancelled(DatabaseError error) {
Log.w(TAG, "Failed to read value.", error.toException());
}
});
break;
default:
Log.d(TAG, "Value is: " + portNum);
Toast.makeText(getApplicationContext(),"Error...",Toast.LENGTH_LONG).show();
break;
}
}
}
adt_rv_HisList.java Adapter:
public class adt_rv_HisList extends RecyclerView.Adapter<adtrvHisListViewHolder> {
HistoryActivity historyActivity;
ArrayList<PreviousLst> history;
public adt_rv_HisList(HistoryActivity historyActivity, ArrayList<PreviousLst> history) {
this.history = history;
this.historyActivity = historyActivity;
}
#NonNull
#Override
public adtrvHisListViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(historyActivity.getBaseContext()).inflate(R.layout.hislist_item, viewGroup, false);
return new adtrvHisListViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull adtrvHisListViewHolder holder, int position) {
holder.hdate.setText(history.get(position).getHisDate());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialogView();
}
});
}
private void dialogView() {
final Dialog dia = new Dialog(historyActivity);
dia.setContentView(R.layout.dialog_ask_view);
dia.show();
Button pvgraph = (Button)dia.findViewById(R.id.bt_pvgraph);
Button pvhr = (Button)dia.findViewById(R.id.bt_pvhrate);
Button cc = (Button)dia.findViewById(R.id.btn_cancel);
cc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dia.dismiss();
}
});
pvgraph.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dia.dismiss();
Intent it = new Intent(historyActivity, ViewgraphActivity.class);
historyActivity.startActivity(it);
}
});
pvhr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dia.dismiss();
Intent it = new Intent(historyActivity, ViewHRActivity.class);
historyActivity.startActivity(it);
}
});
}
#Override
public int getItemCount() {
return 0;
}
}
adtrvHisListViewHolder.java Contains the ViewHolder :
public class adtrvHisListViewHolder extends RecyclerView.ViewHolder {
public TextView hdate;
public adtrvHisListViewHolder(View itemView) {
super(itemView);
hdate = itemView.findViewById(R.id.his_date);
}
}
PreviousLst.java is Model class for my recyclerView:
public class PreviousLst {
String HisDate;
public PreviousLst(String HisDate){
this.HisDate = HisDate;
}
public PreviousLst(){
}
public String getHisDate() {
return HisDate;
}
public void setHisDate(String hisDate) {
HisDate = hisDate;
}
}
This is my key that I get and show in Log.d
D/ContentValues: Child are: HEART RATE
D/ContentValues: Child are:LEAD 1
Child are: LEAD 2
Child are: LEAD 3
Child are: LEAD 4
Child are: LEAD 5
Child are: LEAD 6
but it don't shoe in App.
enter image description here
#Override
public int getItemCount() {
//return 0;
replace it with history.size();
}
the added lines tells the adapter how many items, the adapter has to bind the items to the recycler view. By default it is 0, means the adapter class will never call the binView method to show the items at view side
Based on information from Android: Create spinner programmatically from array. I can select room choices from spinner based on ArrayList. However,it never get inside the process setOnItemSelectedListener.I cannot figure out why does it happen.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_room);
SpaceRoomTable = (TableLayout) findViewById(R.id.tvSpaceRoomTable);
AddroomButton = (Button)findViewById(R.id.btLinkAddRoom);
Backtomenu = (Button) findViewById(R.id.bBackToMenu_DogTrack);
Delete = ContextCompat.getDrawable(this, R.drawable.bin);
dropdown = (Spinner) findViewById(R.id.spinListRoom);
summitDelete = (Button) findViewById(R.id.btDeleteSummit);
AddroomButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent LinkToEditroom = new Intent (EditRoom.this,AddRoom.class);
startActivity(LinkToEditroom);
}
});
Backtomenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent LinkToHomeMenu = new Intent(EditRoom.this,HomeMenu.class);
EditRoom.this.startActivity(LinkToHomeMenu);
}
});
showRoom();
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,showitemName);
spinnerArrayAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropdown.setAdapter(spinnerArrayAdapter);
dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
// Log.d("TEST","selection is ");
Object Itemselected = adapterView.getItemAtPosition(i);
Toast.makeText(getApplicationContext(),"Inside"+String.valueOf(Itemselected),Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
In XML Layout :-
<Spinner
android:id="#+id/dropdown"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
then, in your activity findViewById like this:-
dropdown= (Spinner) findViewById(R.id.dropdown);
then Create an ArrayAdapter using the string array and a default spinner layout :-
ArrayAdapter<String> spinnerArrayAdapter = ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,showitemName);
spinnerArrayAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropdown.setAdapter(spinnerArrayAdapter);
For OnIemClickListener use like this:-
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
Spinner dropdown;
String[] showitemName = {"A","B","C","D","E"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dropdown= (Spinner) findViewById(R.id.dropdown);
dropdown.setOnItemSelectedListener(this);
ArrayAdapter<String> spinnerArrayAdapter = ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,showitemName);
spinnerArrayAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropdown.setAdapter(spinnerArrayAdapter);
}
//Performing action onItemSelected and onNothing selected
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int position,long id) {
Toast.makeText(getApplicationContext(),"Inside" + parent.getItemAtPosition(position) , Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
More information:
You can check in details from these links:-
https://developer.android.com/guide/topics/ui/controls/spinner.html
https://developer.android.com/reference/android/widget/AdapterView.OnItemSelectedListener.html
https://android--code.blogspot.in/2015/08/android-spinner-onitemselected.html
http://www.java2s.com/Code/Android/UI/SpinnerItemSelectedListener.htm
https://android--code.blogspot.in/2015/08/android-spinner-get-selected-item-text.html
For more Information about showroom method
public void showRoom()
{
refroom.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
int Length_Record = dataSnapshot.child("CurrentUser").child("Tracking").child("ListRoom").child("LIST_ROOM_LENGTH").getValue(int.class);
int RunRecord =0;
int printRoom =0;
final String userId = dataSnapshot.child("CurrentUser").child("UserId").getValue(String.class);
for (DataSnapshot zonesnapshot : dataSnapshot.child("CurrentUser").child("Tracking").child("ListRoom").getChildren())
{
if(printRoom!=Length_Record)
{
zonesnapshot.getValue();
String[] parts = String.valueOf(zonesnapshot.getValue()).split(",");
String part1 = parts[0]; // Room Id
String part2 = parts[1]; // Room Name
String part3 = parts[2]; // TypeRoom
String OnRoom = dataSnapshot.child("CurrentUser").child("Tracking").child("Location").getValue(String.class);
itemsName.add(part2+","+part3); // put to arraylist to prepare a room choice for deletion
showitemName.add(part2+"("+part3+")");
itemOfUser.put(userId+"Room"+printRoom,part2+","+part3); // keep room for each user
inRow(dataSnapshot.child("CurrentUser").child("UserId").getValue(String.class), RunRecord, part2, OnRoom, part3);
}
printRoom++;
}
summitDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
storageReference = storage.getInstance().getReferenceFromUrl("gs://********-*****.appspot.com/imagesRoom").child(userId).child(selection);
storageReference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(),"Error Can not delete file",Toast.LENGTH_SHORT).show();
}
});
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
below code will get the selected item text automatically
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
// Log.d("TEST","selection is ");
String item = adapterView.getItemAtPosition(i).toString();
Toast.makeText(getApplicationContext(),"Inside"+item,Toast.LENGTH_SHORT).show();
}
I have An Activity where i retrieve messages that are communicated by the Users. I want to Delete a selected message on Long click.
Here is my code, the Copy to clipboard function is working fine but the delete is giving me a hard time.
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MyMessageViewHolder>{
private ArrayList<Messages> arrayListMessages= new ArrayList<>();
private Context mcontext;
FirebaseAuth mAuth;
private DatabaseReference mUserDatabase;
public ArrayAdapter adapter;
public MessageAdapter(Context context, ArrayList<Messages> arrayListMessages){
this.arrayListMessages = arrayListMessages;
mcontext = context;
}
#Override
public MyMessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.message_single_layout, parent,false);
return new MyMessageViewHolder(view);
}
#Override
public void onBindViewHolder(final MyMessageViewHolder holder, final int position) {
mAuth = FirebaseAuth.getInstance();
String mCurrentUser = mAuth.getCurrentUser().getUid();
final Messages messages = arrayListMessages.get(position);
String message_type = messages.getType();
String from_user = messages.getFrom();
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(from_user);
if(mCurrentUser.equals(messages.getFrom())){
holder.textViewMessage.setBackgroundResource(R.drawable.custom_message_bg_primary);
holder.textViewMessage.setTextIsSelectable(true);
holder.textViewMessage.setGravity(Gravity.RIGHT);
holder.textViewMessage.setTextColor(Color.WHITE);
holder.textViewMessage.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view)
{
CharSequence options[] = new CharSequence[]{"Delete", "Copy Text"};
final AlertDialog.Builder builder = new AlertDialog.Builder(mcontext);
builder.setTitle("Select Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Click Event for each item.
if (i == 0) {
String selectedItem = messages.getMessage();
arrayListMessages.remove(selectedItem);
Toast.makeText(mcontext, "Message deleted", Toast.LENGTH_SHORT).show();
}
if (i == 1)
{
ClipboardManager cm = (ClipboardManager) mcontext.getSystemService(Context.CLIPBOARD_SERVICE);
cm.setText(holder.textViewMessage.getText());
Toast.makeText(mcontext, "Copied to clipboard", Toast.LENGTH_SHORT).show();
}
}
});
builder.show();
return true;
}
});
}else{
holder.textViewMessage.setBackgroundResource(R.drawable.custom_message_bd_white);
holder.textViewMessage.setTextIsSelectable(true);
holder.textViewMessage.setGravity(Gravity.LEFT);
holder.textViewMessage.setTextColor(Color.BLACK);
holder.textViewMessage.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
CharSequence options[] = new CharSequence[]{"Delete", "Copy Text"};
final AlertDialog.Builder builder = new AlertDialog.Builder(mcontext);
builder.setTitle("Select Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Click Event for each item.
if (i == 0) {
String selectedItem = messages.getMessage();
arrayListMessages.remove(selectedItem);
adapter.notifyDataSetChanged();
Toast.makeText(mcontext, "Message deleted", Toast.LENGTH_SHORT).show();
}
if (i == 1)
{
ClipboardManager cm = (ClipboardManager) mcontext.getSystemService(Context.CLIPBOARD_SERVICE);
cm.setText(holder.textViewMessage.getText());
Toast.makeText(mcontext, "Copied to clipboard", Toast.LENGTH_SHORT).show();
}
}
});
builder.show();
return true;
}
});
}
holder.textViewMessage.setText(messages.getMessage());
if(message_type.equals("text")) {
holder.textViewMessage.setText(messages.getMessage());
holder.messageImage.setVisibility(View.INVISIBLE);
} else {
holder.textViewMessage.setVisibility(View.INVISIBLE);
Picasso.with(holder.UserProfile.getContext()).load(messages.getMessage())
.placeholder(R.drawable.my_profile).into(holder.messageImage);
}
}
private void copyText() {
}
#Override
public int getItemCount() {
return arrayListMessages.size();
}
class MyMessageViewHolder extends RecyclerView.ViewHolder{
TextView textViewMessage;
CircleImageView UserProfile;
ImageView messageImage;
public MyMessageViewHolder(View itemView) {
super(itemView);
textViewMessage = itemView.findViewById(R.id.messageTextView);
UserProfile = itemView.findViewById(R.id.message_profile_layout);
messageImage = (ImageView) itemView.findViewById(R.id.message_image_layout);
}
}
}
Is there any suggestions on how can i enable the delete function on the selected item? Thanks in advance...
Be aware that you shouldn't use setOnLongClickListener in the onBindViewHolder method never. Try moving it to the MyMessageViewHolder constructor.
like this:
public MessageAdapter(Context context, ArrayList<Messages> arrayListMessages){
this.arrayListMessages = arrayListMessages;
mcontext = context;
mAuth = FirebaseAuth.getInstance();
}
class MyMessageViewHolder extends RecyclerView.ViewHolder {
TextView textViewMessage;
CircleImageView UserProfile;
ImageView messageImage;
public MyMessageViewHolder(View itemView) {
super(itemView);
textViewMessage = itemView.findViewById(R.id.messageTextView);
UserProfile = itemView.findViewById(R.id.message_profile_layout);
messageImage = (ImageView) itemView.findViewById(R.id.message_image_layout);
String mCurrentUser = mAuth.getCurrentUser().getUid();
final Messages messages = arrayListMessages.get(getLayoutPosition());
String message_type = messages.getType();
String from_user = messages.getFrom();
mUserDatabase =
FirebaseDatabase.getInstance().getReference().child("Users").child(from_user);
textViewMessage.setOnLongClickListener(new View.OnLongClickListener() {
#Override public boolean onLongClick(View view) {
if (mCurrentUser.equals(messages.getFrom())) {
...
} else {
...
}
}
}
}
}