cant update data in sqlite database - android

TextView desc,details,responsibility,status,txtdate;
EditText equipment_id;
DBController controller = new DBController(this,null,null,1);
ImageButton btnupdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_update_equiments);
equipment_id = (EditText)findViewById(R.id.txtequipmentid);
desc = (TextView)findViewById(R.id.txtdescription);
details = (TextView)findViewById(R.id.txtdetails);
status = (TextView)findViewById(R.id.txtstatus);
txtdate = (TextView)findViewById(R.id.txtdate);
responsibility = (TextView)findViewById(R.id.txtresponsibilitycenter);
btnupdate = (ImageButton)findViewById(R.id.btnupdate);
//desc.setVisibility(View.GONE);
//details.setVisibility(View.GONE);
// responsibility.setVisibility(View.GONE);
// btnupdate.setVisibility(View.GONE);
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c.getTime());
txtdate.setText(formattedDate);
//update data
btnupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
//String status = "1";
controller = new DBController(getApplicationContext(), null, null ,1);
SQLiteDatabase database = controller.getWritableDatabase();
ContentValues data = new ContentValues();
data.put("description", desc.getText().toString());
data.put("details", details.getText().toString());
data.put("responsibility_center",responsibility.getText().toString());
data.put("status", status.getText().toString());
data.put("date_taken", txtdate.getText().toString());
database.update("tbl_equipments", data, "equipment_id=" + equipment_id.getText().toString(), null);
//database.update("tbl_equipments", data, "equipment_id=" + equipment_id.getText().toString(), null);
Toast.makeText(Search_Equipments.this, "Updated successfully", Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
Toast.makeText(Search_Equipments.this,ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
//search equipment
public void searchEquipment(View view){
if (equipment_id.getText().toString().equals("")){
Toast.makeText(Search_Equipments.this,"Please Enter Equipement No.",Toast.LENGTH_LONG).show();
} else {
controller = new DBController(this, null, null , 1);
Equipment equipment = controller.getEquipment(equipment_id.getText().toString());
if (equipment != null){
desc.setText(String.valueOf(equipment.get_description()));
details.setText(String.valueOf(equipment.get_details()));
responsibility.setText(String.valueOf(equipment.get_responsibility()));
desc.setVisibility(View.VISIBLE);
details.setVisibility(View.VISIBLE);
responsibility.setVisibility(View.VISIBLE);
btnupdate.setVisibility(View.VISIBLE);
}else {
Toast.makeText(Search_Equipments.this,"Not Found",Toast.LENGTH_LONG).show();
}
}
}
can someone help my code. if passed the condition that data successfully updated but when i display the updated data from database data has not updated, can someone help me to fix this. . . . . . because i dont where is my error there. see my update code. thanks :)

You forgot to commit the transaction.
database.setTransactionSuccessful();
database.endTransaction();

Related

Firebase error cannot get into the database

//error here
private FirebaseDatabase database = FirebaseDatabase.getInstance();
private DatabaseReference myRef = database.getReference("Runtime");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ping);
btn1 = (Button) findViewById(R.id.ping);
lstPing = (ListView) findViewById(R.id.listPing);
editText = (EditText) findViewById(R.id.edit_query);
// Write a message to the database
}
public void fExecutePing (View view) {
Editable host = editText.getText();
List<String> listResponsPing = new ArrayList<String>();
ArrayAdapter<String> adapterList = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listResponsPing);
try {
String cmdPing = "ping -c 2 "+host;
Runtime r = Runtime.getRuntime();
Process p = r.exec(cmdPing);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String inputLine;
String time_part = "";
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
while ((inputLine = in.readLine())!= null){
for(String time:listResponsPing){
if(time.contains("time=")){
String[] parts = time.split("time\\=");
time_part = parts[1];
myRef.push().setValue(time_part + " " + dateFormat.format(date));
}
}
listResponsPing.add(inputLine);
lstPing.setAdapter(adapterList);
}
Toast.makeText(this, " Command Execute Success", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, " Error: "+e.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}
}
I'm new in firebase and android. My apps are about network testing. I have a problem in my PingActivity. I cannot insert the result from ping activity to Firebase. I've tried all the solution that I found. But its not working. Please help. Thank you.
The error at the code that I've comment.

