i have created an app which insert data to sql server. i made column NAME as unique key.
i want that if i enter same name by edittext to insert...it should give a toast message.
but it's not happening. i cann't understand where i have made error.
in connection to server there is no problem. the only thing is i have to display Toast msg if i entered same name again.
my code is.......
public void onClick(View v) {
// TODO Auto-generated method stub
String myloc=loc.getText().toString();
String myname=name.getText().toString();
String myphone=phone.getText().toString();
initilize();
ResultSet rs;
try{
Statement statement=connect.createStatement();
rs=statement.executeQuery("SELECT * FROM FORM1");
List<Map<String,String>>data=null;
data=new ArrayList<Map<String,String>>();
while(rs.next()){
Map<String,String>datanum=new HashMap<String,String>();
datanum.put("a", rs.getString("NAME"));
data.add(datanum);
}
if(data.contains(myname)){
Toast.makeText(c, myname+" Already stored: please choose different one", Toast.LENGTH_LONG).show();
}
else{
insert(myname,myphone,myloc);
}
}catch(Exception e){
Log.e("ERROR", e.getMessage());
}
}
plzz guys...help me someone...
With data.contains(myname) you are trying to check if there is myname of type String in your data varible, but, in fact, your data have type List<Map<String,String>>, so when you are invoking contains(Object object) method passing a String, you are performing equals operation between Map<String,String> and String, which clearly would always result false. So I would suggest you either write something like this
List<String> data = new ArrayList<String>();
while(rs.next()) {
data.add(rs.getString("NAME"));
}
if(data.contains(myname)){
Toast.makeText(c, myname+" Already stored: please choose different one", Toast.LENGTH_LONG).show();
}
or there is a better way, just change your query to SELECT * FROM FORM1 WHERE NAME = myname and check if your result set is empty.
Related
I have a listView that is created in onCreate method.As below, and read data from a Stored Procedure.
I Used CallabeStatement.
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.type_of_dairy);
try
{
CallableStatement catCallable;
ConnectionHelper connectionHelper = new ConnectionHelper();
catCallable = connectionHelper.getConnection().prepareCall("{ CALL SpGetDairyCategory}");
catCallable.execute();
resultSet = catCallable.getResultSet();
setResultSet(resultSet);
if(getResultSet().next()) {
do {
String typeString = resultSet.getString("CategoryName");
int typeId = resultSet.getInt("CategoryId");
integerArraList.add(typeId);
typeArray.add(typeString);
typeAdapter.getItemViewType(R.id.listView); // adapter for first ListView
dairyType.setAdapter(typeAdapter);//dairyType is my first List View
}while(resultSet.next());
}
}
catch (SQLException e)
{
Toast.makeText(getApplicationContext(), "Something is wrong", Toast.LENGTH_LONG).show();
}
In the above code, I got Id of Category Id and name,and passed them into two ArrayLists named integerArrayList and typeArray.
I generate the second ListView with the Id of category that i got from the above Stored Procedure.
I do it in dairyType(first ListView)onClickListener.
here is the code
dairyType.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
flavorAapter.clear();
CallableStatement proCallable;
ConnectionHelper connectionHelper = new ConnectionHelper();
proCallable = connectionHelper.getConnection().prepareCall("{call SpGetCategoryProducts(?)}");
proCallable.setInt(1, integerArraList.get(dairyType.getCheckedItemPosition())); //integerArrayList contains the categoryId from the first Store Procedure
resultSet2 = proCallable.executeQuery();
//The second Stored Procedure get the Id and return some value as you see
if (resultSet2.next()) {
do {
int flavourId;
int weitgh;
int price;
weitgh = resultSet2.getInt("Weight");
price = resultSet2.getInt("Price");
String flavourString = resultSet2.getString("Name");
flavourId = resultSet2.getInt("Id");
dairyArray.add(flavourString);
idOfCategories.add(flavourId);
weightArray.add(weitgh);
priceArray.add(price);
flavorAapter.getItemViewType(R.id.listView2);
dairyFlavour.destroyDrawingCache();
dairyFlavour.setAdapter(flavorAapter);
} while (resultSet2.next());
connectionHelper.closeConnection();
} else {
flavorAapter.clear();
Toast.makeText(getApplicationContext(), "Nothing to show", Toast.LENGTH_LONG).show();
}
} catch (SQLException e) {
Toast.makeText(getApplicationContext(), "Something wrong", Toast.LENGTH_LONG).show();
dairyArray.clear();
}
}
});
Ok, so i generate the second Listview sucessfully as i wanted,
the problem is in the insert Buttom,
Now i have ArrayList of Name, Weight, Price and Id.( I use Id as an argument that passes to last Stored Procedure.
So I have to call another Stored Procedure to insert all these data into DB(Name,Weight,Price)
But it doesnt insert the changed items values.
It means, i select an item from the first ListView,The second Listview generate and i choose one of them, but when i change my select in the first ListView, it still insert the id of first ListView.
here is my insert code via buttom named apply.
apply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
dairyFlavour.invalidateViews();
dairyType.invalidateViews();
typeAdapter.notifyDataSetInvalidated();
flavorAapter.notifyDataSetChanged();
int weight = weightArray.get(dairyFlavour.getCheckedItemPosition()); //weitgh from previous SP
int price = priceArray.get(dairyFlavour.getCheckedItemPosition()); //price from previous SP
String count = "";
int c;
count = countOfProduct.getText().toString(); // insert the count of product via editText
c = Integer.parseInt(count); // cast the cound to Integer
we = idOfCategories.get(dairyFlavour.getCheckedItemPosition());//the id i got in previous SP
CallableStatement callableStatement = null;
ConnectionHelper connectionHelper = new ConnectionHelper();
callableStatement = connectionHelper.getConnection().prepareCall("{call SpInsertLoadCityProducts(?, ?, ? ,?)}");
callableStatement.setInt(1, we);
callableStatement.setInt(2, weight);
callableStatement.setInt(3, price);
callableStatement.setInt(4, c);
callableStatement.executeQuery();
}catch(SQLException e){
Toast.makeText(getApplicationContext(), "Something is wrong", Toast.LENGTH_LONG).show()
}
Intent i = new Intent(getApplicationContext(), FinishLoading.class);
startActivity(i);
}
});
In view it is ok and as i change the first ListView the second ListView generated as desired.
But in insert, i only insert the first chose values into DB, and when i change the selection in the first ListView and choose another product in second ListView and click apply buttom, the first data is inserted.
Any Suggestion?
If you are confused ask question to make myself more clear !
I found the solution.
I should clear every ArrayList befor storing data.
when first time get index and data, i should clear ArrayList and again fill out them as below.
dairyTypes.clear();
integerArraList.clear();
typeArray.clear();
and also
flavorAapter.clear();
I am trying to add or update information in an SQLite database in Android.
The database takes a Lesson note id and a student id. If the lesson note id is 0, then a new entry is being made.
Here is what is in my Dbhelper class (for inserting, the update is fairly similar):
public boolean insertLessonNotes(LessonNotesData lData)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues lessonValues = new ContentValues();
//values.put(LESSON_ID, lData.getLessonID()); // Lesson ID
//values.put(ST_ID, lData.getStudentID()); // Student ID
//values.put(LESSON_IMAGE_ID, lData.getImageID()); // Lesson Image ID
//values.put(LESSON_IMAGE_NOTE, lData.getImageNote()); // Note attached to image
lessonValues.put(LESSON_ID, lData.getLessonID());
lessonValues.put(ST_ID, lData.getStudentID());
lessonValues.put(DATE, lData.getDate()); // Date note added
lessonValues.put(LESSON_READING, lData.getReadingNote()); // reading notes
lessonValues.put(LESSON_PHONICS, lData.getPhonicsNote()); // phoncis notes
lessonValues.put(LESSON_SPELLING, lData.getSpellingNote()); // spelling notes
lessonValues.put(LESSON_WRITING, lData.getWritingNote()); // writing notes
lessonValues.put(LESSON_COMMENTS, lData.getCommetns()); // comments notes
lessonValues.put(LESSON_HOMEWORK, lData.getHomework()); // homework notes
// Inserting Row
db.insert(TABLE_LESSON_NOTES, null, lessonValues);
db.close();
return true;
}
This is my lessonNotes class (where the information is entered and saved)
LessonNotesData lNote = new LessonNotesData(id_To_Update, student_id, lessonDate.getText().toString(), readNote.getText().toString(), phonNote.getText().toString(), spellNote.getText().toString(), writeNote.getText().toString(), commentNote.getText().toString(), homeworkNote.getText().toString());
Bundle extras = getIntent().getExtras();
int studentID = extras.getInt("studentId");
int lessonID = extras.getInt("lessonID");
Toast.makeText(getApplicationContext(), "LessonID is:(lessonNotes3) "+String.valueOf(lessonID), Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "StudentID is: (lessonNotes3) "+String.valueOf(studentID), Toast.LENGTH_SHORT).show();
//Bundle studentId = getIntent().getExtras();
if (lessonID != 0) {
if (studentID > 0) {
if (mydb.updateLessonNotes(lNote)) {
//Update was successful
Toast.makeText(getApplicationContext(), "Updated successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), com.example.ltss.dyslexia.app.LessonNotesList.class);
intent.putExtra("studentId",studentID);
startActivity(intent);
} else {
//Update did not complete correctly
Toast.makeText(getApplicationContext(), "Update unsuccessful, Please try again", Toast.LENGTH_SHORT).show();
}
} else {
if (mydb.insertLessonNotes(lNote)) {
Toast.makeText(getApplicationContext(), "New Lesson note created", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Error creating lesson note! Please try again", Toast.LENGTH_SHORT).show();
}
//Return user to lessonNotesList where ListView should now show new lesson note
Intent intent = new Intent(getApplicationContext(), com.example.ltss.dyslexia.app.LessonNotesList.class);
intent.putExtra("studentId",studentID);
startActivity(intent);
}
}
Whenever I try to add or update anything in the system, I get this from the debug log:
04-02 20:02:33.925 26789-26789/com.example.ltssdyslexiaapp D/Items to add:﹕ com.example.ltss.dyslexia.app.LessonNotesData#42602bf8
Any ideas as to what this is or how I can fix it?
Thanks
Actually its not an error at all its just a Log output, its a DEBUG type of Log. You colud try to log the same adding line android.util.Log.d("hello","world"); to any method you want. And 'com.example.ltss.dyslexia.app.LessonNotesData#42602bf8' means that LessonNotesData has no toString() method and thats why you see #42602bf8 - its an instance address in memory or hash.
I am working on a button to email all users that have an email within the sqlite database. At the moment i have got the button working successfully, but can only call a single email address that is linked to the rows id.
Below is the code where i call upon the email and then send.
view.findViewById(R.id.btn_save).setOnClickListener(new OnClickListener() {
public void onClick(View view ) {
Mail m = new Mail("gmail#gmail.com", "password");
int arg = 0;
String[] toArr = {user_eMail.get(arg)};
m.setTo(toArr);
m.setFrom("gmail#gmail.com");
m.setSubject("This email is never going to work");
m.setBody("If you can read this email, please call me immediately because this never should have worked.");
try {
if(m.send()) {
Toast.makeText(getActivity(), "Email was sent successfully.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "Email was not sent.", Toast.LENGTH_LONG).show();
}
} catch(Exception e) {
//Toast.makeText(MailApp.this, "There was a problem sending the email.", Toast.LENGTH_LONG).show();
Log.e("MailApp", "Could not send email", e);
}
}
});
How do i go about changing the "int arg = 0" into calling all ids in the database? If you need any other code just let me know.
ok, since user_eMail is an ArrayList
private ArrayList<String> user_eMail = new ArrayList<String>();
.setTo() method must receive an array of emails separated by ","
create a method to extract an array from the database (for example getEmailsFromDB()) containing the emails: {"email1#gmail.com", "email2#gmail.com", "email3#gmail.com", "email4#gmail.com", "email5#gmail.com"};
and use:
m.setTo(getEmailsFromDB())
other option, the method returns from Database a String containing all the emails separated by "," , like "email1#gmail.com, email2#gmail.com, email3#gmail.com, email4#gmail.com, email5#gmail.com";
String[] user_eMail = getEmailsFromDB().split(",");
m.setTo(user_eMail);
I am having issued Retrieving objects from Parse.com. I plan to have a list of anywhere from 3 to 25 objects displayed, They will change daily. I will not know the ObjectID, or any of the content of the object. I followed this guide the best I could.
I wrote this code here to simplify what I am doing. It is throwing a null pointer exception in my .done.
UPDATED
Saving my object: //I am doing this successfully
ParseObject testObject = new ParseObject("TestObject");
testObject.put("TheColumn", "The name in the column");
testObject.saveInBackground();
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, "Saved", Toast.LENGTH_LONG);
toast.show();
Retrieving my Object //Unsuccessfully....
ParseQuery<ParseObject> query = ParseQuery.getQuery("TestObject");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> parseObjects, com.parse.ParseException e) {
if (e==null){
Log.d("THE OBJECT", "" +parseObjects.size());
name = parseObjects.toString();
Log.d("THE QUERY ", "" + name);
} else {
Log.d("ERROR:", "" + e.getMessage());
}
}
});
In my logcat, I get my Log.d's to log. I get two; D/THE OBJECT: 1 and D/THE QUERY: [com.parse.ParseObject#XXXXXX] But if I try to set it to a TextView, I get a nullPointerException.
Why am I getting data returned like this? I feel I am following this guide closely.
The Reason for my nullpointer was that I was setting the text to a TextView in a different class on accident. Got my r.id's confused.
I have ORMLite database with some fields. I want to select titles from the table where id == id which I get from webservice. I do like that:
try {
Dao<ProcessStatus,Integer> dao = db.getStatusDao();
Log.i("status",dao.queryForAll().toString());
QueryBuilder<ProcessStatus,Integer> query = dao.queryBuilder();
Where where = query.where();
String a = null;
for(Order r:LoginActivity.orders) {
//LoginActivity.orders - array of my objects which I get from webservice
Log.i("database",query.selectRaw("select title from process_status").
where().rawComparison(ProcessStatus.STATUS_ID, "=",
r.getProcess_status().getProccessStatusId()).toString());
}
Log.i("sr",a);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I tried like this but I get only sets of my id, not titles. I tried like this:
Log.i("database", query.selectColumns(ProcessStatus.STATUS_TITLE).where().
eq(ProcessStatus.STATUS_ID, r.getProcess_status().getProccessStatusId())
.toString());
but I have the same result. How should I get data from database?
For selecting an specific field from the table, you could do something like this:
String result = "";
try {
GenericRawResults<String[]> rawResults = yourDAO.queryRaw("select " +
ProcessStatus.STATUS_TITLE +" from YourTable where "+
ProcessStatus.STATUS_ID + " = " +
r.getProcess_status().getProccessStatusId());
List<String[]> results = rawResults.getResults();
// This will select the first result (the first and maybe only row returned)
String[] resultArray = results.get(0);
//This will select the first field in the result which should be the ID
result = resultArray[0];
} catch (Exception e) {
e.printStackTrace();
}
Hope this helps.
It's hard to properly answer this question without seeing all of the classes of the processStatusId field and others. However I think you are doing too much raw method and may not be properly escaping your values and the like.
I would recommend that you use the IN SQL statement instead of what you are doing in the loop. Something like:
List<String> ids = new ArrayList<String>();
for(Order r : LoginActivity.orders) {
ids.add(r.getProcess_status().getProccessStatusId());
}
QueryBuilder<ProcessStatus, Integer> qb = dao.queryBuilder();
Where where = qb.where();
where.in(ProcessStatus.STATUS_ID, ids);
qb.selectColumns(ProcessStatus.STATUS_TITLE);
Now that you have built your query, either you can retrieve your ProcessStatus objects or you can get the titles themselves using dao.queryForRaw(...):
List<ProcessStatus> results = qb.query();
// or use the prepareStatementString method to get raw results
GenericRawResults<String[]> results = dao.queryRaw(qb.prepareStatementString());
// each raw result would have a String[] with 1 element for the title