Facing the problem from updating the data and delete data in android - java

I'm trying to learn the android and need your help!
Problem 1:
I store my data with ".push()" . How do I update the data on the random number that I declared with ".push()".
Once I update that only create new data but not a data update
Problem 2
Once I delete the data will delete whole data but not only the specific data.
This is my timetable.java.
public class Timetable extends AppCompatActivity{
//View
RecyclerView timeTable;
RecyclerView.LayoutManager layoutManager;
DatabaseReference counterRef,currentRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ttable);
timeTable = (RecyclerView)findViewById(R.id.timeTable);
timeTable.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
timeTable.setLayoutManager(layoutManager);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolBar);
toolbar.setTitle("Time Table");
setSupportActionBar(toolbar);
counterRef = FirebaseDatabase.getInstance().getReference("Time");
currentRef = counterRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
//online list here
updateList();
}
private void updateList() {
FirebaseRecyclerAdapter<Time, ListTimeViewHolder> adapter = new FirebaseRecyclerAdapter<Time, ListTimeViewHolder>(
Time.class,
R.layout.time_table,
ListTimeViewHolder.class,
currentRef
) {
#Override
protected void populateViewHolder(final ListTimeViewHolder viewHolder, final Time model, int position) {
viewHolder.txtEmail.setText("Time (" +model.getTime()+ ")");
viewHolder.itemClickListenener1 = new ItemClickListenener1() {
#Override
public void onClick(View view, int position) {
showUpdateDeleteLog(model.getEmail(),model.getTime());
//alert dialog
// AlertDialog alertDialog = new AlertDialog.Builder(Timetable.this).create();
//
// // Setting Dialog Title
// alertDialog.setTitle("Message");
//
// // Setting Dialog Message
// alertDialog.setMessage("Unable to click");
//
// alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // Write your code here to execute after dialog closed
// Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_SHORT).show();
// }
// });
//
// // Showing Alert Message
// alertDialog.show();
}
private void showUpdateDeleteLog(String email, String time) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(Timetable.this);
LayoutInflater inflater = getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.update_dialog, null);
dialogBuilder.setView(dialogView);
final EditText editTextName = (EditText) dialogView.findViewById(R.id.editTextName);
final Button buttonUpdate = (Button) dialogView.findViewById(R.id.buttonUpdateArtist);
final Button buttonDelete = (Button) dialogView.findViewById(R.id.buttonDeleteArtist);
dialogBuilder.setTitle(email);
final AlertDialog b = dialogBuilder.create();
b.show();
buttonUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = editTextName.getText().toString().trim();
if (!TextUtils.isEmpty(name)) {
updateArtist(model.getEmail(),name);
b.dismiss();
}
}
});
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deleteArtist(model.getEmail(),model.getTime());
b.dismiss();
}
});
}
private boolean deleteArtist(String email, String time) {
//getting the specified artist reference
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("Time").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
//removing artist
dR.removeValue();
Toast.makeText(getApplicationContext(), "Time is deleted", Toast.LENGTH_LONG).show();
return true;
}
private boolean updateArtist(String email, String time) {
//getting the specified artist reference
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("Time").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
//updating artist
Time artist = new Time(email,time);
dR.push().setValue(artist);
Toast.makeText(getApplicationContext(), "Time is updated", Toast.LENGTH_LONG).show();
return true;
}
};
}
};
adapter.notifyDataSetChanged();
timeTable.setAdapter(adapter);
}
}
Thanks for help! I'm newbie in Android need pro to help me up! Thanks guys and this platform!

