Passing Listview OnClick to Fetch Data from DB - sqlite

I have a ListView which displays static data along with images (say Activity A). When I click a ListVoew Item, the data is captured and passed onto next Activity (lets call it Activity B). In Activity B, I want to pass the selected value into DB select where clause and fetch data and show relevant information pertaining to the selection. Here is my code snippet...
Activity A:
String subproduct = ((TextView) view.findViewById(R.id.product_label)).getText().toString();
// Launching new Activity on selecting single List Item
SharedPreferences sharedPreferences = getSharedPreferences("pref",MODE_WORLD_READABLE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.putString("subproduct", subproduct);
editor.commit();
Intent myIntent = new Intent(getApplicationContext(),Details.class);
startActivity(myIntent);
And here is my Activity B:enter code here
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.setContentView(R.layout.details1);
SharedPreferences myPrefs = this.getSharedPreferences("pref", MODE_WORLD_READABLE);
String subproduct = myPrefs.getString("subproduct","null");
TextView txtProduct1 = (TextView) findViewById(R.id.detail_item);
txtProduct1.setText(subproduct);
and here is my DBHelper.java. Here I want to pass the selected value. Please help me how I can acheive this...
public Cursor getData(){
//SharedPreferences myPrefs = this.getSharedPreferences("pref", 0);
//String subproduct = myPrefs.getString("subproduct","null");
Cursor c = myDataBase.rawQuery("SELECT * FROM Destmain WHERE destname= " + ? + " ", null);
while (c.moveToNext()){
DestInfo q = new DestInfo();
q.setDestination(c.getString(1));
q.setCity(c.getString(2));
q.setCountry(c.getString(3));
q.setPeriod(c.getString(4));
q.setType(c.getString(5));
q.setCurrency(c.getString(6));
q.setBriefhistory(c.getString(7));
q.setHighlights(c.getString(8));
}
c.close();
return c;
Can anyone help me how I can pass the ListView (Activity A) selected value into fetching DB data and show in Activity B? Thanks a ton.

By using method onItemcClick in Activity A you can get the Id and pass it to the second Activity B.
onItemClick(AdapterView<?> adapterView, View view, int pos, long id)
newActivity.putExtra("key", id);
then in Activity B you can use this Id to search on the Database.
Intent newActivity = getIntent();
long id = newActivity.getLongExtras("key", -1);
in some other case you can use getLunchDetails method

Related

JavaFX Saving editable TableView to SQL

I have created a two column editable TableView which the user can edit and change the data thats inside each cell. Now my question is, once the user has changed some data around in each cell, how do I then save this data or print it out in a way to add to an SQL query like this example below
INSERT INTO table_name
VALUES (Value from table,Value from table,Value from table,...);
//Editable cell
PriceColumn.setCellFactory(TextFieldTableCell.forTableColumn());
PriceColumn.setOnEditCommit(
new EventHandler<CellEditEvent<NewCustomerList, String>>() {
#Override
public void handle(CellEditEvent<NewCustomerList, String> t) {
((NewCustomerList) t.getTableView().getItems().get(
t.getTablePosition().getRow())).setPrice(t.getNewValue());
}
}
);
You could do this by getting the required values and then passing them onto the DAO class to execute the query on the DB. Example follows-
PriceColumn.setOnEditCommit(
new EventHandler<CellEditEvent<NewCustomerList, String>>() {
#Override
public void handle(CellEditEvent<NewCustomerList, String> t) {
((NewCustomerList) t.getTableView().getItems().get(t.getTablePosition().getRow())).setPrice(t.getNewValue());
String newPrice = t.getNewValue();
String uniqueIdentifier = t.getRowValue().getUniqueIdentifier(); //Unique identfier is something that uniquely identify the row. It could be the name of the object that we are pricing here.
daoObj.updatePrice(newPrice, uniqueIdentifier); //Call DAO now
}
}
);
And somewhere in the deep dark jungles of DAO class,
private final String updateQuery = "UPDATE <TABLE_NAME> SET <PRICE_COLUMN> = ? WHERE <UNIQUE_COLUMN> = ?"; //If you require multiple columns to get a unique row, add them in the where clause as well.
public void updatePrice(String newPrice, String uniqueIdentifier) {
PreparedStatement ps = con.prepareStatement(updateQuery); //con is the connection object
ps.setString(1,uniqIdentifier); //if a string
ps.setString(2,newPrice); //if a string
ps.executeQuery();
}
If this is not what you were expecting, then can you please clarify your requirement?

Xamarin Android Pass Data Between Fragments

I create Android Project in Xamarin plugin for Visual Studio Community 2015. I have in my application 4 fragments and I switch in them by ViewPager which is navigated in ActionBar. In second and third tab, there are few fields (for second tab -> Name, Surname, Mail, Phone and for third -> description field). These fields are EditText. On last fragment there are fields (TextView) and I need to pass data from 2nd, 3rd to 4th fragment. These data is only string value.
I try to use this code:
public void OnTabSelected(ActionBar.Tab tab, FragmentTransaction ft)
{
viewPager.CurrentItem = tab.Position;
if (tab.Position == 0)
{
actionBar.SetTitle(Resource.String.GalleryTab);
} else if (tab.Position == 1)
{
actionBar.SetTitle(Resource.String.DescriptionTab);
} else if (tab.Position == 2)
{
actionBar.SetTitle(Resource.String.ContactInfoTab);
} else if (tab.Position == 3)
{
actionBar.SetTitle(Resource.String.SummaryTab);
nameContact.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) =>
{
nameSummary.Text = e.Text.ToString();
};
}
nameContact and nameSummary are properly initialized.
var nameContact = FindViewById<EditText>(Resource.Id.nameContactText);
var surnameContact = FindViewById<EditText>(Resource.Id.surnameContactText);
var nameSummary = FindViewById<TextView>(Resource.Id.nameSummary);
var surnameSummary = FindViewById<TextView>(Resource.Id.surnameSummary);
Can someone explain me how to send data between fragments. Thank you for answer.
UPDATE
I just do something like this.
var nameContact = FindViewById<EditText>(Resource.Id.nameContactText);
nameContactText = nameContact.Text.ToString();
var nameContactSummary = FindViewById<TextView>(Resource.Id.nameSummary);
nameContactSummary.Text = nameContactText;
A way to do it is to store data you need to transfer in parent activity (assuming that both fragments are hosted in the same activity) so every fragment will have access to this data using (Activity as yourActivityType).YourPropertyName in every fragment.
More details on Communicating with the Activity from Fragment can be found here:http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity

Combobox selections disappear when table editing canceled

Ok, I'm starting to lose my mind on this one. I have a tableview where there are 3 combobox table cells. The first is a box where a user can select a job, the job selected changes the next combobox's options (job category). The job category selection changes the options in the labor box. So the flow down is:
job > job category > labor.
I have a very peculiar problem. When editing the table, you can click on any box to get a corresponding list of the available selections based on the other fields. This works fine. Where it blows up is when a selection ISN'T made. To make things more interesting, it only effects the job and job category comboboxes the labor box works flawlessly.
symptom:
-- job category selection disappears when edit is canceled via esc or focus lost
-- selection chosen in the job category field is placed into the job field when editing is canceled via esc or upon loss of focus
Here's the steps to recreate the symptoms:
1) click on job category box and enable editing mode
2) make a new selection from the drop down list
new selection made img
3) click on the job box and enable editing
4) click off the job box and cancel editing by click on job category or labor box in the same row
5) enable job category editing and then cancel job category edit by clicking on either labor / labor boxes or using esc
lose the job category / job selections img
here is the code to initialize the graphic when it comes up:
public void initialize(URL location, ResourceBundle resources) {
/* this is here because the screen handler will load up the Main screen in the
in the hashmap; no connection data will be assigned to the user at that time.
Without this block, when the hashmap attempts to load the Main data this
will cause the screenhandler to error and the main application
to not load correctly. The block below initiatializes the connection to
prevent this from happening.*/
if ( vUsers.getConn() == null){
try {
//establishes a user's connection to the database
vUsers.ConnecrDB();
} catch (SQLException | IOException ex) {
//debugging catch
System.out.println(ex);
}
}
//set the job box list for the user
cmbxJobT.setItems(cmbxPopulator.getJobComboBox());
cmbxJobT.valueProperty().addListener(new ChangeListener<String>(){
#Override
//reads the user's selectino and returns the appropriate labor codes for the Employee
public void changed(ObservableValue o, String oldValue, String newValue){
if (newValue != null){
cmbxJobCatT.getItems().clear();
cmbxJobCatT.getItems().addAll(cmbxPopulator.getJobCatComboBox(newValue));
}else {
cmbxJobCatT.getItems().clear();
cmbxJobCatT.getItems().add(null);
}
}
});
cmbxJobCatT.valueProperty().addListener(new ChangeListener<String>(){
#Override
//reads the user's selectino and returns the appropriate labor codes for the Employee
public void changed(ObservableValue o, String oldValue, String newValue){
if (newValue != null){
cmbxLaborT.getItems().clear();
cmbxLaborT.getItems().addAll(cmbxPopulator.getLaborComboBox(newValue));
}else {
cmbxLaborT.getItems().clear();
cmbxLaborT.getItems().add(null);
}
}
});
tblviewTime.getSelectionModel().selectedItemProperty().addListener((obs, oldSelection, newSel) ->{
if (newSel != null){
Model_Time current = tblviewTime.getSelectionModel().getSelectedItem();
cmbxJobCatT.getItems().clear();
cmbxJobCatT.getItems().addAll(cmbxPopulator.getJobCatComboBox(current.getJob()));
cmbxLaborT.getItems().clear();
cmbxLaborT.getItems().addAll(cmbxPopulator.getLaborComboBox(current.getJobCat()));
}
if (newSel == null){
Model_Time current = tblviewTime.getSelectionModel().getSelectedItem();
cmbxJobCatT.getItems().clear();
cmbxJobCatT.getItems().addAll(cmbxPopulator.getJobCatComboBox(current.getJob()));
cmbxLaborT.getItems().clear();
cmbxLaborT.getItems().addAll(cmbxPopulator.getLaborComboBox(current.getJobCat()));
}
});
addDragListeners(bertaTabPane);
}
here's the code that sets up the tableview:
public void btnTimeSearch(ActionEvent event){
//makes an instance of the toolkit needed to query user time.
Database_RetrievesTime userData = new Database_RetrievesTime();
//grabs data from the userinput fields to set the toolkit
userData.setDateSelect(lblPickDateT.getValue());
userData.setJobBoxSelect(jobTbl.getIdByDesc(cmbxJobT.getValue()));
userData.setLaborBoxSelect(laborTbl.getIdByDesc(cmbxLaborT.getValue()));
userData.setJobCatSelect(jobCatTbl.getIdByDesc(cmbxJobCatT.getValue()));
/*creates cell factories in each column and maps the cell values to the
observable array list's IDs. The section also sets the columns up for user
editing to be available and the methods to execute upon an editted cell
being committed to entry.
**NOTE: The values are retrieved by the model class's getter methods.
Changing a name in the model class requires the user to update the getters.
Naming convention does apply. So for example: a variable
named cscHelp is added, it would need to have a getter called getCscHelp otherwise
the corresponding column will return blanks.*/
//setup ID column
IDcol.setCellValueFactory(new PropertyValueFactory<>("ID"));
//setup Datecol
Datecol.setCellValueFactory(new PropertyValueFactory<>("userDate"));
Datecol.setCellFactory(DatePickerTableCell.forTableColumn());
//created a custom datepicker callback that can be reused throughout the code's interfaces
Datecol.setOnEditCommit((CellEditEvent<Model_Time,LocalDate> t) -> {
//generate a temporary variable to convert the LocalDate returned into a SimpleObjectProperty
ObjectProperty<LocalDate> temp = new SimpleObjectProperty(t.getNewValue());
//store the new value to the object's model
t.getRowValue().setUserDate(temp);
//store row's object to the change list
Helper_TimShArrGen.addToEditedMatrix(t.getRowValue());
//signaling to the program that a change had been made
isChanged = true;
});
//job column setup
Jobcol.setCellValueFactory(new PropertyValueFactory<>("Job"));
Jobcol.setCellFactory(ComboBoxTableCell.forTableColumn(cmbxPopulator.getJobComboBox()));
/*creates a combobox filled with the populated items found at initialization of the screen
user inputs are automatically commited
*/
Jobcol.setOnEditCommit((CellEditEvent<Model_Time,String> t) -> {
SimpleStringProperty ssp = new SimpleStringProperty(t.getNewValue());
//store selection to the object's model (unprocessed so values will show something like '6002: Kobota'
t.getRowValue().setJob(ssp);
//store row's object to the change list
Helper_TimShArrGen.addToEditedMatrix(t.getRowValue());
cmbxJobCatT.getItems().clear();
cmbxJobCatT.getItems().addAll(cmbxPopulator.getJobCatComboBox(t.getRowValue().getJob()));
//signaling a change has been made
isChanged = true;
});
jobCatCol.setCellValueFactory(new PropertyValueFactory<>("JobCat"));
jobCatCol.setCellFactory(ComboBoxTableCell.forTableColumn(cmbxPopulator.getJobCatComboBox(cmbxJobT.getValue())));
jobCatCol.setOnEditCommit((CellEditEvent<Model_Time,String> t)->{
SimpleStringProperty ssp = new SimpleStringProperty(t.getNewValue());
//store selection to the object's model (unprocessed so values will show something like '6002: Kobota'
t.getRowValue().setJob(ssp);
//store row's object to the change list
Helper_TimShArrGen.addToEditedMatrix(t.getRowValue());
cmbxLaborT.getItems().clear();
cmbxLaborT.getItems().addAll(cmbxPopulator.getLaborComboBox(t.getRowValue().getJob()));
//signaling a change has been made
isChanged = true;
});
//labor column setup works just like the job column
Laborcol.setCellValueFactory(new PropertyValueFactory<>("Labor"));
Laborcol.setCellFactory(ComboBoxTableCell.forTableColumn(cmbxPopulator.getLaborComboBox(cmbxJobCatT.getValue())));
Laborcol.setOnEditCommit((CellEditEvent<Model_Time,String> t) -> {
SimpleStringProperty ssp = new SimpleStringProperty(t.getNewValue());
t.getRowValue().setLabor(ssp);
Helper_TimShArrGen.addToEditedMatrix(t.getRowValue());
t.getTableView().getItems().get(t.getTablePosition().getRow()).setLabor(ssp);
isChanged = true;
});
//time column setup.
Timecol.setCellValueFactory(new PropertyValueFactory<>("Time"));
Timecol.setCellFactory(TextFieldTableCell.<Model_Time, Float>forTableColumn(new FloatStringConverter()));
Timecol.setOnEditCommit((CellEditEvent<Model_Time,Float> t) -> {
//temp variable initialiation
float token = t.getNewValue();
//generate a temporary variable to convert the float return to a SimpleFloatProperty
SimpleFloatProperty temp = new SimpleFloatProperty(token);
//now update the row's object
t.getRowValue().setTime(temp);
//store row's object to the change list
Helper_TimShArrGen.addToEditedMatrix(t.getRowValue());
isChanged = true;
});
//set tableView editable
tblviewTime.setEditable(true);
//sets tableView to allow multiline selection
TableViewSelectionModel<Model_Time> tvt = tblviewTime.getSelectionModel();
tvt.setSelectionMode(SelectionMode.MULTIPLE);
/* checks if edits have been made. If there are edits, it commits to the
database before wiping the arraylists and updating the table*/
if (isChanged == true){
/*makes sure there are no duplicate entries in the arraylist. Throws out
previous edits and takes the most recent*/
Helper_TimShArrGen.validateMatrixEntries();
//commits changes and resets the "isChanged" value.
isChanged = Helper_TimShArrGen.confirmChanges(vUsers, jobTbl, jobCatTbl, laborTbl, isChanged);
}
/*tells the kit to run the querytime Method which uses the user input data
and user data to search the timesheet tables and returns the user's time.*/
if (isChanged == false){
try {
rs = userData.queryTime(vUsers.getConn(), vUsers.getLogin_ID());
} catch (SQLException ex) {
System.out.println(ex);
}
} else {
return;
}
//sets up the observablelist for the tableview
renderTable.setTableView(tblviewTime);
ObservableList n = renderTable.generateTable(jobTbl, jobCatTbl, laborTbl, rs, vUsers.getConn());
//renders the data on the screen`
tblviewTime.setItems(n);
Helper_TimeBreakDown breakdown = new Helper_TimeBreakDown();
breakdown.setTblArr(n);
breakdown.BreakDwnTim();
lblMonTim.setText(String.valueOf(breakdown.getMon()));
lblTuesTim.setText(String.valueOf(breakdown.getTues()));
lblWedsTim.setText(String.valueOf(breakdown.getWeds()));
lblThursTim.setText(String.valueOf(breakdown.getThurs()));
lblFriTim.setText(String.valueOf(breakdown.getFri()));
lblSatTim.setText(String.valueOf(breakdown.getSat()));
lblSunTim.setText(String.valueOf(breakdown.getSun()));
lblWkTim.setText(String.valueOf(breakdown.getWeek()));
}
this is the segment from the class that handles the data that goes into the lists.
public ObservableList<String> getJobComboBox(){
//clear the jobList to clean out junk data between calls
jobList.clear();
//looks at the job table to determine if the job is active. If active, it reads the entry
for (count=0; count<= jobTbl.getTblArray().size()-1; count++){
if(jobTbl.getTblArray().get(count).isActive()){
/*here we scroll through the JobIDList and match the IDs to the jobtbl
data. When a match is hit, we grab up the number on the job and the description
this is added to another array that will become the combobox's list
*/
for(inCount = 0; inCount <= jobIDList.size()-1; inCount++){
if(jobIDList.get(inCount).getCol2ID() == jobTbl.getTblArray().get(count).getID()){
jobList.add(jobTbl.getNumById(jobIDList.get(inCount).getCol2ID())
+ ": " + jobTbl.getDescById(jobIDList.get(inCount).getCol2ID()));
}
}
}
}
/* there's probably a better dataset to use that won't allow duplicates
due to my lack of knowledge at this time, I elected to create a hashset, pass the arrayList
to the hashset to wipe out duplicates, and then pass it back to the arrayList to be used in the combobox
*/
Set<String> tmp = new HashSet();
tmp.addAll(jobList);
jobList.clear();
jobList.addAll(tmp);
jobList.add(null);
return jobList;
}
/**
*
* #param job Argument for the selected Job String
* #return returns the ObservableList of strings for the Job Category ComboBox
*/
public ObservableList<String> getJobCatComboBox(String job){
//clearing out old artifact data from the previous selection
jobCatList.clear();
//splitting the user's string selection apart (number as string, description as string)
int jID=0;
if (job != null){
if (job.contains(": ")){
String[] tmp = job.split(": ");
job = tmp[1];
}
}
// here we comb the job Table for a matching description and vacuum up the associated ID number
for(count=0; count<=jobTbl.getTblArray().size()-1; count++){
if(jobTbl.getTblArray().get(count).getDesc().equals(job)){
jID = jobTbl.getTblArray().get(count).getID();
}
}
/*using that jobID number to examine the fKey in the category table.
once we match the JobID to the fKey ID in the jobCat table, we scoop up the
the job Category code and description to create a list for the combobox
*/
for (count=0; count<= jobCTbl.getTblArray().size()-1; count++){
for(inCount = 0; inCount <= jobCatIDList.size()-1; inCount++){
if(jobCatIDList.get(inCount).getID() == jobCTbl.getTblArray().get(count).getID()){
if(jobCTbl.getTblArray().get(count).getfKeyId() == jID){
jobCatList.add(jobCTbl.getNumById(jobCatIDList.get(inCount).getID())
+ ": " + jobCTbl.getDescById(jobCatIDList.get(inCount).getID()));
}
}
}
}
//same house keeping to remove duplicates as described above
Set<String> tmp = new HashSet();
tmp.addAll(jobCatList);
jobCatList.clear();
jobCatList.addAll(tmp);
jobCatList.add(null);
return jobCatList;
}
/**
*
* #param jobCat Argument for the selected Job Category String
* #return ObservableList of strings for the Labor ComboBox
*/
public ObservableList<String> getLaborComboBox(String jobCat){
//temp arrays I needed to decode the affiliated connections
ArrayList<Integer> jCID = new ArrayList();
ArrayList<Integer> laborID = new ArrayList();
//house keeping to remove artifact data from previous selections
if(jCID != null){
jCID.clear();
}
if(laborID != null){
laborID.clear();
}
if(laborList !=null){
laborList.clear();
}
//split user's string selection for the job category (numerical code as sting, description as string)
if(jobCat != null){
if (jobCat.contains(": ")){
String[] tmp = jobCat.split(": ");
jobCat = tmp[1];
}
}
//use the description to find the affiliated job category ID
for(count=0; count<=jobCTbl.getTblArray().size()-1; count++){
if(jobCTbl.getTblArray().get(count).getDesc().equals(jobCat)){
jCID.add(jobCTbl.getTblArray().get(count).getID());
}
}
//use the job category ID to find the associated labor IDs from the associate entity table
for(count=0; count<=jCLTbl.getTblArray().size()-1; count++){
for(inCount=0; inCount<=jCID.size()-1; inCount++){
if(jCLTbl.getTblArray().get(count).getCol1ID() == jCID.get(inCount)){
laborID.add(jCLTbl.getTblArray().get(count).getCol2ID());
}
}
}
//use the labor ID to look up the needed data from the labor table.
for (count=0; count<= laborTbl.getTblArray().size()-1; count++){
for(inCount = 0; inCount <= laborID.size()-1; inCount++){
if(laborID.get(inCount) == laborTbl.getTblArray().get(count).getID()){
laborList.add(laborTbl.getNumById(laborID.get(inCount))
+ ": " + laborTbl.getDescById(laborID.get(inCount)));
}
}
}
//more housekeeping to remove duplicate entries.
Set<String> tmp = new HashSet();
tmp.addAll(laborList);
laborList.clear();
laborList.addAll(tmp);
laborList.add(null);
return laborList;
}
I know there are probably better ways to do things here. I'm still new to JAVA and coding. I work at a small company so I'm the only coder they employee. Unfortunately this limits me to what I can teach myself, so there are probably some more efficient ways to accomplish the same mission here. Anyway, if anyone could help me figure out what is going on, it would be appreciated.
The answer to this problem is actually found in the SetOnEdit portion of the jobcatCol.
upon closer inspection and a lot of debugging, I found that this line
t.getRowValue().setJob(ssp);
is actually supposed to be
t.getRowValue().setJobCat(ssp);
I also chose to forego the ComboBoxTableCell API and write my own combobox implementations for each cell. It's a very basic version found here:
public class JobComboBoxCell extends TableCell<Model_Time, String>
{
private ComboBox<String> comboBox;
private Helper_UserSpecificTimDat cmbxPopulator = new Helper_UserSpecificTimDat();
public JobComboBoxCell(Helper_UserSpecificTimDat cmbxPopulator)
{
comboBox = new ComboBox<>();
this.cmbxPopulator = cmbxPopulator;
}
#Override
public void startEdit()
{
if ( !isEmpty() )
{
super.startEdit();
comboBox.setItems( cmbxPopulator.getJobComboBox() );
comboBox.getSelectionModel().select( this.getItem() );
comboBox.focusedProperty().addListener( new ChangeListener<Boolean>()
{
#Override
public void changed( ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue )
{
if ( !newValue )
{
commitEdit( comboBox.getSelectionModel().getSelectedItem() );
}
}
} );
setText( null );
setGraphic( comboBox );
}
}
#Override
public void cancelEdit()
{
super.cancelEdit();
setText( ( String ) this.getItem() );
setGraphic( null );
}
#Override
public void updateItem( String item, boolean empty )
{
super.updateItem( item, empty );
if ( empty )
{
setText( null );
setGraphic( null );
}
else
{
if ( isEditing() )
{
setText( null );
setGraphic( comboBox );
}
else
{
setText( this.getItem() );
setGraphic( null );
}
}
}
}
This code was courtesy of Uluk Biy's response in thread:Populate combo box list dynamically for each row in javaFx table view
I adapted his code a little bit to specifically fit my needs. This solved a problem with values disappearing from the job category field and from data transferring from the job category field to the Job field.
This was one of the harder pieces of code I've had to troubleshoot. It was a combination of how the ComboBoxTableCell operates, the dynamic data of my comboboxes, and a slip in the which setter I was calling. It was about a perfect storm of flubs that the program saw no exceptions for as a result.
Thank you for the help

