Couldn't get text from the textfield Java - java

I have encounter a problem with my if else statement. I can't execute my if else statement. Actually the program should get the text from the text field and then convert to integer and validate whether the item id is found or not.
below is my partial coding:
Integer itmID = new Integer(inputItemID.getText());
Integer brwID = new Integer(inputBorrowerID.getText());
Item itm = parent.getItems().get(itmID);
Borrower brw = parent.getBorrowers().get(brwID);
if (itm == null) {
JOptionPane.showMessageDialog(this, "Item ID not found","Error", JOptionPane.ERROR_MESSAGE);
return;
}

You are retrieving item like Item itm = parent.getItems().get(itmID); , i assume that getItems() is some kind of collection . You are getting itm = null because your getItems() doesn't contain any item with given itemId.

Related

getting first level of categorisation from Notes view

I have a categorized Notes view, let say the first categorized column is TypeOfVehicle the second categorized column is Model and the third categorized column is Manufacturer.
I would like to collect only the values for the first category and return it as json object:
I am facing two problems:
- I can not read the value for the category, the column values are emptry and when I try to access the underlying document it is null
the script won't hop over to the category/sibling on the same level.
can someone explain me what am I doing wrong here?
private Object getFirstCategory() {
JsonJavaObject json = new JsonJavaObject();
try{
String server = null;
String filepath = null;
server = props.getProperty("server");
filepath = props.getProperty("filename");
Database db;
db = utils.getSession().getDatabase(server, filepath);
if (db.isOpen()) {
View vw = db.getView("transport");
if (null != vw) {
vw.setAutoUpdate(false);
ViewNavigator nav;
nav = vw.createViewNav();
JsonJavaArray arr = new JsonJavaArray();
Integer count = 0;
ViewEntry tmpentry;
ViewEntry entry = nav.getFirst();
while (null != entry) {
Vector<?> columnValues = entry.getColumnValues();
if(entry.isCategory()){
System.out.println("entry notesid = " + entry.getNoteID());
Document doc = entry.getDocument();
if(null != doc){
if (doc.hasItem("TypeOfVehicle ")){
System.out.println("category has not " + "TypeOfVehicle ");
}
else{
System.out.println("category IS " + doc.getItemValueString("TypeOfVehicle "));
}
} else{
System.out.println("doc is null");
}
JsonJavaObject row = new JsonJavaObject();
JsonJavaObject jo = new JsonJavaObject();
String TypeOfVehicle = String.valueOf(columnValues.get(0));
if (null != TypeOfVehicle ) {
if (!TypeOfVehicle .equals("")){
jo.put("TypeOfVehicle ", TypeOfVehicle );
} else{
jo.put("TypeOfVehicle ", "Not categorized");
}
} else {
jo.put("TypeOfVehicle ", "Not categorized");
}
row.put("request", jo);
arr.put(count, row);
count++;
tmpentry = nav.getNextSibling(entry);
entry.recycle();
entry = tmpentry;
} else{
//tmpentry = nav.getNextCategory();
//entry.recycle();
//entry = tmpentry;
}
}
json.put("data", arr);
vw.setAutoUpdate(true);
vw.recycle();
}
}
} catch (Exception e) {
OpenLogUtil.logErrorEx(e, JSFUtil.getXSPContext().getUrl().toString(), Level.SEVERE, null);
}
return json;
}
What you're doing wrong is trying to treat any single view entry as both a category and a document. A single view entry can only be one of a category, a document, or a total.
If you have an entry for which isCategory() returns true, then for the same entry:
isDocument() will return false.
getDocument() will return null.
getNoteID() will return an empty string.
If the only thing you need is top-level categories, then get the first entry from the navigator and iterate over entries using nav.getNextSibling(entry) as you're already doing, but:
Don't try to get documents, note ids, or fields.
Use entry.getColumnValues().get(0) to get the value of the first column for each category.
If the view contains any uncategorised documents, it's possible that entry.getColumnValues().get(0) might throw an exception, so you should also check that entry.getColumnValues().size() is at least 1 before trying to get a value.
If you need any extra data beyond just top-level categories, then note that subcategories and documents are children of their parent categories.
If an entry has a subcategory, nav.getChild(entry) will get the first subcategory of that entry.
If an entry has no subcategories, but is a category which contains documents, nav.getChild(entry) will get the first document in that category.

