Remove data that was previously added in App - java

Hello so I have this Java code for an address book app on android studio where I have the add button so whatever name I type, it gets added into the address book app. I made a delete button so whatever name I type in, if it is already added, it will delete it from the address book data. How would I get the delete button to work
public void btnAddData(View v)
{
String name= firstName.getText().toString();
String surName= lastName.getText().toString();
String phone1= phone.getText().toString();
Person person= new Person();
person.name=name;
person.surname=surName;
person.phone=phone1;
persons.add(person);
setTextToTextView();
}
public void btnRemoveData(View v)
{
//code to delete name
}
private void setTextToTextView()
{
String text = "";
for (int i=0;i<persons.size(); i++)
{
text=text + persons.get(i).name+","+persons.get(i).surname+","+persons.get(i).phone+"\n";
}
results.setText(text);
}

You would do this :-
persons.remove(<index or object name>);

You can find it using loop and then remove it.
public void btnRemoveData(View v)
{
String name= firstName.getText().toString();
for (int i=0;i<persons.size(); i++)
{
if(persons.get(i).name.equals(name)) persons.remove(i);
}
}

Related

List not Updating in android after String is spoken through SpeechRecognizer

So, i am creating a virtual assistant app which after listening to user suppose to update the ui and then take another input but it updating the ui at once and then listening and speaking at once and taking no input
messageHolder = "The Global text get from Recognizer";
private void sendChatMessage(boolean side){
if(side != true){
tts.speak(messageHolder,TextToSpeech.QUEUE_ADD,null);
}
chatArrayAdapter.add(new ChatMessage(side,messageHolder));
chatArrayAdapter.notifyDataSetChanged();
}
startSpeechToText() -> get the result from the speechrecognizerIntent
private class SeprateQuery extends AsyncTask<String,String,query>{
#Override
protected query doInBackground(String... strings) {
String v_query = strings[0].toString();
Log.e("APP","String recieved inn seprateQuery and is"+v_query);
if(v_query.indexOf("create contact")!=-1){
v_query = v_query.replace("create contact ","");
return new query(4,v_query);
return new query(-1,"null");
}
#Override
protected void onPostExecute(query code) {
super.onPostExecute(code);
if(code.code==4){
messageHolder = "Enter the name";
sendChatMessage(false);
startSpeechToText(speechRecognizerIntent,false);
String name = messageHolder;
messageHolder = "Enter the number";
sendChatMessage(false);
startSpeechToText(speechRecognizerIntent,false);
String contact = messageHolder;
addContact(name,contact);
//addContact(name,contact);
}else
is there any way i can perform the code in onPostExecute procedurally one by one instead ui updating at once without listening to users

Access Variables From Other Class With Getter Setter JAVA

I'm getting problem with accessing variables with getter & setter on multiple classes. I looked up this one but I'm too confused.
I have 3 type users: Admin (Position No: 0 in mysql table), Manager (Position No: 1), Clerk (Position No:2).
I have SeeReportsAndFeedbacks class. I want to show all reports by selecting rows with position_no = 0 and 1 to admin and manager, 2 to clerk. It's already done with if statement.
So clerk can see only see reports that with position_no=2
manager can see only see reports that with position_no=0 and 1
admin can see only see reports that with position_no=0 and 1
Please help me. I'm stucked here for a long time. What are wrong with my getter setters?
If i set on Login_Form, and call get it shows correct in girisyap() function but if i call get in other class named SeeReportsAndFeedbacks it shows first initial value from Users () constructor instead of set value on girisyap() function on Login_Form.
tip value takes position_no from mysql db as string, new1 value is parsing (converting) string to int for if statement
screenshot
GIST
Users Class
public class Users {
private int id;
private String username;
private String fullname;
private String password;
private String phone;
private String gender;
private byte[] image;
private int position_no;
public Users () {
setPno(1); //firsst initialize
//getFullname();
}
public Users (int uid ,String uname, String fname, String upassword, String uphone, String ugender, byte[] uimage, int pno){
this.id = uid;
this.username = uname;
this.fullname = fname;
this.password = upassword;
this.phone = uphone;
this.gender =ugender;
this.image =uimage;
this.position_no = pno;
}
public Users (int pno){
setPno(pno);
}
public int getPno(){
return position_no;
}
public void setPno(int pno){
this.position_no = pno;
}}
SeeReportsAndFeedbacks class (i removed not-related funcs or some other gui things for the question.
public class SeeReportsAndFeedbacks { // extends javax.swing.JFrame
//CLIENT client = new CLIENT();
int new1 = 9999; //testing something
int PositionNoGetiren;
//sers loginf = new Users(0, null,null,null,null,null,null,new1);
public SeeReportsAndFeedbacks() {
//initComponents();
Users loginf = new Users();
PositionNoGetiren = loginf.getPno(); //gets initial value instead of set value on login_form
System.out.println("Babakingg " + PositionNoGetiren);
//int ananas = loginf.getPno();
//fillFeedbackJTable(jTable2);
}
public void fillReportJTable(){//JTable table
//loginf.setPno(2); it works if i manually set but it's useless
//System.out.println("Loginfvalue in see reports: " + loginf.getPno() + loginf.getUsername());
//new1 = loginf.getPno(); //not works shows 0
//see.getNo();
new1=PositionNoGetiren;
String selectQuery = "SELECT * FROM `users` WHERE `position_no` = ?";
if(new1==0){//admin
selectQuery = "SELECT * FROM `reports`";
}
if(new1==1){//manager
selectQuery = "SELECT * FROM `reports` WHERE `position_no` = 1";
}
if(new1==2){//clerk
selectQuery = "SELECT * FROM `reports` WHERE `position_no` = 2";
}
//}
}}
Login_Form
public class Login_Form {
int positionNoGetiren;
/**
* Creates new form Login_Form
*/
public Login_Form() {
//initComponents();
//positionNoGetiren = 9999;
}
private void girisyap() {
//I DELETED ALL DATABASE RELATED THINGS FOR QUESTION.
//String tip = rs.getString("position_no"); //DETECTS CORRECTLY POSITION NO FROM DATABASE
String tip = "IT'S rs.getString(\"position_no\")"; //for posting question
System.out.println(tip);
int new1 = Integer.parseInt(tip);
//Users loginf = new Users(new1); //welcome yazisi icin
Users loginf = new Users(); //ONLY WORKS IN THIS CLASS.
loginf.setPno(new1); //set user type for reports class BUT IT'S NOT WORKING
System.out.println("Loginf degeri login_formdaki: " + loginf.getPno());
//THIS IF IS WORKING CORRECTLY.
if(new1==0){
//Admin form = new Admin();
//form.setVisible(true);
//form.pack();
//form.setLocationRelativeTo(null);
// form.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
if(new1==1){
//Manager form = new Manager();
//form.setVisible(true);
//form.pack();
//form.setLocationRelativeTo(null);
}
if(new1==2){
//Clerk form = new Clerk();
//form.setVisible(true);
//form.pack();
//form.setLocationRelativeTo(null);
// form.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
//this.dispose();
}
private void jButton_LoginActionPerformed(java.awt.event.ActionEvent evt) {
girisyap();}
}
There is nothing wrong with your getters and setters.
This is most likely an issue with parsing the value of TIP, that could not be parsed as an INT, maybe its a float with a weird value of like 2.00000004, or simply null. Try writing a test or log the value which your query return and check if this is the value you are looking for.

User properties, random object without concord .. Why doesn't works? Why doesn't get 21 objects?

I have a complex problem, what I don't understand. In this class I would like to
add 21 random objects from one arraylist listChallenges to the arraylist finalChallenges. However it doesn't work , sometimes finalChallanges contains 21 objects , but most of the times it contains less objects, but I don't know where is the problem. Actually, I tried to comment every step, and if did something wrong, please tell me.
Please help me, I have no idea what shoud I do..
ArrayList<Challenges> listChallenges = new ArrayList<Challenges>();
ArrayList<Challenges> finalChallenges = new ArrayList<Challenges>(20);
//Check where the same userId and subscribers.objectId,
//Request these categories object and save to the ArrayList<Category> totalCategories
//Save these categories objectId to the selectedCategoriesId List<String>
BackendlessDataQuery query = new BackendlessDataQuery();
query.setWhereClause( "subscribers.objectId = '"+backendlessUser.getObjectId()+"'");
Backendless.Data.of(Category.class).find(query, new AsyncCallback<BackendlessCollection<Category>>() {
#Override
public void handleResponse(BackendlessCollection<Category> categoriesBackendlessCollection) {
//add selected categories to totalActivities Category ArrayList
for( Category categories : categoriesBackendlessCollection.getData()) {
totalCategories.add(categories);
selectedCategoriesId.add(categories.getObjectId());
//
}
System.out.println(selectedCategoriesId);
//For cycle is going to selectedCategoriesId.size
//Check where the same category-objectId and actual selectedCategoriesId
//Request these challenges object, which are in the actual category and save to the ArrayList<Challenges> listChallenges
//Save these categories objectId to the selectedCategoriesId List<String>
for(int k=0;k<selectedCategoriesId.size();k++) {
BackendlessDataQuery query = new BackendlessDataQuery();
query.setPageSize(pageSize);
query.setWhereClause("category.objectId = '" + selectedCategoriesId.get(k) + "'");
Backendless.Data.of(Challenges.class).find(query, new AsyncCallback<BackendlessCollection<Challenges>>() {
#Override
public void handleResponse(BackendlessCollection<Challenges> cha) {
for (Challenges challenges : cha.getData()) {
listChallenges.add(challenges);
challengeTitle.add(challenges.getChallengeTitle());
challengeContent.add(challenges.getChallengeContent());
challangeId.add(challenges.getObjectId());
}
System.out.println("osszes elem:"+listChallenges);
//ArrayList<Challenges> finalChallenges size is 21 with 0
// get from listChallenges random 21 object without concord and add to the finalChallenges
Random random = new Random();
List<Challenges> temp = new ArrayList<>(listChallenges);
ArrayList<Challenges> tempNewList = new ArrayList<Challenges>();
//ArrayList<Challenges> temp = new ArrayList<Challenges>(listChallenges.size());
for (Challenges item : listChallenges) temp.add(item);
while (finalChallenges.size()<21 && temp.size()>0) {
int index = random.nextInt(temp.size());
tempNewList.add(temp.get(index));
temp.remove(index);
finalChallenges= tempNewList;
}
// System.out.println("kihívások");
System.out.println(finalChallenges);
System.out.println(finalChallenges.size());
// title.setText(challengeTitle.get(0));
// content.setText(challengeContent.get(0));
// objectId = challangeId.get(0);
}
#Override
public void handleFault(BackendlessFault fault) {
}
});
//save finalChallenges array objects to the current user "userChallenges" relationship
Backendless.UserService.login( email, password, new AsyncCallback<BackendlessUser>() {
#Override
public void handleResponse(BackendlessUser backendlessUser) {
backendlessUser.setProperty("userChallenges",new ArrayList<>(finalChallenges));
}
});
Backendless.UserService.update(backendlessUser, new BackendlessCallback<BackendlessUser>() {
#Override
public void handleResponse(BackendlessUser response) {
System.out.println( "User has been updated" );
}
#Override
public void handleFault(BackendlessFault fault) {
System.out.println( "User has not been updated");
}
});
}
#Override
public void handleFault(BackendlessFault backendlessFault) {
System.out.println( "Server reported an error - " + backendlessFault.getMessage() );
}
},true);
}
}
#Override
public void handleFault(BackendlessFault fault) {
}
});
You don't show where finalChallenges is initialized, and we can see it is overwritten asynchronously in response handlers: it is very likely an issue of concurrent access.
The logic itself where you fill the list from random elements of another list would be correct, if the instance of finalChallenges was not "shared" across different/concurrent executions of that handler.
Also, a small tip: to create your temp list in one go without loop you can do this: List<Challenge> temp = new ArrayList<>(listChallenges);
Edit: 2 suggestions.
Use a temporary list in your loop when you fill it, then swap the lists atomically (listChallenges = tempNewList)
When you pass your list to user properties, pass a copy (backendlessUser.setProperty("userChallenges", new ArrayList<>(finalChallenges));)

Java, Generating a dynamic object name [duplicate]

This question already has answers here:
Assigning variables with dynamic names in Java
(7 answers)
Closed 8 years ago.
I was trying to generate a dynamic object names that will change everytime an object is created. Something like:
first object name would be like "userName" and the following would be like "userName1".
I'm new to java, and I tried to initialize int count=0 and count++ to do it, but the User class doesn't seem to allow me to do that like userName+count. Therefore, is there anyway i could possible go about doing it?
I have search through all the similar thread about dynamic object name, but it doesn't seems to work out for my case.
EDIT
So i have this app built up, that allow user to create account.
And, now i encounter this problem where whenever i tried to create new account,
Firebase clear away all my previous data that i have inserted, and replace it with the current inserted data.
Here's my code:
Main.java
name = (EditText) findViewById(R.id.edit_rName);
email = (EditText) findViewById(R.id.edit_rEmail);
password = (EditText) findViewById(R.id.edit_rPassword);
Button btnSubmit = (Button) findViewById(R.id.btn_rSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Firebase f = new Firebase("https://xxx.firebaseio.com/");
Firebase usersRef = f.child("users");
Map<String, User> users = new HashMap<String, User>();
users.put(name.getText().toString(), new User(name.getText().toString(), password
.getText().toString(), email.getText().toString()));
usersRef.setValue(users);
}
});
User.java
public class User {
private String fullName;
private String password;
private String email;
public User(String fullName, String password,String email) {
this.fullName = fullName;
this.password = password;
this.email = email;
}
public String getPassword() {
return password;
}
public String getFullName() {
return fullName;
}
}
You should use an array if you know in advance how many objects you will create, and a list if you don't know in advance.
Array:
String[] usernames = new String[4];
usernames[0] = "Alex";
usernames[1] = "Bob";
usernames[2] = "Carol";
usernames[3] = "David";
//usernames[4] = "Eliza"; // won't work, out of bounds!
System.out.println(usernames[2]); //prints Carol
List(recommended) (first import java.util.ArrayList):
List<String> usernames = new ArrayList<String>();
usernames.add("Alex");
usernames.add("Bob");
usernames.add("Carol");
usernames.add("David");
usernames.add("Eliza");
System.out.println(usernames.get(2)); // prints Carol
usernames.set(2, "Carlos");
System.out.println(usernames.get(2)); // prints Carlos

Trying to pass information from 4 fields in an Android app to a String in java for testing connection prior to saving the information

I'm programing an android app that connects to a MySQL server, so far I have it so the user can enter the server ip, database name, user name and password and store it to the phone. I am trying to build a string off the info the user just entered to test the connection prior to saving to the .txt files. I know it's probably right in front of my face but after a day of this I'm stuck, please help!! The problem is located in the 'TestButtonListener'
public class AppInfo extends Activity {
public static final String DEBUGTAG = "It's Broke";
public static final String DATABASEPASSWORD = "pinfo.txt";
public static final String SERVERIP = "sinfo.txt";
public static final String DATABASEUSER = "ninfo.txt";
public static final String DATABASE = "dinfo.txt";
public static final String FILESAVED = "filesaved";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_info);
addTestButtonListener();
///Test connection
private void addTestButtonListener() {
Button test = (Button) findViewById(R.id.testcon);
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
///need information from the R.id.server, R.id.database, R.id.name, R.id.pword
/// and insert it into the string as serverIp, dataBase, name, pword.
///
try {
/// everything I've tried in here spits out the name of the text file,
/// or the memory address, but not the value just typed in.
}
String serverConnect = new String("jdbc:mysql://" + serverIp
+ "/" + dataBase + ", " + name + ", " + pword);
Toast.makeText(AppInfo.this, serverConnect, Toast.LENGTH_LONG)
.show();
}
});
}
Don't bother, I figured out how to fix it with .getText().toString() and after all that come to find out Android DOES NOT WORK with jdbc connector.

Categories