How can I move a question on single page on Android for quiz app using sqllite ?
I have used this code for the next button:
Cursor cus = db.rawQuery("select * from java", null);
cus.moveToNext();
que = cus.getString(0);
question.setText(que);
A = cus.getString(1);
a.setText(A);
B = cus.getString(2);
b.setText(B);
C = cus.getString(3);
c.setText(C);
D = cus.getString(4);
d.setText(D);
but it is not working.
If you want to insert a new question on the click of next button then do someththing like this-
final Cursor cus = db.rawQuery("select * from java", null);
cus.moveToPosition(-1);
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (cus.moveToNext()) {
que = cus.getString(0);
question.setText(que);
A = cus.getString(1);
a.setText(A);
B = cus.getString(2);
b.setText(B);
C = cus.getString(3);
c.setText(C);
D = cus.getString(4);
d.setText(D);
} else {
Toast.makeText(context, "No questions left",Toast.LENGTH_SHORT).show();
}
}
});
Related
I'm using listView and in every line I have a button. I'm using OnClick and not a listener.
When I press the button I need to update the database. How can I know what is the ID?
here is my code:
public void saleButtonClick(View v) {
int quantity = 0;
TextView mQuantityTextView = (TextView) findViewById(R.id.main_quantity);
quantity = Integer.parseInt(mQuantityTextView.getText().toString());
if (quantity > 0){
quantity --;
Uri updateUri = ContentUris.withAppendedId(BookEntry.CONTENT_URI, v.getId());
ContentValues values = new ContentValues();
values.put(BookEntry.COLUMN_BOOK_QUANTITY, quantity);
int rowsUpdated = getContentResolver().update(
updateUri,
values,
null,
null);
if (rowsUpdated == 1) {
Toast.makeText(this, R.string.sellable, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.not_sellable, Toast.LENGTH_SHORT).show();
}
} else {
// Out of stock
Toast.makeText(this, R.string.out_of_stock, Toast.LENGTH_LONG).show();
}
mQuantityTextView.setText(Integer.toString(quantity));
}
If you use ListView with CursorAdapter (+ContentProvider) then you should add onClickListener in your CursorAdapter. In this case all of your List Items will have the SaleButton connected to your product (with it's unique id).
Try this code in your Adapter:
Button saleButton = view.findViewById(R.id.sale_button);
saleButton.setOnClickListener(v -> {
sellItem(_id, productQuantity);
});
/**
* helper method for sell a product
* #param id - id of product
* #param productQuantity - original quantity which must decreased by one
*/
private void sellItem(long id, int productQuantity) {
int newQuantity = --productQuantity;
// check that new quantity is greater than 0. In this case we update product
if (newQuantity > 0) {
ContentValues sellItem = new ContentValues();
sellItem.put(BookEntry.COLUMN_BOOK_QUANTITY, quantity);
int result= mContext.getContentResolver().update(ContentUris.withAppendedId(BookEntry.CONTENT_URI,id),sellItem,null,null);
if(result==1){
// rest of your code
}
}
}
Hope it helps.
I had a very similar project, take a look at: https://github.com/csongi77/InventoryApp
Best regards!
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.
I am trying to code a "next" button for my Sqlite db. The way I want it to work is upon entering a number it one of the entries from the db if pressed again it brings up the entry on the list for the same given number entered. However I cant get it to bring up the next entry. So far my button code looks like this. However I have tried countless way to configure it with no luck. Please help. Thanks in advance!!!
public void onClick(View view) {
if (view == btnNext) {
Cursor c = db.rawQuery("SELECT * FROM number WHERE meter='" + editText6.getText() + "'", null);
if (editText6.getText().toString().trim().length() >= 0) {
c.getPosition();
c.moveToPosition(+1);
idNumber.setText(c.getString(0));
editText5.setText(c.getString(6));
editText4.setText(c.getString(5));
editText3.setText(c.getString(4));
editText2.setText(c.getString(3));
editText.setText(c.getString(2));
textView4.setText(c.getString(7));
status.setText(c.getString(8));
while (c.moveToNext()) ;
}
}
I had to add this separate method to keep cursor open while scrolling to the next entry:
final Button nextBtn = (Button) findViewById(R.id.btnNext);
nextBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (editText6.getText().toString().trim().length() == 0) {
Toast ToastMessage1 = Toast.makeText(getApplicationContext(), "Please" +
" Enter Meter Number\nThen Press Lookup Meter", Toast.LENGTH_LONG);
ToastMessage1.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
View toastView1 = ToastMessage1.getView();
toastView1.setBackgroundResource(R.drawable.shape9);
ToastMessage1.show();
} else {
if (c.getPosition() >= 1) {
c.moveToPrevious();
idNumber.setText(c.getString(0));
//Must maintain this order listed below in order for clear field on focus to work properly.
editText6.setText(c.getString(1));
editText5.setText(c.getString(6));
editText4.setText(c.getString(5));
editText3.setText(c.getString(4));
editText2.setText(c.getString(3));
editText.setText(c.getString(2));
//To here-list order.
date.setText(c.getString(7));
status.setText(c.getString(8));
etAddress.setText(c.getString(9));
}
if (c.getPosition() == 0) {
c.close();
Toast ToastMessage = Toast.makeText(getApplicationContext(), " Last Entry Recorded ", Toast.LENGTH_LONG);
ToastMessage.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
View toastView = ToastMessage.getView();
toastView.setBackgroundResource(R.drawable.shape9);
ToastMessage.show();
}
final Button clearBtn = (Button) findViewById(R.id.btnClear);
clearBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v2) {
if (v2 == clearBtn) {
c.close();
clearText();
}
}
});
}
}
});
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();
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.