First of all, why do you need to push() after Uid? As Uid is always unique, you can remove that to easily access the child node like below:
-Time
-UID
-email
-time
Problem 1: I store my data with ".push()" . How do I update the data on the random number that I declared with ".push()".
You need to get the reference of that particular node to update. For that, you can store the push Id along with email and time. Also, you don't need to push while updating.
private boolean updateArtist(String email, String time) {
//getting the specified artist reference
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("Time").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child(timeModel.getPushId());
//updating artist
Time artist = new Time(email,time);
dR.updateChildren(artist); // instead use updateChildren
Toast.makeText(getApplicationContext(), "Time is updated", Toast.LENGTH_LONG).show();
return true;
}
Once I delete the data will delete whole data but not only the specific data
Same goes for problem 2, you need that particular node to delete,
private boolean deleteArtist(String email, String time) {
//getting the specified artist reference
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("Time").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child(timeModel.getPushId());
//removing artist
dR.getRef().removeValue();
Toast.makeText(getApplicationContext(), "Time is deleted", Toast.LENGTH_LONG).show();
return true;
}

Related

Combining Spinner and Button onClick Listener is giving me a Null Pointer exception

I have an app where a person will be allowed to post an announcement. The person has to select on the spinner the category of their announcement and type their announcement on an EditText. After entering both these fields the Button will allow the person to make the Announcement but if the spinner value or the EditText Value is empty an Error should be generated. I tried making the button invisible for the person typing the Announcement because i was getting a Null Pointer Exception but after switching to, making the button invisible I still get the same Error. This is my Code:
public class MakeAnnouncements extends AppCompatActivity {
private EditText announcement;
private Button announce_button;
private ProgressDialog announcementDialog;
private DatabaseReference mRootRef;
private FirebaseAuth mAuth;
private String mCurrentUserId;
private String announcer;
private String []SPINNERCATEGORY ={"General","Cubs","Scouts","Seniors"};
private String category_text;
private MaterialBetterSpinner betterSpinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_announcements);
announcementDialog = new ProgressDialog(this);
mRootRef = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
mCurrentUserId = mAuth.getCurrentUser().getUid();
announcement = (EditText)findViewById(R.id.announce_text);
announce_button = (Button)findViewById(R.id.announce_btn);
announce_button.setVisibility(View.VISIBLE);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,SPINNERCATEGORY);
betterSpinner = (MaterialBetterSpinner)findViewById(R.id.category_spinner);
betterSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
String spinner_value= adapterView.getItemAtPosition(position).toString();
if(position==0){
// no item selected show Toast message
announce_button.setVisibility(View.INVISIBLE);
} else{
announce_button.setVisibility(View.VISIBLE);
// item selected
}
category_text = spinner_value;
return;
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
announce_button.setVisibility(View.INVISIBLE);
}
});
betterSpinner.setAdapter(arrayAdapter);
mRootRef.child("Users").child(mCurrentUserId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
announcer = dataSnapshot.child("name").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
announce_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) { //<----- This is where i am getting a null point exception
String announced_text = announcement.getText().toString().trim();
String choosen_category = category_text.trim();
if (TextUtils.isEmpty(announced_text)){
announcement.setError("You did not type any announcement");
return;
}
announcementDialog.setTitle("Posting Announcement...");
announcementDialog.setMessage("Please wait...");
announcementDialog.setCanceledOnTouchOutside(false);
announcementDialog.show();
PostAnnouncement(announced_text,choosen_category);
}
});
}
private void PostAnnouncement(String announced_text, String choosen_category) {
DatabaseReference chat_push_key = mRootRef.child("Announcements").child(announcer).push();
String push_key = chat_push_key.getKey();
Map messageMap = new HashMap();
messageMap.put("announcement",announced_text);
messageMap.put("type","text");
messageMap.put("category",choosen_category);
messageMap.put("from",announcer);
messageMap.put("time", ServerValue.TIMESTAMP);
Map messageUserMap = new HashMap();
messageUserMap.put( "Announcements" + "/" + push_key, messageMap);
announcement.setText("");
announcementDialog.hide();
Toast.makeText(getApplicationContext(), "Your announcement was successfully posted",Toast.LENGTH_LONG).show();
mRootRef.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError != null){
Log.d("CHAT_LOG", databaseError.getMessage().toString());
}
}
});
}
}
What am i required to do to validate if the spinner Value is not empty?
According to your code you can check on the variable category_text.
if(TextUtils.isEmpty(category_text)){
//Show your error message
}
After checking for possible ways to solve this This Link assisted me.
I first changed the spinner_value to be a global variable. Then wrote this code:
String announced_text = announcement.getText().toString().trim();
String choosen_category = null;
if (TextUtils.isEmpty(announced_text)){
announcement.setError("You did not type any announcement");
return;
}
if(spinner_value != null){
choosen_category = spinner_value.trim();
return;
}
else if(spinner_value == null){
betterspinner.setError("This section must be selected before proceeding");
return;
}
After that i removed button Visibilities that are in my initial code.