checking name in list it is there than update client table else category and client table

I have List which has names. I am providing name by using Scanner by using advance for loop and checking if the name is in the list it will update the client table else it will update . Category and client table both are in database .The problem is if my list has 4 names it should check if condition only and not go to the else statement till it check the 4 names , if name is not there than(which i give from scanner) should go to else condition needed a logic
String n = scann.nextLine();
List<String> li = new ArrayList<>();
li.add("abc");
li.add("def");
li.add("ghi");
li.add("jkl");
for (int i = 0; i < li.size(); i++) {
if (n.equals(li.get(i))) {
System.out.println("client table update");
} else {
System.out.println("category and client table update");
}
}
}
I kinda get the gist of what you are asking, but please be more precise.
From what i understand from your question is, you want to print either the first or the second thing, depending on wether your name is in the list or not. And in your case, both get printed.
That is because your prints are inside the for loop, thus printing 4 times and printing both options regardless, since your name cant be all 4 names at the same time.
Here is how i would solve this:
List<String> li = new ArrayList<>();
li.add("abc");
li.add("def");
li.add("ghi");
li.add("jkl");
boolean inList = false;
for (int i = 0; i < li.size(); i++) {
if (n.equals(li.get(i))) {
inList = true;
}
}
if (inList) {
System.out.println("client table update");
} else {
System.out.println("category and client table update");
}
You can simply use contains() to check whether the name exists in the list i.e.
if(li.contains(n)){
System.out.println("client table update");
}
else{
System.out.println("category and client table update");
}
String n = scann.nextLine();
List<String> li = new ArrayList<>();
li.add("abc");
li.add("def");
li.add("ghi");
li.add("jkl");
for (String data : li) {
if (li.contains(n)) {
System.out.println("client table update");
} else {
System.out.println("category and client table update");
}
}

Getting ArrayList with SQLOpenHelper not working