SQL Database in android not updating

I take input in an edittext, that is in a popup window. On dismiss of that popup, the string in edittext should be updated in db at required postion.
Popup Window code:
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.popl,(ViewGroup)findViewById(R.id.pop));
final PopupWindow pw = new PopupWindow(layout, 700 * (metrics.widthPixels/1080) , 300 * (metrics.heightPixels/1080) , true);
int coord[]= new int[2];
v.getLocationOnScreen(coord);
pw.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(getApplicationContext(), android.R.color.transparent)));
pw.setOutsideTouchable(true);
pw.showAtLocation(v, Gravity.NO_GRAVITY, coord[0] + 50 ,coord[1]+100);
Button del = (Button) layout.findViewById(R.id.del);
Button viewImage = (Button) layout.findViewById(R.id.view);
final EditText notes = (EditText) layout.findViewById(R.id.note);
notes.setText(data[6]);
notedata = data[6];
del.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SQLiteDatabase db = dBcontract.getWritableDatabase();
if ((thisimageuri!=null)&&(thisimageuri.toString().charAt(0)!='a'))
deleteimage(thisimageuri);
Log.d("delete operaiton",String.valueOf(db.delete(eventDBcontract.ListofItem.tableName,eventDBcontract.ListofItem.columnID+" = "+data[4],null)));
recreate(); //add option to delete files as well
}
});
viewImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (thisimageuri!=null)
{
Intent intent = new Intent(getApplicationContext(),showPic.class);
intent.putExtra("photo uri",thisimageuri);
notedata = notes.getText().toString();
pw.dismiss();
startActivity(intent);
}
}
});
pw.setOnDismissListener(new PopupWindow.OnDismissListener() {
#Override
public void onDismiss() {
notedata = notes.getText().toString();
Log.d("popop window", "onDismiss: " + notedata);
interact.savenote(data[4],notedata);
}
});
} catch (Exception e) {
e.printStackTrace();
}
Method to save in database:
public void savenote(String id , String note)
{
ContentValues values = new ContentValues();
SQLiteDatabase db = dBcontract.getWritableDatabase();
values.put(eventDBcontract.ListofItem.columnnotes,note);
db.update(eventDBcontract.ListofItem.tableName,values,"id=?",new String[]{id});
Log.d("Interact","add note complete " + note);
}
The code works correctly,i.e note is saved correctly in db, when i click on view image but not when I click outside of popup to dismiss it.
Log:
04-14 00:12:24.569 9517-9517/lcukerd.com.stufflist D/popop window: onDismiss: Yu
04-14 00:12:24.569 9517-9517/lcukerd.com.stufflist D/Interact: add note complete Yu
Help me spot the issue. This is eating my brain.
EDIT 1:
data[4] is the id of entry in db to be updated.
data[6] is the old value of "note" as saved in db.

How to update database table in android sqlite..?

I am new to Android.
I want to update the table data based on a CheckBox value.
But it's not updating the table - instead, I am getting a No Such Table error.
Here is the code :
public class CheckListActivity extends Activity {
CheckBox chkTask1, chkTask2, chkTask3, chkTask4, chkTask5, chkTask6,
chkTask7, chkTask8, chkTask9, chkTask10;
Button btnSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_list);
chkTask1 = (CheckBox) findViewById(R.id.task1_option);
chkTask2 = (CheckBox) findViewById(R.id.task2_option);
chkTask3 = (CheckBox) findViewById(R.id.task3_option);
chkTask4 = (CheckBox) findViewById(R.id.task4_option);
chkTask5 = (CheckBox) findViewById(R.id.task5_option);
chkTask6 = (CheckBox) findViewById(R.id.task6_option);
chkTask7 = (CheckBox) findViewById(R.id.task7_option);
chkTask8 = (CheckBox) findViewById(R.id.task8_option);
chkTask9 = (CheckBox) findViewById(R.id.task9_option);
chkTask10 = (CheckBox) findViewById(R.id.task10_option);
btnSave = (Button) findViewById(R.id.button2);
btnSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String error = "";
if (chkTask1.isChecked()) {
error = updateCheckList(1, 1);
} else {
error = updateCheckList(0, 1);
}
if (chkTask2.isChecked()) {
error = updateCheckList(1, 2);
} else {
error = updateCheckList(0, 2);
}
if (chkTask3.isChecked()) {
error = updateCheckList(1, 3);
} else {
error = updateCheckList(0, 3);
}
if(error.length()>0){
Toast.makeText(CheckListActivity.this, "ERROR " +error,
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(CheckListActivity.this, "Successfully Saved...!",Toast.LENGTH_LONG).show();
}
}
});
}
private String updateCheckList(int flag, int id) {
String errorStr = "";
SQLiteDatabase db;
db = openOrCreateDatabase("CheckList.db",
SQLiteDatabase.CREATE_IF_NECESSARY, null);
try {
String sql = "UPDATE CheckList SET CHECKEDFLAG = " + flag
+ " WHERE ID = " + id;
db.execSQL(sql);
} catch (Exception e) {
errorStr = errorStr + e.getMessage();
}
return errorStr;
}
}
Wild guess: you added the table AFTER the app was run the first time.
Solution: You have to uninstall and reinstall your app.