Firebase database is updating but Android ListView containing data is not

I have implemented an spinner in an Alert Dialog with an update button that is successfully updating my Firebase database. This was achieved using help here - Updating Firebase records that are displayed in an Android ListView
However, these updates in data are not being reflected in the ListView that is displaying the Firebase data, they are just staying the same.
Can anyone help me show these in my ListView?
Here is my showProgressDialog:
private void showProgressDialog(final String id, String title, String description, String property, String maintenanceTitle) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.archive_maintenance, null);
dialogBuilder.setView(dialogView);
final Spinner spinnerProgress = (Spinner) dialogView.findViewById(R.id.spinnerProgress);
final Button buttonUpdateProgress = (Button) dialogView.findViewById(R.id.buttonUpdateProgress);
dialogBuilder.setTitle("Maintenance: " + maintenanceTitle);
final AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
buttonUpdateProgress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = editTextTitle.getText().toString().trim();
String desc = editTextDesc.getText().toString().trim();
String progress = spinnerProgress.getSelectedItem().toString();
String property = spinnerProperty.getSelectedItem().toString();
updateProgress(title, desc, id, property, progress);
alertDialog.dismiss();
}
});
And my updateProgress method:
private boolean updateProgress (String title, String desc, String id, String property, String progress) {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("maintenance");
FirebaseUser user = mAuth.getCurrentUser();
String uid = user.getUid();
Map<String, Object> params = new HashMap<>();
params.put("progress", progress);
databaseReference.child(uid)
.child(id)
.updateChildren(params);
Toast.makeText(this, "Maintenance Updated Updated Successfully", Toast.LENGTH_LONG).show();
return true;
}
As you can see from my data structure, the node progess has changed to complete, but it is the maintenanceProgress that needs to be done. The progress is changed by a Spinner and then an OK Button.
Any help would be greatly appreciated.

Retrieve data from database to my app (NOT WORKING)

so i am trying to retrieve data stored in my database.
basically the user inputs a car registration number and a rating (between 1-5)and click button. once the button is clicked my code will execute. which gets text from both editext and send to my server. i have php file saved, which will check if the carregistration number matches the value in the databse. if it matches retrieve the current rating stored in the database. the value is then showed on another acitivity. The php file works fine. i tried by inserting value manually. the problem i have is that when the button is clicked nothign happens. i have used this code to retrieve user name and other details on another app.
dataretrieve.java
public class DataRetrieve extends StringRequest {
private static final String REGISTER_REQUEST_URL = "https://dipteran-thin.000webhostapp.com/Login1.php";
private Map<String, String> params;
public DataRetrieve (String carreg, int rating, Response.Listener<String> listener) {
super(Method.POST, REGISTER_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("carreg", carreg);
params.put("rating", rating + "");
}
#Override
public Map<String, String> getParams() {
return params;
}
}
Profile.java (where the user inputs carreg and rating)
public class Profile extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
final EditText editText = (EditText) findViewById(R.id.carreg);
final EditText editText1 = (EditText) findViewById(R.id.editText3);
Button button = (Button) findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String carreg = editText.getText().toString();
final int rating = Integer.parseInt(editText1.getText().toString());
// Response received from the server
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
int rating = jsonResponse.getInt("rating");
Intent intent = new Intent(Profile.this, UserAreaActivity.class);
intent.putExtra("rating", rating);
Profile.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
DataRetrieve loginRequest = new DataRetrieve(carreg, rating, responseListener);
RequestQueue queue = Volley.newRequestQueue(Profile.this);
queue.add(loginRequest);
}});
}
}
userareaactivity.java (where value is shown when retrieved)
public class UserAreaActivity extends AppCompatActivity {
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_area);
final TextView etusername = (TextView) findViewById(R.id.textView2);
final TextView etwelcome = (TextView) findViewById(R.id.textView);
final TextView etuname = (TextView) findViewById(R.id.textView3);
final Button Logout = (Button) findViewById(R.id.logout);
//String Name = SharedPreferenceUtils.getName(this);
//etwelcome.setText(Name);
Intent intent = getIntent();
username = intent.getIntExtra("rating", -1);
etusername.setText(username + "");
//Intent in = new Intent(getApplicationContext(), Messages.class);
//in.putExtra("username", username);
//UserAreaActivity.this.startActivity(in);
}
#Override
public void onBackPressed(){
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
Intent intent = new Intent(UserAreaActivity.this, Messages.class);
UserAreaActivity.this.startActivity(intent);
}
return true;
}
I'm getting an error from your php page:
<b>Parse error</b>: syntax error, unexpected ']' in <b>/storage/ssd1/526/2972526/public_html/Login1.php</b> on line <b>8</b><br />
You can see the output of your response in the log by using this line above your JSON parsing (before it throws the exception)
Log.d("Response", response.toString());
I copied your success block into the exception block and it works as expected, so that code is valid. I would also put some kind of alert in the catch to let you know the failure happened when you're done testing.
Side note, change your parameter line to this...it's cleaner:
params.put("rating", String.valueOf(rating));