I have a problem with my SQLiteOpenHelper class.
I have a database with printer manufacturers and details of any kind of printer.
I try to get all manufacturer from my database with this code and returning them in a arraylist.
// Read database for All printer manufacturers and return a list
public ArrayList<String> getPrManufacturer(){
ArrayList<String> manufacturerList = new ArrayList<String>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(CoDeskContract.Printer.TABLE_NAME,
printerManuProjection, null, null, null, null, null,null);
// If cursor is not null and manufacturer List
// does not contains Manufacturer in the list then add it!
if ((cursor != null) && (cursor.getCount()>0)){
cursor.moveToFirst();
do {
String cursorManufacturer = cursor.getString(0);
//Checking for manufacturer in the list
for(String manufacturerInList:manufacturerList){
if (!manufacturerInList.equals(cursorManufacturer))
manufacturerList.add(cursorManufacturer);
}
}while(cursor.moveToNext());
}
// Return list of manufacturers from database
return manufacturerList;
}
I want every manufacturer to be once in a list.
Somehow i cant to get it to work.
Im still a newbie.
Thanks for any Help.
You can also use the distinct keyword in SQLite (http://www.sqlite.org/lang_select.html). Use SQLiteDatabase.rawQuery(String query, String[] args) for that.
db.rawQuery("SELECT DISTINCT name FROM " + CoDeskContract.Printer.TABLE_NAME,null);
There are two issues:
In the beginning, when your list manufacturerInList is empty then it will not go inside for(String manufacturerInList:manufacturerList){ loop and hence it will never add any entry in the list.
Once you fix your problem 1, still it will not work as if (!manufacturerInList.equals(cursorManufacturer)) checks against each entry in the list and adds the non matching entry in the list possibly multiple times.
To fix the issue, you have two options.
Option1: Use contains as:
if (!manufacturerList.contains(cursorManufacturer)) {
manufacturerList.add(cursorManufacturer);
}
Option2: Use a matchFound boolean flag as:
String cursorManufacturer = cursor.getString(0);
boolean matchFound = false;
//Checking for manufacturer in the list
for(String manufacturerInList:manufacturerList){
if (manufacturerInList.equals(cursorManufacturer)){
matchFound = true;
break;
}
}
if(!matchFound){ // <- doesn't exit in the list
manufacturerList.add(cursorManufacturer);
}
Use ArrayList.contains(Object elem) to check if item is exist in ArrayList or not Change your code as:
// does not contains Manufacturer in the list then add it!
if ((cursor != null) && (cursor.getCount()>0)){
cursor.moveToFirst();
do {
String cursorManufacturer = cursor.getString(0);
//Checking for manufacturer in the list
if (!manufacturerList.contains(cursorManufacturer)) {
manufacturerList.add(cursorManufacturer);
} else {
System.out.println("cursorManufacturernot found");
}
}while(cursor.moveToNext());
}

Android: IndexOutOfBounds Error when deleting row in ListView

I have an application that has 2 screens. The first screen has a ListView of movies with a row consisting of 3 Elements: Title, Date and Gross declared in strings.xml. The user has the option of adding a movie by clicking the menu button, which sends him to another screen. The second screen has 3 Edit texts that correspond to Title Date and Gross, which is alphabetically sorted straight away when it returns to screen 1.
Similarly, the user can also Edit/Delete entries by long clicking a row thatbrings up a context menu. The Edit function works like this:
a.) User long clicks Titanic and chooses Edit
b.) Row gets deleted, and user is brought to screen 2
c.) Edit texts are populated with the initial data from the deleted Row
d.) When user edits data, new movie is added at the bottom of the ListView.
The problem arises when the user deletes this new movie at the bottom of the ListView. Logcat gives a
java.lang.IndexOutOfBoundsException: Invalid index 50, size is 50
Here is my code (Take note I am using Perst to persist data, but I don;t think that won't really matter with my problem):
case R.id.contextedit:
Lab9_082588FetchDetails row = (Lab9_082588FetchDetails) getListView()
.getItemAtPosition(info.position);
Intent editData = new Intent(MovieList.this, Lab9_082588Edit.class);
String startTitle = row.getTitle();
String startGross = row.getGross();
String startDate = row.getDate();
editData.putExtra(Lab9_082588Edit.TITLE_STRING, startTitle);
editData.putExtra(Lab9_082588Edit.GROSS_STRING, startGross);
editData.putExtra(Lab9_082588Edit.DATE_STRING, startDate);
startActivityForResult(editData, MovieList.EDIT_MOVIE);
int posEdit = info.position;
String editTitle = results.get(info.position).getTitle();
results.remove(posEdit);
adapter.notifyDataSetChanged();
//Perst
Index<Lab9_082588FetchDetails> rootEdit = (Index<Lab9_082588FetchDetails>) db
.getRoot();
rootEdit.remove(editTitle, results.get((int) info.id));
db.setRoot(rootEdit);
return true;
Edit Class:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection using item.getItemId()
switch (item.getItemId()) {
case R.id.edit:
next();
break;
}
return true;
}
private void next() {
// TODO Auto-generated method stub
EditText movieTitle = (EditText) findViewById(R.id.etTitle);
EditText movieGross = (EditText) findViewById(R.id.etGross);
EditText movieDate = (EditText) findViewById(R.id.etDate);
String title = movieTitle.getText().toString();
String gross = movieGross.getText().toString();
String date = movieDate.getText().toString();
if ((title.length() > 0) && (gross.length() > 0)
&& (date.length() == 4)) {
Intent hobby = getIntent();
hobby.putExtra(Lab9_082588Edit.TITLE_STRING, title);
hobby.putExtra(Lab9_082588Edit.GROSS_STRING, gross);
hobby.putExtra(Lab9_082588Edit.DATE_STRING, date);
setResult(RESULT_OK, hobby);
finish();
}
}
Delete function:
int posDelete = info.position;
String deleteTitle = results.get(
info.position).getTitle();
results.remove(posDelete);
adapter.notifyDataSetChanged();
Index<Lab9_082588FetchDetails> rootDelete = (Index<Lab9_082588FetchDetails>) db
.getRoot();
rootDelete.remove(deleteTitle,
results.get(info.position));
db.setRoot(rootDelete); //Perst
return;
OnActivityResult (Edit):
case EDIT_MOVIE:
Lab9_082588FetchDetails edittedMovie = new Lab9_082588FetchDetails();
NumberFormat formatterEdit = new DecimalFormat("###,###,###");
edittedMovie.setTitle(data
.getStringExtra(Lab9_082588Add.TITLE_STRING));
edittedMovie.setGross("$"
+ formatterEdit.format(Double.parseDouble(data
.getStringExtra(Lab9_082588Add.GROSS_STRING))));
edittedMovie.setDate(data
.getStringExtra(Lab9_082588Add.DATE_STRING));
results.add(edittedMovie);
adapter.notifyDataSetChanged();
Populating the Listview:
for (int i = 0; i < items.size(); i++) {
Lab9_082588FetchDetails sr = new Lab9_082588FetchDetails();
sr.setTitle(items.get(i).getTitle());
sr.setGross(items.get(i).getGross());
sr.setDate(items.get(i).getDate());
results.add(sr);
Collections.sort(results, ignoreCaseStart);
}
How do I remedy this?
This problem occurs because in your delete function, you first remove the element from the results collection("results.remove(posDelete);"), and then, a few lines later, you call "results.get(info.position)" to fetch a parameter for the rootDelete.remove call, but which is already removed.
If the element is the last element of your collection, let's say the 50th element, the value for "info.position" is 50. You remove one element, so the number of elements is now 49. In the rootDelete.remove line you call results.get(50), which produces the error.

