I have a simple class named A which has two private fields.
public class A {
private String a;
private String b;
} // A
When I get all declared fields from class instance, I get one extra field named $change of type com.android.tools.fd.runtime.IncrementalChange. Where is it coming from ? I am totally not getting this.
Field[] fields = cls.getDeclaredFields();
for (int i = 0, len = fields.length; i < len; i++) {
Field field = fields[i];
field.setAccessible(true);
Log.d("TAG", field.getName());
if (field.isAnnotationPresent(Primary.class)) {
query += getFromalName(field.getName()).toUpperCase() + " " + getSchemaType(field.getType().getSimpleName()) + " PRIMARY KEY, ";
continue;
}
if (field.isAnnotationPresent(NotNull.class)) {
query += getFromalName(field.getName()) + " " + getSchemaType(field.getType().getSimpleName()) + " NOT NULL, ";
continue;
}
query += getFromalName(field.getName()) + " " + getSchemaType(field.getType().getSimpleName()) + ", ";
} // end for
query = query.substring(0, query.lastIndexOf(","));
query += " )";
It was added to support instant run. Disabling instant run solved the problem. here
is the link to android issue tracker
Related
I have a palette who's model is populated by a user search of customers. This works perfectly when searching initially, however once a customer is selected and the user continues to search for more customers to select a NPE is thrown.
Code from .tml
<t:palette t:id="custSelect" model="customerModel" t:encoder="stringValueEncoder"
availableLabel="Search Results" t:selected="custSelected" value="custSelected">
${custSelected}
</t:palette>
Coresponding .java
Object listResults(List<TbgWebIntCustomer> customers) {
log.debug("LISTRESULTS");
customerList = new ArrayList<String>();
if (customerList != null) {
customerList.clear();
if (request.isXHR()) {
ajaxResponseRenderer.addRender(resultZone);
}
}
String result;
log.debug("LISTRESULTS2 " + customers.size());
for (int i = 0; i <= customers.size() - 1; i++) {
log.debug("counter: " + i);
TbgWebIntCustomer currentCustomer = customers.get(i);
String customerNumber = currentCustomer.getCustomerId();
// Remove leading zeros
String customerName = currentCustomer.getLocationName();
result = customerNumber + " - " + customerName + " - "
+ currentCustomer.getCity();
log.debug(result);
customerList.add(result);
}
log.debug("LISTRESULTS3");
log.debug("customer list size: " + customerList.size());
getCustomerModel();
log.debug("customermodel after customerlist: "
+ getCustomerModel().size());
if (customerList.size() == 100) {
resultsMessage = "Search returned over 100 results. Showing top 100.";
log.debug(resultsMessage);
} else {
String numResults = Integer.toString(customerList.size());
resultsMessage = "Search returned " + numResults + " customers";
log.debug(resultsMessage);
}
log.debug("LISTRESULTS4");
log.debug("customerModel returns at i 0: " + getCustomerModel().get(0));
return request.isXHR() ? resultZone.getBody() : null;
}
Note: getCustomerModel() returns getCustomerList().
I understand that NPEs in Palette happen when one of the selected options is not present in the model you passed to it however I can't identify where it is I'm doing this. I can post setupRender() code if necessary, just trying to keep OP compact.
Connection conn = SqlConnection.getConnection("jdbc:mysql://localhost:3306/stocks");
Statement statement = conn.createStatement();
File path = new File("/Users/Zack/Desktop/JavaDB/BALANCESHEETS");
for(File file: path.listFiles()) {
if (file.isFile()) {
String fileName = file.getName();
String ticker = fileName.split("\\_")[0];
if (ticker.equals("ASB") || ticker.equals("FRC")) {
if (ticker.equals("ASB")) {
ticker = ticker + "PRD";
}
if (ticker.equals("FRC")) {
ticker = ticker + "PRD";
}
}
//CSVReader reader = new CSVReader(new FileReader(file));
//List entries = reader.readAll();
//ArrayList<String> entry = new ArrayList<String>();
Reader reader = new BufferedReader(new FileReader(file));
StringBuilder builder = new StringBuilder();
int c;
while ((c = reader.read()) != -1) {
builder.append((char) c);
}
String string = builder.toString();
ArrayList<String> stringResult = new ArrayList<String>();
if (string != null) {
String[] splitData = string.split("\\s*,\\s*|\\n");
for (int i = 0; i <splitData.length; i++) {
if (!(splitData[i] == null) || !(splitData[i].length() ==0)) {
stringResult.add(splitData[i].trim());
}
}
}
String columnName = null;
int yearCount = 0;
for (int i = 0; i < stringResult.size(); i++) {
int sL = stringResult.get(i).length();
for (int x = 0; x < sL; x++) {
if (Character.isLetter(stringResult.get(i).charAt(x))) {
yearCount = 0;
System.out.println("index: " + i);
columnName = stringResult.get(i);
columnName = columnName.replace(" ", "_");
System.out.println(columnName);
i++;
break;
}
}
yearCount++;
String value = stringResult.get(i);
System.out.println("Year: " + stringResult.get(yearCount) + " Value: " + value + " Stock: " + ticker + " Column: " + columnName );
if (!(columnName == null)) {
String writeValues = "INSERT INTO BalanceSheet (ticker, Year, " + columnName + ") "
+ "VALUE ('" + ticker + "','" + stringResult.get(yearCount) + "','" + value + "')";
String writeValues2 = "UPDATE BalanceSheet "
+ "SET ticker = '" + ticker + "', "
+ "Year = '" + stringResult.get(yearCount) + "', "
+ columnName + " = '" + value + "' "
+ "WHERE ticker = '" + ticker + "'";
statement.executeUpdate(writeValues2);
}
}
Towards the bottom of the code are two queries I tried, I'm trying to get all data organized by ticker and year into a table, "writeColumns" works but it's making a new row for every new "value" put into "columnName". My second attempt "writeColumns2" doesn't do anything.
I want to update the same row with a certain year for all values and then move onto the next year, then next ticker.
If I have understood your question correctly, you want to insert a row if it doesn't exists but update the values if it already does. You need to use ON DUPLICATE KEY UPDATE
String writeValues = "INSERT INTO BalanceSheet (ticker, Year, " + columnName + ") "
+ "VALUES (?,?,?) "
+"ON DUPLICATE KEY UPDATE " + columnName +"=?";
Statement statement = conn.prepareStatement(writeValues);
statement.setString(1,ticker);
statement.setString(2,stringResult.get(yearCount));
statement.setString(3, value);
This will solve your immidiate problem provided you create a UNIQUE index on ticker,year
However there are lot's of other issues here.
An update for each column - Currently you are doing an insert/update for each column on the table. What you are supposed to do is to insert update all the columns at one.
You are not using prepared statements addressed in my code sample
You shouldn't be doing this at all the best way to batch process data is to use MYSQL's built in LOAD DATA INFILE command. If your data is not in a format that can be easily imported into mysql, what your Java code can do is to transform it into a format that can be. Such a code will be a lot simpler and neater than what you have now
How can I add in my return findSingleOrNoItem() at the end of the statement to display the for loop counter getClassName() and getAbsolutePercentage() in the findSingleOrNoItem() statement? The reason I added a counter, some will have 4 values of getClassName() and getAbsolutePercentage() and some will have 6 values? so this will depend on the cosModel that gets passed on setParameter 1.
#Override
public TrafficProfile getTrafficProfileByCosClassAllocationNew(CosModel cosModel, Direction direction,
List<ClassOfServiceAllocation> cosClassAllocation, RouterType routerType) throws Exception {
EntityManager em = getEntityManager();
logger.info("Starting getTrafficProfileByCosClass2Allocations cos2 " );
Query query = em.createNativeQuery(buildTrafficProfileByCosClassAllocationQueryNew(cosModel, direction, cosClassAllocation, routerType), TrafficProfile.class);
query.setParameter(1, cosModel.name());
query.setParameter(2, direction.name());
int i= 2;
for(ClassOfServiceAllocation alloc : cosClassAllocation){
query.setParameter(i++, alloc.getClassName());
query.setParameter(i++, alloc.getAbsolutePercentage());
}
return findSingleOrNoItem(query, "Traffic_Profile", "cos_model = " + cosModel.name() + ", direction = " + direction.name() + ?;
}
I am following this existing code below but this is only for cos6. I will have both cos4 and cos6 so I can't hard coded.
#Override
public TrafficProfile getTrafficProfileByCosClassAllocations(Direction direction,
ClassOfService6Allocations cosClassAllocation, RouterType routerType) throws Exception {
EntityManager em = getEntityManager();
logger.info("Starting getTrafficProfileByCosClass6Allocations cos6" );
Query query = em.createNativeQuery(buildTrafficProfileByCosClassAllocationsQuery(direction, cosClassAllocation, routerType), TrafficProfile.class);
query.setParameter(1, "cos6");
query.setParameter(2, direction.name());
query.setParameter(3, cosClassAllocation.getCos1());
query.setParameter(4, cosClassAllocation.getCos2V());
query.setParameter(5, cosClassAllocation.getCos2());
query.setParameter(6, cosClassAllocation.getCos3());
query.setParameter(7, cosClassAllocation.getCos4());
query.setParameter(8, cosClassAllocation.getCos5());
return findSingleOrNoItem(query, "Traffic_Profile", "cos_model = cos6, direction = " + direction.name() + " cos1 = " + cosClassAllocation.getCos1()
+ " cos2v = " + cosClassAllocation.getCos2V() + " cos2 = " + cosClassAllocation.getCos2()
+ " cos3 = " + cosClassAllocation.getCos3() + " cos4 = " + cosClassAllocation.getCos4() + " cos5 = " + cosClassAllocation.getCos5() );
}
Assuming that your ClassOfService6Allocations and supposedly ClassOfService4Allocations inherit from ClassOfServiceAllocation you can check, inside your for-loop, what is the type of the current object and then cast to this class, for instance:
for(ClassOfServiceAllocation alloc : cosClassAllocation) {
if (alloc instanceof ClassOfService6Allocations) {
ClassOfService6Allocations alloc6 = (ClassOfService6Allocations) alloc;
//set your parameters using the alloc6 object
} else if (alloc instanceof ClassOfService4Allocations) {
ClassOfService4Allocations alloc4 = (ClassOfService4Allocations) alloc;
//set your parameters using the alloc4 object
}
I'm trying to make my own ORM framework. I get the values from object into arrayList and I'm trying to save them in one time. I have to make for loop to save them all, but I'm confused how to make it?
prepareteState = connect.prepareStatement(Query);
for (int y = 1; y <= obs.size() ; y++) {
for(Object obj : obs){
prepareteState.setObject(y, obj);
System.out.println(Query);
System.out.println(prepareteState.toString());
}
}
prepareteState.execute();
thanks for good advices but, i found the solution :) it is a little bit different than the first idea but, works fine for me:) instead of using prepareState and setObject one by one i`m using StringBuilder to make String and execute query
private String makeInsertQuery(List<String> listOfColumnsNames, List<Object> listOfParameters, String tableName){
StringBuilder columns = new StringBuilder();
StringBuilder parameters = new StringBuilder();
String query = null;
if(listOfColumnsNames != null && listOfColumnsNames.size() != 0 && listOfParameters != null && listOfParameters.size() != 0 && tableName != null){
for(String string : listOfColumnsNames){
columns.append(string + ",");
}
columns.deleteCharAt(columns.length() - 1);
for(Object object : listOfParameters){
parameters.append ("'" + object + "'" + ",");
}
parameters.deleteCharAt(parameters.length() - 1);
query = "INSERT " + "INTO " + tableName + " ( " + columns.toString() + " ) " + " VALUES " + "( " + parameters.toString() + " )" ;
}
//TODO if you need check for null
return query;
}
I'm using android.util.Log
class Foo
{
private void boo()
{
// This is the basic log of android.
Log.i("tag", "Start");
}
}
I want the log should be printed [Foo::boo] Start.
Can I get the class and function name in Java? Then how do I wrap the code?
here
UPDATED
String tag = "[";
tag += this.getClass().toString();
tag += " :: ";
tag += Thread.currentThread().getStackTrace()[1].getMethodName().toString();
tag += "]";
Log.i(tag, "Message");
this.getClass().toString() will return class name as String
UPDATE
if function is static then use following code
String tag = "[";
tag += Thread.currentThread().getStackTrace()[1].getClassName().toString();
tag += " :: ";
tag += Thread.currentThread().getStackTrace()[1].getMethodName().toString();
tag += "]";
Log.i(tag, "Message");
Get The Current Class Name and Function Name :
Log.i(getFunctionName(), "Start");
private String getFunctionName()
{
StackTraceElement[] sts = Thread.currentThread().getStackTrace();
if(sts == null)
{
return null;
}
for(StackTraceElement st : sts)
{
if(st.isNativeMethod())
{
continue;
}
if(st.getClassName().equals(Thread.class.getName()))
{
continue;
}
if(st.getClassName().equals(this.getClass().getName()))
{
continue;
}
return mClassName + "[ " + Thread.currentThread().getName() + ": "
+ " " + st.getMethodName() + " ]";
}
return null;
}
You can use these methods of java.lang.Class class
getClass().getname() - to get the name of the class
getClass().getMethods() - to get the methods declared in that class.