Updating a column in database of the selected user ID IN ANDROID

Can somebody help me about this matter? I have a listview with checkbox, every time the user tick the checkbox, all the selected user ID was inserted into a arraylist. Then if the button Export was clicked, all the column "Mark" in the database should be updated from "Not send" to "sent". I know that by this code the database will be updated:
public void updateEmailmark(String consumerId)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Constants.CONSUMER_EMAILMARK, "Sent");
db.update(Constants.DATABASE_TABLE_CONSUMER, contentValues, Constants.CONSUMER_ID + "=?",new String[]{consumerId});
db.close();
}
but my problem is I don't know how to update that column when the user selected many UserID to export. I only knew that I need to use a for loop but I don't know how. Thank for anyone who will help me. Here's my other code.
btn_Export.setOnClickListener(new OnClickListener()
{
public void onClick(View v){
arraylistSelectedConsumerIds = simpleAdapterConsumerData.getArrayListConsumerId();
arraylistSelectedConsumer = simpleAdapterConsumerData.getArrayListConsumer();
if (!arraylistSelectedConsumerIds.toString().equals("[]") && !arraylistSelectedConsumer.toString().equals("[]"))
{
boolean hasSDCard = false;
boolean sdCardIsWriteable = true;
String sdCardState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(sdCardState))
hasSDCard = true;
else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(sdCardState))
sdCardIsWriteable = true;
if (hasSDCard == true && sdCardIsWriteable == true){
new AsyncCreateBackup().execute();
String date = String.valueOf(calendar.get(Calendar.MONTH)+1)+"-"+String.valueOf(calendar.get(Calendar.DATE))+"-"+String.valueOf(calendar.get(Calendar.YEAR));
int fileCounter = 1;
File sdcard = Environment.getExternalStorageDirectory();
File dir = new File (sdcard.getAbsolutePath() + "/CompanyCares/export/");
if (dir.exists()){
File[]dirs = dir.listFiles();
try{
for(File fileFolder: dirs){
if(fileFolder.isDirectory() && fileFolder.getName().contains("export_"+date)){
fileCounter++;
}
}
} catch (Exception e){
e.printStackTrace();
}
}
consumerData = new StringBuilder();
File personFile;
time = String.valueOf(calendar.get(Calendar.HOUR_OF_DAY))+String.valueOf(calendar.get(Calendar.MINUTE))+String.valueOf(calendar.get(Calendar.SECOND));
personFile = createCSV("Person_Table_"+date+"_"+time, Constants.COLUMN_STRING_PERSON_TABLE, getConsumersDetails(arraylistSelectedConsumerIds), fileCounter, false);
createEmailWithAttachments(personFile);
arrayListExportedConsumerId.addAll(arraylistSelectedConsumerIds);
arrayListExportedConsumer.addAll(arraylistSelectedConsumer);
exportedConsumerId = new HashSet<String>();
exportedConsumer = new HashSet<String>();
exportedConsumerId.addAll(arrayListExportedConsumerId);
exportedConsumer.addAll(arrayListExportedConsumer);
sharedPreferencesEditor.putStringSet(Constants.SHARED_PREFERENCES_EXPORTED_CONSUMER_ID, exportedConsumerId);
sharedPreferencesEditor.putStringSet(Constants.SHARED_PREFERENCES_EXPORTED_CONSUMER, exportedConsumer);
sharedPreferencesEditor.commit();
}else{
Toast.makeText(AdminActivity.this, getString(R.string.error_sdcard), Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(AdminActivity.this, getString(R.string.error_select), Toast.LENGTH_LONG).show();
}
}
});