Add values to existing cookie in ASP.NET

I am facing the following task:
As the user navigates the site logs onto the website, write the
following information
Current Date
Current Time
Name of up to 5 Products the user viewed or Ordered during the visit
As I don't really have a product list site, I was going to do on the order screen. When user inputs the quantity to order I have a TextChanged event. So I can get details of a single product with the required information, but I am not sure how to keep adding to it?
This is what I am doing atm:
foreach (GridViewRow row in this.GridView1.Rows)
{
// string pName1 = GridView1.DataKeys[test].Values["ProductName"].ToString();
testCookie.Values.Add("CurrentDate", currentDate);
testCookie.Values.Add("CurrentTime", currentTime);
testCookie.Values.Add("ProductName", pName);
Label lblPartStatus = ((Label)row.Cells[4].FindControl("Label8"));
double testprice = Convert.ToDouble(lblPartStatus.Text);
grandTotal = grandTotal + testprice;
}
And also, how do I limit/check the amount of products that have been saved in the cookie and replace the oldest one with a newer ones?
Thanks for any advise!
I will recommend to create Dictionary object and add key value pair to it then store dictionary into Session.
Dictionary<string, string> dic = new Dictionary<string, string>();
int i = 0;
foreach (GridViewRow row in this.GridView1.Rows)
{
dic.Add("CurrentDate" + i, currentDate);
dic.Add("CurrentTime" + i, currentTime);
dic.Add("ProductName" + i, pName);
i++;
// your code
}
Session["dic"] = dic;
For retrieving those values.
Dictionary<string, string> dic = (Dictionary<string, string>)Session["dic"];
int i = 0;
foreach(KeyValuePair<string, string> entry in dic)
{
string date = entry.Value.ToString();
}

