I got following code and there is this error (I tried to keep the code as short as possible, ignore the getColumnCount etc. functions just the constructor):
The following code is used to make a JTable in Swing by an SQLite statement, I need the booleans for checkboxes (Yes I know I have to edit/add an function, but I wanted to keep the code as small as possible).
Code:
package view;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.table.AbstractTableModel;
import controller.Database;
class Test extends AbstractTableModel {
Database db = new Database();
ResultSet rs;
private String[] columnNames = {"Vorname", "Nachname", "E-Mail", "Anrede", "Jahrgang", "Ablösung", "Scheibe", "Waffe", "Gruppe", "Verpflegung", "Aktiv"};
Object[][] data;
public Test(){
int result = 0;
try {
rs = db.stat.executeQuery("select count(*) as schuetzencount from schuetze;");
result = Integer.parseInt(rs.getString("schuetzencount"));
data = new String[result][11];
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rs = db.stat.executeQuery("select * from schuetze as s join waffe as w on w.Waffe_ID = s.Waffe_ID join gruppe as g on g.Gruppe_ID = s.Gruppe_ID join anrede as a on a.Anrede_ID = s.Anrede_ID join verpflegung as v on v.Verpflegung_ID = s.Verpflegung_ID;");
int counter = 0;
while(rs.next()){
data[counter][1] = rs.getString("Schuetze_Nachname");
data[counter][0] = rs.getString("Schuetze_Vorname");
data[counter][4] = rs.getString("Schuetze_Jahrgang");
data[counter][2] = rs.getString("Schuetze_Email");
data[counter][5] = rs.getString("Schuetze_Abloesung");
data[counter][6] = rs.getString("Schuetze_Scheibe");
data[counter][7] = rs.getString("Waffe_Name");
data[counter][8] = rs.getString("Gruppe_Name");
data[counter][3] = rs.getString("Anrede_Name");
data[counter][9] = rs.getString("Verpflegung_Name");
data[counter][10] = true;
counter++;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public int getColumnCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getRowCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getValueAt(int arg0, int arg1) {
// TODO Auto-generated method stub
return null;
}
public static void main(String[] args) {
Test t = new Test();
}
}
Error:
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Boolean
at view.Test.<init>(Test.java:43)
at view.Test.main(Test.java:72)
If I'll do
Object[][] data = {{"Test", "Test","Test","Test","Test","Test","Test","Test","Test","Test",true}}
it works, but that's not what I need. Then I tried to do a Object[] and fill the Booleans in and then add the Object[] into the data[][] but this also didn't work.
I hope someone can help me, thanks.
Greetz.
You have Array of Strings and try to put Boolean there in line
data[counter][10] = true;
That is not allowed.
When You do
Object[][] data = {{"Test", "Test","Test","Test","Test","Test","Test","Test","Test","Test",true}}
Java creates for you array of Objects
Like:
Object[][] o = new Object[1][6];
o[0][2] = true; // it works
Your array expects a String as dataType, on the other hand are you trying to put a boolean into it.
data[counter][10] = true;
a simple solution to this is using a string "true"instead of the primitive booleantype (or parse it to string)
data[counter][10] = "true";
You cannot insert a boolean value to an array of String. That is the problem :
data = new String[result][11];
data[counter][10] = true;
At least insert it as a String and parse it when neccessary.
You have defined data as matrix of Objects, but instantiated it as matrix of String.
That's why, at runtime, you have this type mismatch exception.
Either instantiate it like:
Object[][] o = new Object[1][6];
or
replace boolean value with string:
data[counter][10] = "true";
The problem is here:
data = new String[result][11];
You declare the array of String and you do this
data[counter][10] = true;
You have two options:
declare data as
new Object[result][11];
put string instead of boolean
data[counter][10] = Boolean.TRUE.toString();
Related
The current question is the second part of this ODCI related question.
I have implemented a collection type in Oracle SQL which is practically defined as a type and a table of that type.
CREATE TYPE row_type AS OBJECT
(
C1 VARCHAR2(50),
C2 VARCHAR2(50),
C3 VARCHAR2(50)
);
/
CREATE TYPE row_type_set AS TABLE OF row_type;
Also, I have defined an ODCI type with its implementation as a Java Stored Procedure within database:
SQL:
CREATE OR REPLACE TYPE ODCIImpl AS OBJECT (
key INTEGER,
STATIC FUNCTION ODCITableStart(sctx OUT ODCIImpl, cur SYS_REFCURSOR)
RETURN NUMBER
AS LANGUAGE JAVA
NAME 'ODCIImpl.ODCITableStart(oracle.sql.STRUCT[], java.sql.ResultSet) return java.math.BigDecimal',
MEMBER FUNCTION ODCITableFetch(self IN OUT ODCIImpl, nrows IN NUMBER,
outSet OUT row_type_set) RETURN NUMBER
AS LANGUAGE JAVA
NAME 'ODCIImpl.ODCITableFetch(java.math.BigDecimal, oracle.sql.ARRAY[]) return java.math.BigDecimal',
MEMBER FUNCTION ODCITableClose(self IN ODCIImpl) RETURN NUMBER
AS LANGUAGE JAVA
NAME 'ODCIImpl.ODCITableClose() return java.math.BigDecimal'
);
/
Java Stored Procedure:
import java.io.*;
import java.util.*;
import oracle.sql.*;
import java.sql.*;
import java.math.BigDecimal;
import oracle.CartridgeServices.*;
// stored context type
public class StoredCtx
{
ResultSet rset;
public StoredCtx(ResultSet rs) { rset=rs; }
}
// implementation type
public class ODCIImpl implements SQLData
{
private BigDecimal key;
final static BigDecimal SUCCESS = new BigDecimal(0);
final static BigDecimal ERROR = new BigDecimal(1);
final static int MAX_COLUMNS = 3;
// Implement SQLData interface.
String sql_type;
public String getSQLTypeName() throws SQLException
{
return sql_type;
}
public void readSQL(SQLInput stream, String typeName) throws SQLException
{
sql_type = typeName;
key = stream.readBigDecimal();
}
public void writeSQL(SQLOutput stream) throws SQLException
{
stream.writeBigDecimal(key);
}
// type methods implementing ODCITable interface
static public BigDecimal ODCITableStart(STRUCT[] sctx,ResultSet rset)
throws SQLException
{
Connection conn = DriverManager.getConnection("jdbc:default:connection:");
// create a stored context and store the result set in it
StoredCtx ctx=new StoredCtx(rset);
// register stored context with cartridge services
int key;
try {
key = ContextManager.setContext(ctx);
} catch (CountException ce) {
return ERROR;
}
// create a ODCIImpl instance and store the key in it
Object[] impAttr = new Object[1];
impAttr[0] = new BigDecimal(key);
StructDescriptor sd = new StructDescriptor("ODCIIMPL",conn);
sctx[0] = new STRUCT(sd,conn,impAttr);
return SUCCESS;
}
public BigDecimal ODCITableFetch(BigDecimal nrows, ARRAY[] outSet)
throws SQLException
{
Connection conn = DriverManager.getConnection("jdbc:default:connection:");
// retrieve stored context using the key
StoredCtx ctx;
try {
ctx=(StoredCtx)ContextManager.getContext(key.intValue());
} catch (InvalidKeyException ik ) {
return ERROR;
}
// get the nrows parameter, but return up to 10 rows
int nrowsval = nrows.intValue();
// create a vector for the fetched rows
Vector v = new Vector(nrowsval);
int i=0;
StructDescriptor outDesc =
StructDescriptor.createDescriptor("ROW_TYPE", conn);
Object[] out_attr = new Object[MAX_COLUMNS];
ResultSetMetaData rsmd = ctx.rset.getMetaData();
int columnsNumber = rsmd.getColumnCount();
while(nrowsval>0 && ctx.rset.next()){
for(int j = 0; j < columnsNumber; j++) {
if(j == MAX_COLUMNS)
break;
out_attr[j] = (Object)ctx.rset.getString(j+1);
}
v.add((Object)new STRUCT(outDesc, conn, out_attr));
i+=1;
nrowsval-=1;
}
// return if no rows found
if(i==0) return SUCCESS;
// create the output ARRAY using the vector
Object out_arr[] = v.toArray();
ArrayDescriptor ad = new ArrayDescriptor("ROW_TYPE_SET",conn);
outSet[0] = new ARRAY(ad,conn,out_arr);
return SUCCESS;
}
public BigDecimal ODCITableClose() throws SQLException {
// retrieve stored context using the key, and remove from ContextManager
StoredCtx ctx;
try {
ctx=(StoredCtx)ContextManager.clearContext(key.intValue());
} catch (InvalidKeyException ik ) {
return ERROR;
}
// close the result set
Statement stmt = ctx.rset.getStatement();
ctx.rset.close();
if(stmt!=null) stmt.close();
return SUCCESS;
}
}
After all of this, I've implemented a pipelined function that can be called using a cursor.
CREATE OR REPLACE FUNCTION Exec_Remote_SQL_JSP(p SYS_REFCURSOR) RETURN row_type_set
PIPELINED USING ODCIImpl;
/
My question now is how can we implement an ODCITableDescribe method in a Java Stored Procedure in order to output any data type in the emulated table? First of all, is it possible at all? I didn't seem to find any relevant information about this on the Oracle documentation from here and here
If it is possible to do so, it is self-explainable that we do not need anymore the collection types mentioned at the beginning. The emulated table should have the same size and data types as the table from which we intend to select information.
I am trying to open a csv file using openCSV, iterate over every column and if the userID is different write a new JavaBean pair at the end of the file.
The problem is that the reader only checks the first column of my file and not the whole file. While created, the file contains only a header and nothing else. The program will check every column and if the sudoID is different it will write it to the file. If the sudoID in the first line is equal to the the one imported from my main class it will recognise it and not write it. But if this -same- sudoID is in the second row it will not recognise it and will write it again.
For instance, if my CSV looks like this it will work:
"Patient_id Pseudo_ID",
"32415","PAT106663926"
If it looks like this it will re-write the sudoID:
"Patient_id Pseudo_ID",
"32416","PAT104958880"
"32415","PAT106663926"
Thanks!
My Code:
public class CSVConnection {
#SuppressWarnings({ "deprecation", "resource", "rawtypes", "unchecked" })
public String getID(String sID,String pseudoID) throws IOException, CsvDataTypeMismatchException, CsvRequiredFieldEmptyException{
try {
CsvToBean csv = new CsvToBean();
String csvFilename = "CsvFile.csv";
Writer writer= new FileWriter(csvFilename,true);
CSVReader csvReader = new CSVReader(new FileReader(csvFilename),',','"',1);
ColumnPositionMappingStrategy strategy = new ColumnPositionMappingStrategy();
strategy.setType(PatientCSV.class);
String[] columns = new String[] {"patID","pseudoID"};
strategy.setColumnMapping(columns);
//Set column mapping strategy
StatefulBeanToCsv<PatientCSV> bc = new StatefulBeanToCsvBuilder<PatientCSV>(writer).withMappingStrategy(strategy).build();
List patList = csv.parse(strategy, csvReader);
for (Object patObj : patList) {
PatientCSV pat = (PatientCSV) patObj;
if(((PatientCSV) patObj).getPatID().equals(sID)){
return pat.getPseudoID();
}
else
{
PatientCSV pat1 = new PatientCSV();
pat1.setPatID(sID);
pat1.setPseudoID(pseudoID);
patList.add(pat1);
/*Find a way to import it to the CSV*/
bc.write(pat1);
writer.close();
return pseudoID;
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String [] args) throws IOException, CsvDataTypeMismatchException, CsvRequiredFieldEmptyException{
CSVConnection obj = new CSVConnection();
String sID="32415";
String pseudoID="PAT101830150";
obj.getID(sID,pseudoID);
}
}
and the Java Bean :
public class PatientCSV {
private String patID;
private String pseudoID;
public String getPatID() {
return patID;
}
public void setPatID(String patID) {
this.patID = patID;
}
public String getPseudoID() {
return pseudoID;
}
public void setPseudoID(String pseudoID) {
this.pseudoID = pseudoID;
}
public PatientCSV(String patID, String pseudoID) {
super();
this.patID = patID;
this.pseudoID = pseudoID;
}
public PatientCSV() {
super();
// TODO Auto-generated constructor stub
}
public String toString()
{
return "Patient [id=" + patID + ", pseudoID=" + pseudoID + "]";
}
}
Lets inspect your for loop
for (Object patObj : patList) {
PatientCSV pat = (PatientCSV) patObj;
if(((PatientCSV) patObj).getPatID().equals(sID)){
return pat.getPseudoID();
}
else
{
PatientCSV pat1 = new PatientCSV();
pat1.setPatID(sID);
pat1.setPseudoID(pseudoID);
patList.add(pat1);
/*Find a way to import it to the CSV*/
bc.write(pat1);
writer.close();
return pseudoID;
}
}
So in the case you mention it is not working as expected, meaning that the line that matches your input is the second line:
"Patient_id Pseudo_ID",
"32416","PAT104958880"
"32415","PAT106663926"
So you call: getID("32415", "PAT106663926")
What happens in your loop is:
You take the first element of your csv patients, the one with id: 32416,
check if it matches with the id given as input to your method, 32415.
It does not match so it goes to the else part. There it creates the new patient (with the same patID and pseudoID as the 2nd row of your csv) and stores it in the file.
So by now you should have 2 entries in your csv with the same data "32415","PAT106663926".
I think that this is the error, in your for loop you should check against all entries if there is a match, and then create the patient and store it to the csv.
An example:
PatientCSV foundPatient = null;
for (Object patObj : patList) {
PatientCSV pat = (PatientCSV) patObj;
if(((PatientCSV) patObj).getPatID().equals(sID)){
foundPatient = pat;
}
}
if (foundPatient == null) {
foundPatient = new PatientCSV();
foundPatient.setPatID(sID);
foundPatient.setPseudoID(pseudoID);
patList.add(foundPatient);
/*Find a way to import it to the CSV*/
bc.write(foundPatient);
writer.close();
}
return foundPatient.getPseudoID();
P.S. The above example is written very quickly, just to give you the idea what needs to be done.
I am trying to create JSON data store into ArrayList and load on ListView. Now I have successfully stored my JSON data into ArrayList. But the problem is I have maintaining multiple column listview. I need to List out my first array on first column.
Below I have tried something, multiple columns with array. But exactly I dont know how to do that. Please help me, I am new developer for Android.
// I need to add my array into first column
private ArrayList<String> myarray = new ArrayList<String>();
//JSON string data's I have loaded
myarray.add(jsondata);
//LISTVIEW WATCHLIST
ListView listView=(ListView)findViewById(R.id.listView1);
list=new ArrayList<HashMap<String,String>>();
HashMap<String,String> temp=new HashMap<String, String>();
temp.put(FIRST_COLUMN, "Minchu");
temp.put(SECOND_COLUMN, "USA");
temp.put(THIRD_COLUMN, "City");
temp.put(FOURTH_COLUMN, "Ranks");
list.add(temp);
.
.
.
.
ListViewAdapters adapter=new ListViewAdapters(this,list);
listView.setAdapter(adapter);
NOTE : Above HashMap to putted manual data. I need to load first array first columns, second array second columns.
You need to create model for your json object see below code.
import java.io.Serializable;
public class PersonDetailsItem implements Serializable {
public int id;
private String intEducationEN, intVillageID;
public PersonDetailsItem(int id, String name, String phoneNo, String email) {
// TODO Auto-generated constructor stub
this.id = id;
this.strNameEN = name;
this.strEmailid = email;
}
public String getIntVillageID() {
return intVillageID;
}
public void setIntVillageID(String intVillageID) {
this.intVillageID = intVillageID;
}
public String getIntEducationEN() {
return intEducationEN;
}
public void setIntEducationEN(String intEducationEN) {
this.intEducationEN = intEducationEN;
}
public PersonDetailsItem() {
// TODO Auto-generated constructor stub
}
Then set the value for the model form parsing json received string.
private void parseJson(String rs) {
private ArrayList<PersonDetailsItem> listData = new ArrayList<PersonDetailsItem>();;
// TODO Auto-generated method stub
listData = new ArrayList<PersonDetailsItem>();
spinerPersonData = new ArrayList<SpinerItem>();
try {
JSONObject obj = new JSONObject(rs);
JSONArray jArray = obj.getJSONArray("Table");
for (int i = 0; i < jArray.length(); i++) {
JSONObject c = jArray.optJSONObject(i);
String intEducationEN = c.getString("intEducationEN");
String intVillageID = c.getString("intVillageID");
PersonDetailsItem personItem = new PersonDetailsItem();
personItem.setIntEducationEN(intEducationEN);
personItem.setIntVillageID(intVillageID);
listData.add(personItem);
}
} catch (JSONException e) { // TODO Auto-generated catch block
e.printStackTrace();
Log.v("perosnJson Error", e.toString());
}
}
set to listadapter
CustomAdapter adapter = new CustomAdapter(MainActivity.this, R.id.listView1, listData);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
enter code here
You can check link for more detail https://github.com/yagneshshinde101/mysamaj/blob/master/MySamaj/src/com/example/mysamajmain/MainActivity.java
I am new to Hive UDTF. I have a requirement where I have to pass string values as Paratmeter in UDTF and the returning Column should be a ArrayList.
I have written the following Code:
public StructObjectInspector initialize(ObjectInspector[] arg0)
throws UDFArgumentException {
ArrayList<String> fieldNames = new ArrayList<String>();
ArrayList<ObjectInspector> fieldOIs = new ArrayList<ObjectInspector>();
fieldNames.add("col1");
stringOI = (PrimitiveObjectInspector) arg0[0];
listOi=(ListObjectInspector) arg0[0];
fieldOIs.add(listOi.getListElementObjectInspector());
return ObjectInspectorFactory.getStandardStructObjectInspector(fieldNames, fieldOIs);
}
#Override
public void process(Object[] record) throws HiveException {
// TODO Auto-generated method stub
String document = (String) stringOI.getPrimitiveJavaObject(record[0]);
if (document == null) {
return;
}
firstColumn=(String) stringOI.getPrimitiveJavaObject(record[0]);
secondColumn=(String) stringOI.getPrimitiveJavaObject(record[1]);
if(outputMapper.containsKey(firstColumn))
{
ArrayList<String> tempList=new ArrayList<String>();
tempList=outputMapper.get(firstColumn);
tempList.add(secondColumn);
outputMapper.put(firstColumn,tempList);
}
else
{
childVendorList=new ArrayList<String>();
childVendorList.add(secondColumn);
outputMapper.put(firstColumn,childVendorList);
}
forward(outputMapper.get(firstColumn));
}
}
And I am getting the following Exception:
java.lang.ClassCastException: org.apache.hadoop.hive.serde2.lazy.objectinspector.primitive.LazyStringObjectInspector cannot be cast to org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector
Can Anyone Help???
listOi=(ListObjectInspector) arg0[0];
fieldOIs.add(listOi.getListElementObjectInspector());
return ObjectInspectorFactory.getStandardStructObjectInspector(fieldNames, fieldOIs);
This arg0[0] is a primitive object inspector. With listOi.getListElementObjectInspector(), just get a similar PrimitiveObjectInspector(like String,Integer is not a List). It should
fieldOIs.add(ObjectInspectorFactory.getStandardListObjectInspector(stringOI ))
This will specific the output column with List of type of stringOI.
I have a list of String which I wish to convert to Json. I am using org\json\me in order to do so. However, I don't know how to continue from here. A little help will be appreciated. Thanks.
This is my code:
public class PhoneData implements JSONAble {
private Display display;
private Form mainScr;
public PhoneData() {
mainScr = new Form("Phone Data");
String imei = IDENInfo.imeiToString(IDENInfo.getIMEI());
String imsi = new String();
try{
imsi=GPRSInfo.imeiToString(SIMCardInfo.getIMSI(), false );
}catch(SIMCardException ioe){}
String majorOS = DeviceInfo.getPlatformVersion();
int content = CodeModuleManager.getModuleHandle("net_rim_bb_phone_api");
String version = CodeModuleManager.getModuleVersion(content); //DeviceInfo.getSoftwareVersion();
String modelnumber = DeviceInfo.getDeviceName(); //get modelnumber
String [] phoneData = new String[] { modelnumber = "Model Number", majorOS = "majorOS", version = "softwareversion"
,imei = "imei", imsi = "imsi"}; // an Array
}
protected void startApp() throws MIDletStateChangeException {
// TODO Auto-generated method stub
display.setCurrent(mainScr);
PhoneData user = new PhoneData();
}
public void fromJSON(String jsonString) {
// TODO Auto-generated method stub
}
public String toJSON() {
// TODO Auto-generated method stub
return null;
}
}
You'll have to put your data inside a Vector, then use the new JSONArray(yourvector) to make a JSONArray.
Unless you specifically want to use org.json's barebones package, maybe have a look at this question.
You could use the Jettison driver with XStream to serialize / deserialize string <-> json :
http://x-stream.github.io/json-tutorial.html
I had used this sometime back - there are some caveats on how the json schema should be for the parser to parse perfectly well.