How to Create a Global Level Function with UI capability

I have a function to find an employee's id number from my sqlite database. The function allows the user to look up by id or name (first and/or last); therefore it creates several dialog boxes and finds the data through an If Else Then tree. Here's the code for those who like that sort of thing:
public String getEmployeeID() {
final CharSequence[] items = {"By ID", "By Name", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(LibraryScreen.this);
builder.setTitle("Find Employee");
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(items[item].equals("Cancel")) {
dialog.cancel();
empid = "";
} else if(items[item].equals("By ID")) {
dialog.cancel();
final Dialog dialog2 = new Dialog(LibraryScreen.this);
dialog2.setContentView(R.layout.peopledialog);
dialog2.setTitle("Employee ID");
dialog2.setCancelable(true);
//Set Visibility of the Rows
TableRow tblrow1 = (TableRow) dialog2.findViewById(R.id.trGeneral);
tblrow1.setVisibility(0);
//Set Captions for Rows
TextView txtvw1 = (TextView) dialog2.findViewById(R.id.tvGeneral);
txtvw1.setText("Employee ID");
//Set Up Edit Text Boxes
EditText edttxt1 = (EditText) dialog2.findViewById(R.id.txtGeneral);
//Set Input Type
edttxt1.setRawInputType(0x00000002);//numbers
edttxt1.setText("");
//set max lines
edttxt1.setMaxLines(1);
//Set MaxLength
int maxLength;
maxLength = 15;
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(maxLength);
edttxt1.setFilters(FilterArray);
Button button = (Button) dialog2.findViewById(R.id.btnTxtDiaSav);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText emplid = (EditText) dialog2.findViewById(R.id.txtGeneral);
String newemp = "";
db.open();
Cursor c = db.getEmployee(emplid.getText().toString());
if(c.moveToFirst()) {
empid = c.getString(c.getColumnIndex("employeeid"));
} else {
Toast.makeText(LibraryScreen.this, "No ID Match", Toast.LENGTH_LONG).show();
empid = "";
}
c.close();
db.close();
dialog2.dismiss();
}
});
Button buttonCan = (Button) dialog2.findViewById(R.id.btnTxtDiaCan);
buttonCan.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog2.dismiss();
empid = "";
}
});
dialog2.show();
} else if(items[item].equals("By Name")) {
dialog.cancel();
final Dialog dialog1 = new Dialog(LibraryScreen.this);
dialog1.setContentView(R.layout.peopledialog);
dialog1.setTitle("Employee's Name");
dialog1.setCancelable(true);
//Set Visibility of the Rows
TableRow tblrow1 = (TableRow) dialog1.findViewById(R.id.trGeneral);
tblrow1.setVisibility(0);
//Set Captions for Rows
TextView txtvw1 = (TextView) dialog1.findViewById(R.id.tvGeneral);
txtvw1.setText("Employee Name");
//Set Up Edit Text Boxes
EditText edttxt1 = (EditText) dialog1.findViewById(R.id.txtGeneral);
//Set Input Type
edttxt1.setRawInputType(0x00002001);//cap words
edttxt1.setText("");
//set max lines
edttxt1.setMaxLines(1);
//Set MaxLength
int maxLength;
maxLength = 50;
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(maxLength);
edttxt1.setFilters(FilterArray);
Button button = (Button) dialog1.findViewById(R.id.btnTxtDiaSav);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText emplid = (EditText) dialog1.findViewById(R.id.txtGeneral);
String firstname = emplid.getText().toString();
String lastname = "";
String matchlist = "";
String temptext = "";
int matchcount = 0;
if(firstname.lastIndexOf(" ") <= 0) {
lastname = firstname;
firstname = "X";
} else {
lastname = firstname.substring(firstname.lastIndexOf(" ") + 1);
firstname = firstname.substring(0, firstname.lastIndexOf(" "));
}
db.open();
Cursor c1, c2;
String titletext = "";
if(firstname.length() > 0) {
c1 = db.getEmployeeByName(lastname, firstname);
if(c1.getCount() == 0) {
c1 = db.getRowByFieldTextOrdered("employees", "lastname", lastname, "lastname, firstname");
if(c1.getCount() == 0) {
Toast.makeText(LibraryScreen.this, "No matching Employees.", Toast.LENGTH_LONG).show();
empid = "";
}
}
if(c1.getCount() > 0) {
do {
c2 = db.getRowByField("orgcodes", "manager", c1.getString(c1.getColumnIndex("employeeid")));
if(c2.moveToFirst()) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(9, 10).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(7, 8).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(5, 6).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(4, 5).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(3, 4).equals("0")) {
titletext = "Top Brass";
} else {
titletext = "Senior VP";
}
} else {
titletext = "VP";
}
} else {
titletext = "Director";
}
} else {
titletext = "Senior Manager";
}
} else {
titletext = "Manager";
}
} else {
titletext = "Employee";
}
matchcount++;
matchlist = matchlist + c1.getString(c1.getColumnIndex("employeeid")) + ": " + c1.getString(c1.getColumnIndex("firstname")) + " " + c1.getString(c1.getColumnIndex("lastname")) + ": " + titletext + "|";
} while(c1.moveToNext());
}
} else {
empid = "";
}
if(matchcount == 0) {
db.close();
Toast.makeText(LibraryScreen.this, "No matching Employees.", Toast.LENGTH_LONG).show();
empid = "";
} else {
final CharSequence[] items = new CharSequence[matchcount + 1];
items[0] = "(Cancel)";
for(int i = 1; i <= matchcount; i++) {
items[i] = matchlist.substring(0, matchlist.indexOf("|"));
matchlist = matchlist.substring(matchlist.indexOf("|") + 1);
}
db.close();
AlertDialog.Builder builder1 = new AlertDialog.Builder(LibraryScreen.this);
builder1.setTitle("Select Employee");
builder1.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(items[item].equals("(Cancel)")) {
dialog.cancel();
empid = "";
} else {
String wasted = items[item].toString();
empid = wasted.substring(0, wasted.indexOf(":"));
dialog.cancel();
}
}
});
AlertDialog alert1 = builder1.create();
alert1.show();
}
dialog1.dismiss();
}
});
Button buttonCan = (Button) dialog1.findViewById(R.id.btnTxtDiaCan);
buttonCan.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog1.dismiss();
empid = "";
}
});
dialog1.show();
}
}
});
AlertDialog alert = builder.create();
alert.show();
return empid;
}
I use the employee id for a variety of functions through multiple activities in my program. Up to now, I've simply pasted the code under each listener that needs the id, but that is such a waste of space IMHO.
My question:
Is there a way to put this function somewhere that can be called from many different activities?
If so:
How do I do that?
How do I set the context for the dialog boxes for multiple activities?
How do I get the employee id back to the function that needs it?
I'm sure this has been asked before, but I haven't been able to find it online: actually, I'm not even sure how to word the query right. My attempts have come up woefully short.
A little late to the party - but recorded for posterity:
Read up on the Application class:
Base class for those who need to maintain global application state.
You can provide your own implementation by specifying its name in your
AndroidManifest.xml's tag, which will cause that class
to be instantiated for you when the process for your
application/package is created.
Basically, this would give you the ability to obtain a single object that represents your running application (think of it as a singleton that returns an instance of your running app).
You first start off by creating a class that extends Application base class and defining any common code that is used throughout your application
import android.app.Application;
public class MyApplication extends Application {
public void myGlobalBusinessLogic() {
//
}
}
Then tell your application to use the MyApplication class instead of the default Application class via the <application> node in your app manifest:
<application android:icon="#drawable/icon" android:label="#string/app_name"
android:name="MyApplication">
Finally, when you need to get to your common function just do something like:
MyApplication application = (MyApplication) getApplication();
application.myGlobalBusinessLogic();
If you need to get the context from any part of your application, you can simple return it by calling getApplicationContext() (defined in the base Application class) via a getter method within your custom application class.

Categories

Resources