Variables losing data between activities and I don't know why?

I am currently creating an android app that scans a network and outputs results in a ListView but I am trying to make it to where I tap on the network and it saves the data in a database then sends you to a page to show you what you selected but when I click an item it substrings the values correctly and displays work fine on the main activity but when I try to use the variables on my display page activity there values are set null.
Here is the main activity in the click listener:
networklist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String grabItemInfo = wifis[position];
Network_Info info1 = new Network_Info();
info1.setMainBSSID( grabItemInfo.substring(grabItemInfo.indexOf('#') +1, grabItemInfo.lastIndexOf('#')));
info1.setMainSSID( grabItemInfo.substring(0,(grabItemInfo.indexOf('#'))));
info1.setMainCAP( grabItemInfo.substring(grabItemInfo.lastIndexOf('#')+1, grabItemInfo.length()));
Toast toastTest = Toast.makeText(getApplicationContext(), info1.getMainSSID(), Toast.LENGTH_SHORT);
Toast toastTest2 = Toast.makeText(getApplicationContext(), info1.getMainBSSID(), Toast.LENGTH_SHORT);
Toast toastTest3 = Toast.makeText(getApplicationContext(), info1.getMainCAP(), Toast.LENGTH_SHORT);
toastTest.show();
toastTest2.show();
toastTest3.show();
ContentValues dbv = new ContentValues();
dbv.put("SSID", info1.getMainSSID());
dbv.put("BSSID", info1.getMainBSSID());
dbv.put("CAPABILITIES", info1.getMainCAP());
netDataBase.insert("netDataTable", "NULL", dbv);
Intent intent = new Intent(getApplicationContext(), Attack_Page.class);
startActivity(intent);
}
});
Here is my display page:
public class Attack_Page extends Network_List {
protected void onCreate(Bundle SavedIS){
super.onCreate(SavedIS);
setContentView(R.layout.attack_page);
TextView SSIDview = (TextView) findViewById(R.id.SSIDView);
TextView BSSIDview = (TextView) findViewById(R.id.BSSIDView);
TextView CAPview = (TextView) findViewById(R.id.CAPView);
Button backButton = (Button) findViewById(R.id.backbutton);
Intent intent = getIntent();
//String MainSSIDP = intent.getStringExtra(getMainSSID());
Network_Info info1 = new Network_Info();
Toast testToast = Toast.makeText(getApplicationContext(), info1.getMainSSID(), Toast.LENGTH_SHORT);
testToast.show();
//Cursor IDselect = netDataBase.rawQuery("SELECT SSID FROM netDataTable WHERE SSID = "+getMainSSID()+"", wifis);
//SSIDview.setText(IDselect.toString());
backButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent bintent = new Intent(getApplicationContext(), Network_List.class);
startActivity(bintent);
}
});
}
}
Here is my setters and getters class:
public class Network_Info {
private String mainCAP;
private String mainSSID;
private String mainBSSID;
public void setMainSSID(String newMainSSID){
mainSSID = newMainSSID;
}
public void setMainBSSID(String newMainBSSID){
mainBSSID = newMainBSSID;
}
public void setMainCAP(String newMainCAP){
mainCAP = newMainCAP;
}
public String getMainSSID(){
return mainSSID;
}
public String getMainBSSID(){
return mainBSSID;
}
public String getMainCAP(){
return mainCAP;
}
}
Figured out you have to pass the variable with the intent:
Intent intent = new Intent(getApplicationContext(), Attack_Page.class);
intent.putExtra("EXTRA_SSID", info1.getMainSSID());
intent.putExtra("EXTRA_BSSID", info1.getMainBSSID());
intent.putExtra("EXTRA_CAP", info1.getMainCAP());
startActivity(intent);
Then use the key that you set in putExtra()
String MainSSIDP = intent.getStringExtra("EXTRA_SSID");
Thanks for the help though!