dynamic drop down menu with values returned in JSON format in Java

I am developing an application which sets up an http connection with a website and by using GET call. I am getting Data Set IDs and I want to show these DATA SET ID's in a drop down menu, so that the user can select it.
I also want to store the selected data set id in a variable as it will be used in future in my application.
This is how I am getting the values in DSid (string array to store data set id returned in JSON format )
URL urlDS = new URL("http:/link.json?key="+APIkey);
HttpURLConnection httpConDS = (HttpURLConnection) urlDS.openConnection();
StringBuilder sbDS = new StringBuilder();
while ((inputLineDS = inDS.readLine()) != null) {
sbDS.append(inputLineDS);
System.out.println(inputLineDS);
}
String ResultDS;
ResultDS=sbDS.toString();
System.out.println("result:"+ResultDS);
String jsonSourceDS = ResultDS;
JSONArray arrayDS;
try {
arrayDS = new JSONArray(jsonSourceDS);
for (int i = 0; i < arrayDS.length(); i++) {
JSONObject firstObject = (JSONObject) arrayDS.get(i);
System.out.println("Data set ID " + firstObject.getString("datasetId"));
DSid[i]=firstObject.getString("datasetId");
++countDSid;
}
}
I used JComboBox but it is not helping me.
combo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
String selected = (String) cb.getSelectedItem();
labelp3.setText("You selected: " + selected);
}
} );
and this in the constructor of my Log-in class
JComboBox combo = new JComboBox(DSid);
This DSid is an string array which is storing the data set id, using GET call.
I am not able to create the drop down menu with the data set ids, it is being empty if I am using these.
So how can I create dynamic drop down menu and also store the selected value in a variable?
The values shown in data set (2,3) are given by me statically in the DSid array in the class login.

Categories

Resources