Populate ListView with data from SQLite database

I've been beating my head around trying to populate a ListView with data from an SQLite database and can't seem to figure it out. I've read countless tutorials and equally countless posts here, but I'm obviously not getting something critical. Was hoping someone could give me a hint as to why the following two pieces of code aren't working together, or if I should be looking at something else entirely. Any help would be appreciated. The result I'm getting is a force close.
Method that initiates populating ListView object
public void displayNurseRoster(){
listView = (ListView) findViewById(R.id.list);
// create instance of DbCommunicator
DbCommunicator rosterView = new DbCommunicator(this);
// open instance
rosterView.open();
// instantiate SimpleCursorAdapter instance and set value
SimpleCursorAdapter cursorAdapter;
cursorAdapter = rosterView.getRosterListViewAdapter(this);
// close database instance
rosterView.close();
// set adapter to listView
listView.setAdapter(cursorAdapter);
}
Method that returns SimpleCursorAdapter:
public SimpleCursorAdapter getRosterListViewAdapter (Context context) {
// method variables
int[] to = new int[] {R.id.rosterListLname};
// used ArrayList because of unpredictability of array length
List<String> dataArray = new ArrayList<String>();
String[] columns = new String[] {KEY_NURSE_ROWID, KEY_LNAME};
// create cursor
Cursor cursor = sqldb.query(NURSE_TABLE, columns, null, null, null,
null, KEY_LNAME);
int iLname = cursor.getColumnIndex(KEY_LNAME);
cursor.moveToFirst();
String result = "";
while(!cursor.isAfterLast()){
result = result
+ cursor.getString(iLname) + "\n";
dataArray.add(result);
}
// convert ArrayList to String array for use with SimpleCursorAdapter
String [] from = (String[]) dataArray.toArray();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(context,
R.layout.edit_roster, cursor, from, to);
return adapter;
}
Okay, I got it to work and wanted to share to help out anyone else struggling with this and 2) to get feedback on my fix in case anyone with more experience has a better suggestion.
I actually wanted to show three items in the list view, so here's the code that worked. One of the problems I was having was that I was extending ListActivity, but found in another StackOverflow post that that is not a good idea when there is only one list view to worry about.
package com.deadEddie.staffingmanagement;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class EditRoster extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_roster);
displayNurseRoster();
}
public void displayNurseRoster(){
ListView listView = (ListView) findViewById(R.id.list);
int[] to = new int[] {
R.id.rosterListLname,
R.id.rosterListFname,
R.id.rosterListMI };
String[] from = new String [] {
DbCommunicator.KEY_LNAME,
DbCommunicator.KEY_FNAME,
DbCommunicator.KEY_MI};
// create instance of DbCommunicator
DbCommunicator rosterView = new DbCommunicator(this);
// open instance
rosterView.open();
// get & manage cursor
Cursor cursor = rosterView.getRosterCursor(this);
startManagingCursor(cursor);
// instantiate cursor adaptor
ListAdapter adapter = new SimpleCursorAdapter(this,
R.layout.nurse_list, cursor, from, to);
cursor.moveToNext();
// set adapter to listView
listView.setAdapter(adapter);
}// displayNurseRoster()
}
Here's the method in my DbCommunicator class. What finally made the difference was that I was not creating an instance of SQLiteQueryBuilder and using that, but instead I was using sqldb.query(...), as shown above. I'm not sure what the difference is, but it finally did the trick. If anyone would like to share, please do.
public Cursor getRosterCursor (Context context) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(NURSE_TABLE);
Cursor cursor = queryBuilder.query(sqldb, new String[] {
KEY_NURSE_ROWID,
KEY_LNAME,
KEY_FNAME,
KEY_MI},
null, null, null, null, null);
return cursor;
}
A couple other newbie lessons for anyone else out there:
1. Always use the "_id" field in the cursor. The cursor cannot function without that.
2. The while or for loop is not necessary for a simple list view. The cursor adapter handles that.
3. There is no need to call the moveToFirst() method on the cursor.
Hope that's helpful to someone.

Resources