The only data that should appear when I click the "view data button" should be the employee's personal data by searching its employee id.
This is my code:
public void viewAll() {
btnview.setOnClickListener(
new View.OnClickListener() {
#Override`enter code here`
public void onClick(View v) {
Cursor res = EmployeeData.getAllData();
if(res.getCount() == 0) {
// show message
showMessage("Error","Nothing found");
return;}
How can I get the specific data from the existing database?
You need to replace the getAllData with a method that SELECTs the appropriate data using a WHERE clause which is invoked with the employeeId being passed to it (after extracting the employeeId from the clicked item ).
You then need to process the Cursor by extracting the data from it, if any exists.
So you could have something like the following in your class that extends SQLiteOpenHelper :-
public Cursor getEmployeeDataById(long id) {
return this.getWritableDatabase().query("the_table",null,"employeeId=?",new String[]{String.valueOf(id)},null, null,null);
}
obviously "the_table" and "employeeId" should be replaced by the actual names.
see Query for an explanation of the method's parameters.
the Query (method which has 4 signatures) is a convenience method that returns a Cursor object.
-It generates the SQL on your behalf e.g. the above would generate the SQL SELECT * FROM the_table WHERE employeeId=?
- where the ? is bound (prevents SQL Injection) to the passed id value by SQLite.
When extracting the data from the Cursor, rather than checking the count, you can rely upon the fact that the Cursor's will return false if it cannot move to the first row (i.e. there is no first row). So extracting the data could be along the lines of:-
Cursor csr = EmployeeData.getEmployeeDataById(extracted_employee_id);
if (csr.moveToFirst()) {
.... extract the data from the cursor
} else {
showMessage("Error","Nothing found");
}
Related
IDEA does not allow me to use table.raw();
I am new in cucumber so while I was learning/practising I tried to get the data from a DataTable by the following code
public void iEnterTheFollowingForLogin(DataTable table) {
List<List<String>> data = table.raw();
System.out.println("The value is : "+ data.get(1).get(0).toString());
System.out.println("The value is : "+ data.get(1).get(1).toString());
}
I realized that IDEA type the raw method in red so I think maybe it is obsolete and now I should use a newer one.
Rather then accessing the raw table you can address individual cells directly using cell(row, column) or use cells() to get a list of lists.
import io.cucumber.datatable.DataTable;
import java.util.List;
class Scratch {
public static void main(String[] args) {
DataTable data = //...create data table here
System.out.println("The value is : " + data.cell(1, 0));
System.out.println("The value is : " + data.cell(1, 1));
List<List<String>> cells = data.cells();
System.out.println("The value is : " + cells.get(1).get(0));
System.out.println("The value is : " + cells.get(1).get(1));
}
}
Just Want to explain MP's answer in detail for others easy understanding-
Yes you wont be able to use raw() method anymore as, its not supported by cucumber api with newer versions of cucumber i.e. io.cucumber. However One can still still use it with older info.cukes dependencies.
So an alternative to raw() is as answered by MP.
For ex- Let's say you have below- Sample gherkin Step:
Then I should see following sections in my app detail page
|Basic Details|Bank Details|Reconciliation|Summarised Options|Currency Code|
>> The Cucumber step definition for above step should be like belwo-
#Then("I should see following sections in my app detail page")
public void verifySectionsOnDetailPageUI(List<List<String>> dTable) {
//Create your table as below (notice- dataTable declared as- List<List<String>> in method argument above)
DataTable data= DataTable.create(dTable);
// to get number of rows from DataTable
int i=data.cells().size();
// To print entire row's column (iterate via for loop using size if u have more than one row defined in data table
System.out.println("All Cells Data: "+data.cells());
//Read cell by cell data as below, row index to be started from 1 if you have column headings provided in ur table
System.out.println(data.cell(0,0));
System.out.println(data.cell(0,1));
System.out.println(data.cell(0,2));
.....
......... so On .. to be used as per your step's objective .....
O/P:
Basic Details
Bank Details
Reconciliation
I have a field in my database with duplicates. I want to use it in a dropdown list, which has to return distinct data.
Here is the method that I created to do this:
public IEnumerable<SelectListItem> GetBranches(string username)
{
using (var objData = new BranchEntities())
{
IEnumerable<SelectListItem> objdataresult = objData.ABC_USER.Select(c => new SelectListItem
{
Value = c.BRANCH_CODE.ToString(),
Text = c.BRANCH_CODE
}).Distinct(new Reuseablecomp.SelectListItemComparer());
return objdataresult;
}
}
Here is the class I am using:
public static class Reuseablecomp
{
public class SelectListItemComparer : IEqualityComparer<SelectListItem>
{
public bool Equals(SelectListItem x, SelectListItem y)
{
return x.Text == y.Text && x.Value == y.Value;
}
public int GetHashCode(SelectListItem item)
{
int hashText = item.Text == null ? 0 : item.Text.GetHashCode();
int hashValue = item.Value == null ? 0 : item.Value.GetHashCode();
return hashText ^ hashValue;
}
}
}
Nothing is returned and I get the error below. When I try a basic query without Distinct, everything works fine.
{"The operation cannot be completed because the DbContext has been disposed."}
System.Exception {System.InvalidOperationException}
Inner exception = null
How can I return distinct data for my dropdown?
Technically, your problem can be solved simply by appending .ToList() after your Distinct(...) call. The problem is that queries are evaluated JIT (just in time). In other words, until the actual data the query represents is needed, the query is not actually sent to the database. Calling ToList is one such thing that requires the actual data, and therefore will cause the query to be evaluated immediately.
However, the root cause of your problem is that you are doing this within a using statement. When the method exits, the query has not yet been evaluated, but you have now disposed of your context. Therefore, when it comes time to actually evaluate that query, there's no context to do it with and you get that exception. You should really never use a database context in conjuction with using. It's just a recipe for disaster. Your context should ideally be request-scoped and you should use dependency injection to feed it to whatever objects or methods need it.
Also, for what it's worth, you can simply move your Distinct call to before your Select and you won't need a custom IEqualityComparer any more. For example:
var objdataresult = objData.ABC_USER.Distinct().Select(c => new SelectListItem
{
Value = c.BRANCH_CODE.ToString(),
Text = c.BRANCH_CODE
});
Order of ops does matter here. Calling Distinct first includes it as part of the query to the database, but calling it after, as you're doing, runs it on the in-memory collection, once evaluated. The latter requires, then, custom logic to determine what constitutes distinct items in an IEnumerable<SelectListItem>, which is obviously not necessary for the database query version.
I want to set field properties , in table method from code.
I would like to do as a Form
in modifiedField Table method, I wolud like to insered look like this code:
if(this.FieldControl == "valueToBlock")
{
// I want to set here the field property
//this.Field_II allowEdit(false);
}
It's possible to set the property from code in Table method ?
thanks community,
enjoy!
You can use dataSource result on the buffer. The result is FormDataSource if buffer source is from client form.
If record changes you have to re-calculate this (create new method and call it from the table modifiedFiled and form DS active).
public void modifiedField(FieldId _fieldId)
{
FormDataSource fds;
super(_fieldId);
switch (_fieldId)
{
case fieldNum(TableName,FieldI):
if (this.isFormDataSource())
{
fds = this.dataSource();
fds.object(fieldNum(MyTable, Field_II)).allowEdit(this.Field_I != "valueToBlock");
}
break;
}
}
Now I am creating a simple banking project for learning purpose where I need to do a lot of search, update and insert operations for a simple action. For example, if I want to create a transaction from a sample user id, in the "Create Trasaction" Screen, after inputting the details and pressing "submit" button, my application will do the following actions.
1) Insert a row in login session table with values: IP address, user id and timing.
2) To check if the particular user id has access to create a transaction option from user access table.
3) To check if the accounts being debited/credited belong to the same branch code as the home branch code of the creating user.
3) To check if the input inventory (if any) i.e. DD, Cheque is valid or not from inventory table.
4) To check if the account being debited/credited has freeze or not.
5) To check if the account being debited has enough available balance or not.
6) Check the account status Active/Inactive or Dormant.
7) Check and create service tax if applicable i.e. another search from S.Tax table and insert into accounts transaction table
and finally,
8) Insert a row into the accounts transaction table if the criteria pass.
Now I do not feel comfortable to write so many preparedstatement code in my Servlet for only creating a transactions. There will be other operations in my application too. So I was wondering if there is a way we can simply write these SQL statements and pass the SQL file to the Servlet anyway. Or maybe we can write a function in PL/SQL and pass the function to the servelt. Are these ways possible?
Please note, I am using J2EE and Oracle database.
I did this once with a project I was doing some years back and I actually achieved something close to what you are looking for I created a properties file in this format:
trans.getTransactons=select * from whateverTable where onesqlquery
trans.getTranId=select tran_id from whatevertable where anothersqlquery
So that when you write your classes you just load the Properties from the file and the query is populated from the property: for example: This Loads the Property fle
public class QueriesLoader {
Properties prop;
public QueriesLoader() {
}
public Properties getProp() {
prop = new Properties();
ClassLoader classLoader = getClass().getClassLoader();
try {
InputStream url = classLoader.getResourceAsStream("path/to/your/propertiesFile/databasequeries.properties");
prop.load(url);
} catch (IOException asd) {
System.out.println(asd.getMessage());
}
return prop;
}
}
And then in you Database Access Objects
public ArrayList getAllTransactions() {
ArrayList arr = new ArrayList();
try {
String sql = que.getProp().getProperty("trans.getTransactons");
PreparedStatement ps = DBConnection.getDbConnection().prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
arr.add(rs.getString(1));
}
DBConnection.closeConn(DBConnection.getDbConnection());
} catch (IOException asd) {
log.debug(Level.FATAL, asd);
} catch (SQLException asd) {
log.debug(Level.FATAL, asd);
}
return arr;
}
And I ended up not writing a single Query Inside my classes. I hope this Helps you.
The ExamVersion class has an int? property named SourceSafeVersionNum
When I execute the following code:
var query = from examVersion in db.ExamVersions
where examVersion.ExamVersionID == ExamVersionID
select examVersion;
foreach (ExamVersion examVer in query.ToList())
{
yield return examVer;
}
examVer.SourceSafeVersionNum is set to 1 even though it is NULL in the database.
When I run the SQL code generated by LINQ in SQL Server, the SourceSafeVersionNum column value is NULL (as I'd expect) but in the foreach loop the examVer.SourceSafeVersionNum is 1.
I can't find anywhere in the code where a default value is assigned or any similar logic.
Any ideas why/where this value is being set to 1?
Here is the property declaration (generated by a .dbml file)
[Column(Storage="_SourceSafeVersionNum", DbType="Int", UpdateCheck=UpdateCheck.Never)]
public System.Nullable<int> SourceSafeVersionNum
{
get
{
return this._SourceSafeVersionNum;
}
set
{
if ((this._SourceSafeVersionNum != value))
{
this.OnSourceSafeVersionNumChanging(value);
this.SendPropertyChanging();
this._SourceSafeVersionNum = value;
this.SendPropertyChanged("SourceSafeVersionNum");
this.OnSourceSafeVersionNumChanged();
}
}
}
Have you tried setting a breakpoint in the set{} method of the property to see what else might be populating its value? You might catch the culprit in the act, then look at the Call Stack to see who it is.
As a follow up to this, here is what happened:
The code that retrieved the value from the database was being called twice but through two different code paths. The code path that was assigning the value of 1 was being stepped over by the debugger so I didn't see it.