Checking if a username and email are found in Parse database

In my application I have an activity called AddPatient this activity allows the user to enter either a username or a email and the if found the text view will display a text "Found" else "not found" and the button will allow the user to continue to the next activity just if the users found the mail and username already in database. This is my code but it's giving me found all the time and the button is not working....Any help please.
Note this activity extends AppCompatActivity:
EditText UserNameEt;
EditText EmailEt;
String email;
String username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_patient);
UserNameEt = (EditText) findViewById(R.id.et1);
EmailEt = (EditText) findViewById(R.id.et2);
username = UserNameEt.getText().toString();
email = EmailEt.getText().toString();
final TextView tv = (TextView) findViewById(R.id.tv);
ParseQuery<ParseObject> lotsOfWins = ParseQuery.getQuery("User");
lotsOfWins.whereEqualTo("email",email);
ParseQuery<ParseObject> fewWins = ParseQuery.getQuery("User");
fewWins.whereEqualTo("username", username);
List<ParseQuery<ParseObject>> queries = new ArrayList<ParseQuery<ParseObject>>();
queries.add(lotsOfWins);
queries.add(fewWins);
ParseQuery<ParseObject> query = ParseQuery.or(queries);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (true) {
tv.setText("Patient found");
} else {
tv.setText("Patient Not found");
}
}
});
String Result = tv.getText().toString();
if (Result=="Patient found"){
Button fill = (Button) findViewById(R.id.button);
fill.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(AddPatient.this,Patients.class);
startActivity(i);
}
});
}
}
}
You're setting whether the patient has been found or not using if (true), which is obviously always going to be true. You need to replace that with something that checks whether the entered value actually exists.
i would like to try on this way.
first set this method.
1st Method.
ParseQuery<ParseObject> lotsOfWins =new ParseQuery<ParseObject>("User");
lotsOfWins.whereEqualTo("email", email);
ParseQuery<ParseObject> fewWins = new ParseQuery<ParseObject>("User");
fewWins.whereEqualTo("username", username);
List<ParseQuery<ParseObject>> queries = new ArrayList<ParseQuery<ParseObject>>();
queries.add(lotsOfWins);
queries.add(fewWins);
ParseQuery<ParseObject> query = ParseQuery.or(queries);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
if (objects.size() > 0) {
tv.setText("Patient found");
} else {
tv.setText("Patient Not found");
}
getPatientInfo(tv.getText().toString());
} else {
// error
}
}
});
2nd this method.
protected void getPatientInfo(String Result) {
// TODO Auto-generated method stub
if (Result == "Patient found") {
Button fill = (Button) findViewById(R.id.button);
fill.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(AddPatient.this, Patients.class);
startActivity(i);
}
});
}
}
this type do for findInBackGround is one type of thread.

Categories

Resources