Search Results

Search found 1459 results on 59 pages for 'arraylist'.

Page 17/59 | < Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >

  • Cast errors with IXmlSerializable

    - by Nathan
    I am trying to use the IXmlSerializable interface to deserialize an Object (I am using it because I need specific control over what gets deserialized and what does not. See my previous question for more information). However, I'm stumped as to the error message I get. Below is the error message I get (I have changed some names for clarity): An unhandled exception of type 'System.InvalidCastException' occurred in App.exe Additional information: Unable to cast object of type 'System.Xml.XmlNode[]' to type 'MyObject'. MyObject has all the correct methods defined for the interface, and regardless of what I put in the method body for ReadXml() I still get this error. It doesn't matter if it has my implementation code or if it's just blank. I did some googling and found an error that looks similar to this involving polymorphic objects that implement IXmlSerializable. However, my class does not inherit from any others (besides Object). I suspected this may be an issue because I never reference XmlNode any other time in my code. Microsoft describes a solution to the polymorphism error: https://connect.microsoft.com/VisualStudio/feedback/details/422577/incorrect-deserialization-of-polymorphic-type-that-implements-ixmlserializable?wa=wsignin1.0#details The code the error occurs at is as follows. The object to be read back in is an ArrayList of "MyObjects" IO::FileStream ^fs = gcnew IO::FileStream(filename, IO::FileMode::Open); array<System::Type^>^ extraTypes = gcnew array<System::Type^>(1); extraTypes[0] = MyObject::typeid; XmlSerializer ^xmlser = gcnew XmlSerializer(ArrayList::typeid, extraTypes); System::Object ^obj; obj = xmlser->Deserialize(fs); fs->Close(); ArrayList ^al = safe_cast<ArrayList^>(obj); MyObject ^objs; for each(objs in al) //Error occurs here { //do some processing } Thanks for reading and for any help.

    Read the article

  • Dynamic ExpandableListView

    - by JLB
    Can anyone tell me how I can Dynamically add groups & children to an ExpandableListView. The purpose is to create a type of task list that I can add new items/groups to. I can populate the view with pre-filled arrays but of course can't add to them to populate the list further. The other method i tried was using the SimpleExpandableListAdapter. Using this i am able to add groups from a List but when it comes to adding children i can only add 1 item per group. public List<Map<String, String>> groupData = new ArrayList<Map<String, String>>(); public List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>(); public void addGroup(String group) { Map curGroupMap = new HashMap(); groupData.add(curGroupMap); curGroupMap.put(NAME, group); //Add an empty child or else the app will crash when group is expanded. List<Map<String, String>> children = new ArrayList<Map<String, String>>(); Map<String, String> curChildMap = new HashMap<String, String>(); children.add(curChildMap); curChildMap.put(NAME, "EMPTY"); childData.add(children); updateAdapter(); } public void addChild(String child) { List children = new ArrayList(); Map curChildMap = new HashMap(); children.add(curChildMap); curChildMap.put(NAME, child); curChildMap.put(IS_EVEN, "This child is even"); childData.add(activeGroup, children); updateAdapter(); }

    Read the article

  • Collections of generics

    - by Luis Sep
    According to what I've read, I think this can't be done, but I'd like to be sure. I have a class OpDTO and several other *DTO extends OpDTO. Then, I want to have a method to extract just certain elements from lists of these child DTOs, and return the extracted elements in another list: public List<? extends OpDTO> getLastOp (List<? extends OpDTO> listDTOs) { List<? extends OpDTO> last = new ArrayList<? extends OpDTO>(); //compile error: Cannot instantiate the type ArrayList<? extends OpDTO> //processing return last; } I want ult to be a list of elements of the same kind as elements in listDTOs, and use only OpDTO's methods, but it produces a compile error: Cannot instantiate the type ArrayList<? extends OpDTO> I also tried doing something like: public <T> List<T> getLastOp (List<T> listDTOs) { List<T> last = new ArrayList<T>(); //processing return last; } But then I can't enforce elements in listDTOs to be a subclass of OpDTO, and can't instantiate T. Any idea?

    Read the article

  • How do I remove implementing types from GWT’s Serialization Policy?

    - by Bluu
    The opposite of this question: http://stackoverflow.com/questions/138099/how-do-i-add-a-type-to-gwts-serialization-policy-whitelist GWT is adding undesired types to the serialization policy and bloating my JS. How do I trim my GWT whitelist by hand? Or should I at all? For example, if I put the interface List on a GWT RPC service class, GWT has to generate Javascript that handles ArrayList, LinkedList, Stack, Vector, ... even though my team knows we're only ever going to return an ArrayList. I could just make the method's return type ArrayList, but I like relying on an interface rather than a specific implementation. After all, maybe one day we will switch it up and return e.g. a LinkedList. In that case, I'd like to force the GWT serialization policy to compile for only ArrayList and LinkedList. No Stacks or Vectors. These implicit restrictions have one huge downside I can think of: a new member of the team starts returning Vectors, which will be a runtime error. So besides the question in the title, what is your experience designing around this?

    Read the article

  • How to detect column conflicts with Hibernate?

    - by Slim
    So let's say I have an ArrayList full of Products that need to be committed to the database via Hibernate. There are already a large number of Products in the database. Each product has an ID. Note this is NOT the PK that is autogenerated by Hibernate. My questions is: what is the best way to detect conflicts with this ID? I am looking for a relatively efficient method of obtaining, from the the database, a List of Products that share an ID with any of the Products in my ArrayList. This is all in a single table called Products and the ID attribute is in column ProductID. The way I've done it is grabbing a list of all Products in the database, and compared each one with each entry in my ArrayList - but that is seriously inefficient and I don't think it would work well with a larger database. How should it be done? Thanks. I say "relatively" efficient because efficiency is not the primary concern, but it shouldn't take noticeably long to test against a table of ~1000-5000 rows. Help? EDIT* I'm very new to hibernate and below is the best I've come up with. How does this look? for(long id : idList){ //idList just holds the IDs of each Product in my ArrayList Query query = session.createQuery("select product from Product product where product.id = :id"); query.setLong("id", id); for(int i = 0; i < query.list().size(); i++){ listOfConflictingProducts.add((Product) query.list().get(i)); } }

    Read the article

  • Problems breaking out of nested loops

    - by user1040281
    I have problems breaking out off these nested loops correctly. What the code is trying to do is to indicate that a customer has rented a certain movie. Both the movie and customer are compared to properties of arraylist objects and then if all checks out the name property and ID property of a movie object are added as a string to another arraylist. All this works correctly as long as I use the first movie (from movies) and the first customer (from customers) but if I try renting other movies further down my arraylist with other customers then it adds the rented movie to the customerRentedMovies arraylist but prints out the "else message". I figure I need to break out of the foreach(blabla) loops aswell? or could goto be used? Comments was removed (looked kinda messy, can explain further if needed) public void RentMovie(string titel, int movieID, string name, int customerID) { foreach (Customer customer in customers) { if (name == customer.Name && customerID == customer.CustomerID) { foreach (MovieInfo movie in movies) { if (titel == movie.Titel && movieID == movie.MovieID) { movie.rented = true; string rentedMovie = string.Format("{0} ID: {1}", movie.Titel, movie.MovieID); customer.customerRentedMovies.Add(rentedMovie); break; } else { Console.WriteLine("No movie with that titel and ID!"); } } break; } else { Console.WriteLine("No customer with that ID and name"); } } }

    Read the article

  • hibernate executeUpdate IndexOutOfBounds

    - by luke
    I am trying to use an HQL to perform a simple update in hibernate, but i can't seem to get it to work. i have a query template defined as: private static final String CHANGE_DEVICE_STATUS = "UPDATE THING" +"SET ACTIVE = ? " +"WHERE ID = ?"; and then i try to execute it like this: Session s = HibernateSessionFactory.getSession(); Query query = s.createQuery(CHANGE_DEVICE_STATUS); query.setBoolean(0, is_active); query.setLong(1, id); query.executeUpdate(); But now i get this error: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.RangeCheck(ArrayList.java:547) at java.util.ArrayList.get(ArrayList.java:322) at org.hibernate.hql.ast.HqlSqlWalker.postProcessUpdate(HqlSqlWalker.java:390) at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:164) at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:189) at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:130) at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:83) at org.hibernate.impl.SessionFactoryImpl.getQuery(SessionFactoryImpl.java:427) at org.hibernate.impl.SessionImpl.getQueries(SessionImpl.java:884) at org.hibernate.impl.SessionImpl.executeUpdate(SessionImpl.java:865) at org.hibernate.impl.QueryImpl.executeUpdate(QueryImpl.java:89) .... what am i doing wrong here? I am using hibernate 3.0 UPDATE i changed it to Query query = s.createQuery(CHANGE_DEVICE_STATUS); query.setBoolean(1, is_active); query.setLong(2, id);//<---throws here query.executeUpdate(); without changing anything else but the parameter indexes and i got this: java.lang.IllegalArgumentException: Positional parameter does not exist: 2 in query: UPDATE DEVICE_INSTANCES SET ACTIVE = ? WHERE DEVICE_INSTANCE_ID = ? at org.hibernate.impl.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:194) at org.hibernate.impl.AbstractQueryImpl.setLong(AbstractQueryImpl.java:244) ...

    Read the article

  • correct way of initializing variables

    - by OVERTONE
    ok this is just a shot in the dark but it may be the cause of most of the errors ive gotten. when your initializing something. lets say a smal swing program. would it go liek this variables here { private Jlist contactList; String [] contactArray; ArrayList <String> contactArrayList; ResultSet namesList constructor here public whatever() { GridLayout aGrid = new GridLayout(2,2,10,10); contact1 = new String(); contact2 = new String(); contact3 = new String(); contactArrayList = new ArrayList<String>(); // is something supposed too go in the () of this JList? contactList = new JList(); contactArray = new String[5]; from1 =new JLabel ("From: " + contactArray[1]); gridlayout.add(components)// theres too many components to write onto SO. } // methods here public void fillContactsGui() { createConnection(); ArrayList<String> contactsArrayList = new ArrayList<String>(); while (namesList.next()) { contactArrayList.add(namesList.getString(1)); ContactArray[1] = namesList[1]; } } i know this is probably a huge beginner question but this is the code ive gotten used too. im initializing thigns three and fours times without meaning too because im not sure where they gp. can anyone shed some light on this? p.s. sorry for the messy sample code. i done my best.

    Read the article

  • Need help with a custom Spinner/ArrayAdapter setup

    - by MisterSquonk
    I have a WeatherSpinner class which extends Spinner. The class shows region names which I originally did using an ArrayAdapter<String> but I now want to use ArrayAdapter<Locale>(Locale is an abstract 'empty' class of my own). I'm getting a ClassCastException when trying to populate my ArrayAdapter with the following... protected ArrayList<?> theList; protected ArrayAdapter<Locale> aa = null; ... protected void updateContents(ArrayList<?> list, int selectedItem) { theList = list; // Exception thrown on next line aa = new ArrayAdapter<Locale>(theContext, android.R.layout.simple_spinner_item, (Locale[]) theList.toArray()); ... } I'm passing a RegionList object into updateContents() as the 'list' parameter and RegionList extends ArrayList<Region>, and Region extends Locale. I've also overriden Region's toString() method to return a valid String. What am I not seeing here? Am I wrong about the way ArrayList<?>.toArray() works?

    Read the article

  • Java convert time format to integer or long

    - by behrk2
    Hello, I'm wondering what the best method is to convert a time string in the format of 00:00:00 to an integer or a long? My ultimate goal is to be able to convert a bunch of string times to integers/longs, add them to an array, and find the most recent time in the array... I'd appreciate any help, thanks! Ok, based on the answers, I have decided to go ahead and compare the strings directly. However, I am having some trouble. It is possible to have more than one "most recent" time, that is, if two times are equal. If that is the case, I want to add the index of both of those times to an ArrayList. Here is my current code: days[0] = "15:00:00"; days[1] = "17:00:00"; days[2] = "18:00:00"; days[3] = "19:00:00"; days[4] = "19:00:00"; days[5] = "15:00:00"; days[6] = "13:00:00"; ArrayList<Integer> indexes = new ArrayList<Integer>(); String curMax = days[0]; for (int x = 1; x < days.length1; x++) { if (days[x].compareTo(curMax) > 0) { curMax = days[x]; indexes.add(x); System.out.println("INDEX OF THE LARGEST VALUE: " + x); } } However, this is adding index 1, 2, and 3 to the ArrayList... Can anyone help me?

    Read the article

  • Set the amount of rows JList show (Java)

    - by Alex Cheng
    Hi all. Problem: I have a method that creates a list from the parsed ArrayList. I manage to show the list in the GUI, without scrollbar. However, I am having problem setting it to show only the size of ArrayList. Meaning, say if the size is 6, there should only be 6 rows in the shown List. Below is the code that I am using. I tried setting the visibleRowCount as below but it does not work. I tried printing out the result and it shows that the change is made. private void createSuggestionList(ArrayList<String> str) { int visibleRowCount = str.size(); System.out.println("visibleRowCount " + visibleRowCount); listForSuggestion = new JList(str.toArray()); listForSuggestion.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); listForSuggestion.setSelectedIndex(0); listForSuggestion.setVisibleRowCount(visibleRowCount); System.out.println(listForSuggestion.getVisibleRowCount()); listScrollPane = new JScrollPane(listForSuggestion); MouseListener mouseListener = new MouseAdapter() { @Override public void mouseClicked(MouseEvent mouseEvent) { JList theList = (JList) mouseEvent.getSource(); if (mouseEvent.getClickCount() == 2) { int index = theList.locationToIndex(mouseEvent.getPoint()); if (index >= 0) { Object o = theList.getModel().getElementAt(index); System.out.println("Double-clicked on: " + o.toString()); } } } }; listForSuggestion.addMouseListener(mouseListener); textPane.add(listScrollPane); repaint(); } To summarize: I want the JList to show as many rows as the size of the parsed ArrayList, without a scrollbar. Any ideas? Please help. Thanks. Please let me know if a picture of the problem is needed in case I did not phrase my question correctly.

    Read the article

  • Which design pattern fits - strategy makes sense ?

    - by user554833
    --Bump *One desperate try to get someone's attention I have a simple database table that stores list of users who have subscribed to folders either by email OR to show up on the site (only on the web UI). In the storage table this is controlled by a number(1 - show on site 2- by email). When I am showing in UI I need to show a checkbox next to each of folders for which the user has subscribed (both email & on site). There is a separate table which stores a set of default subscriptions which would apply to each user if user has not expressed his subscription. This is basically a folder ID and a virtual group name. But, Email subscriptions do not count for applying these default groups. So if no "on site" subscription apply default group. Thats the rule. How about a strategy pattern here (Pseudo code) Interface ISubscription public ArrayList GetSubscriptionData(Pass query object) Public class SubscriptionWithDefaultGroup Implement ArrayList GetSubscriptionData(Pass query object) Public class SubscriptionWithoutDefaultGroup Implement ArrayList GetSubscriptionData(Pass query object) Public class SubscriptionOnlyDefaultGroup Implement ArrayList GetSubscriptionData(Pass query object) does this even make sense? I would be more than glad for receive any criticism / help / notes. I am learning. Cheers

    Read the article

  • implementing interface

    - by 1ace1
    hello guys so i have this assignment that i need to implement interface to go over an ArrayList and sort it (ascending or descnding).I dont want "the" answer i just need some suggestions on my approach and why i get this error Exception in thread "main" java.lang.ClassCastException: Week7.Check cannot be cast to java.lang.Comparable at java.util.Arrays.mergeSort(Unknown Source) at java.util.Arrays.sort(Unknown Source) at java.util.Collections.sort(Unknown Source) at Week7.TestCheck.main(TestCheck.java:18) This is how i did it: comparable had one method called public int compairTo(Object o) public class Check implements comparable { private Integer checkNumber; public Check(Integer newCheckNumber) { setCheckNumber(newCheckNumber); } public String toString() { return getCheckNumber().toString(); } public void setCheckNumber(Integer checkNumber) { this.checkNumber = checkNumber; } public Integer getCheckNumber() { return checkNumber; } @Override public int compairTo(Object o) { Check compair = (Check)o; int result = 0; if (this.getCheckNumber() > compair.getCheckNumber()) result = 1; else if(this.getCheckNumber() < compair.getCheckNumber()) result = -1; return result; } } in my main i had this import java.util.ArrayList; import java.util.Collections; public class TestCheck { public static void main(String[] args) { ArrayList checkList = new ArrayList(); checkList.add(new Check(445)); checkList.add(new Check(101)); checkList.add(new Check(110)); checkList.add(new Check(553)); checkList.add(new Check(123)); Collections.sort(checkList); for (int i =0; i < checkList.size(); i++){ System.out.println(checkList.get(i)); } } }

    Read the article

  • I'm confused about Polymorphism

    - by Vtanathip
    I'm know polymorphism rule that we can send it via parameter like this code interface Animal { void whoAmI(); } class A implements Animal{ @Override public void whoAmI() { // TODO Auto-generated method stub System.out.println("A"); } } class B implements Animal{ @Override public void whoAmI() { // TODO Auto-generated method stub System.out.println("B"); } } class RuntimePolymorphismDemo { public void WhoRU(List t){ System.out.println(t.getClass()); } public static void main(String[] args) { A a = new A(); B b = new B(); RuntimePolymorphismDemo rp = new RuntimePolymorphismDemo(); rp.WhoRU(a); rp.WhoRU(b); } } but List<Example> examples = new ArrayList<Example>(); This code,I'm don't understand why we must use List. why we can't use like this? ArrayList<Example> examples = new ArrayList<Example>(); Because when we use List we can't use method that only have in ArrayList class like trimToSize() and How I know when to use or not use?

    Read the article

  • JAVA - How to code Node neighbours in a Grid ?

    - by ke3pup
    Hi guys I'm new to programming and as a School task i need to implement BFS,DFS and A* search algorithms in java to search for a given Goal from a given start position in a Grid of given size, 4x4,8x8..etc to begin with i don't know how to code the neighbors of all the nodes. For example tile 1 in grid as 2 and 9 as neighbors and Tile 12 has ,141,13,20 as its neighbours but i'm struggling to code that. I need the neighbours part so that i can move from start position to other parts of gird legally by moving horizontally or vertically through the neighbours. my node class is: class node { int value; LinkedList neighbors; bool expanded; } let's say i'm given a 8x8 grid right, So if i start the program with a grid of size 8x8 right : 1 - my main will func will create an arrayList of nodes for example node ArrayList test = new ArrayList(); and then using a for loop assign value to all the nodes in arrayList from 1 to 64 (if the grid size was 8x8). BUT somehow i need t on coding that, if anyone can give me some details i would really appreciate it.

    Read the article

  • How to save/retrieve words to/from SQlite database?

    - by user998032
    Sorry if I repeat my question but I have still had no clues of what to do and how to deal with the question. My app is a dictionary. I assume that users will need to add words that they want to memorise to a Favourite list. Thus, I created a Favorite button that works on two phases: short-click to save the currently-view word into the Favourite list; and long-click to view the Favourite list so that users can click on any words to look them up again. I go for using a SQlite database to store the favourite words but I wonder how I can do this task. Specifically, my questions are: Should I use the current dictionary SQLite database or create a new SQLite database to favorite words? In each case, what codes do I have to write to cope with the mentioned task? Could anyone there kindly help? Here is the dictionary code: package mydict.app; import java.util.ArrayList; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.util.Log; public class DictionaryEngine { static final private String SQL_TAG = "[MyAppName - DictionaryEngine]"; private SQLiteDatabase mDB = null; private String mDBName; private String mDBPath; //private String mDBExtension; public ArrayList<String> lstCurrentWord = null; public ArrayList<String> lstCurrentContent = null; //public ArrayAdapter<String> adapter = null; public DictionaryEngine() { lstCurrentContent = new ArrayList<String>(); lstCurrentWord = new ArrayList<String>(); } public DictionaryEngine(String basePath, String dbName, String dbExtension) { //mDBExtension = getResources().getString(R.string.dbExtension); //mDBExtension = dbExtension; lstCurrentContent = new ArrayList<String>(); lstCurrentWord = new ArrayList<String>(); this.setDatabaseFile(basePath, dbName, dbExtension); } public boolean setDatabaseFile(String basePath, String dbName, String dbExtension) { if (mDB != null) { if (mDB.isOpen() == true) // Database is already opened { if (basePath.equals(mDBPath) && dbName.equals(mDBName)) // the opened database has the same name and path -> do nothing { Log.i(SQL_TAG, "Database is already opened!"); return true; } else { mDB.close(); } } } String fullDbPath=""; try { fullDbPath = basePath + dbName + "/" + dbName + dbExtension; mDB = SQLiteDatabase.openDatabase(fullDbPath, null, SQLiteDatabase.OPEN_READWRITE|SQLiteDatabase.NO_LOCALIZED_COLLATORS); } catch (SQLiteException ex) { ex.printStackTrace(); Log.i(SQL_TAG, "There is no valid dictionary database " + dbName +" at path " + basePath); return false; } if (mDB == null) { return false; } this.mDBName = dbName; this.mDBPath = basePath; Log.i(SQL_TAG,"Database " + dbName + " is opened!"); return true; } public void getWordList(String word) { String query; // encode input String wordEncode = Utility.encodeContent(word); if (word.equals("") || word == null) { query = "SELECT id,word FROM " + mDBName + " LIMIT 0,15" ; } else { query = "SELECT id,word FROM " + mDBName + " WHERE word >= '"+wordEncode+"' LIMIT 0,15"; } //Log.i(SQL_TAG, "query = " + query); Cursor result = mDB.rawQuery(query,null); int indexWordColumn = result.getColumnIndex("Word"); int indexContentColumn = result.getColumnIndex("Content"); if (result != null) { int countRow=result.getCount(); Log.i(SQL_TAG, "countRow = " + countRow); lstCurrentWord.clear(); lstCurrentContent.clear(); if (countRow >= 1) { result.moveToFirst(); String strWord = Utility.decodeContent(result.getString(indexWordColumn)); String strContent = Utility.decodeContent(result.getString(indexContentColumn)); lstCurrentWord.add(0,strWord); lstCurrentContent.add(0,strContent); int i = 0; while (result.moveToNext()) { strWord = Utility.decodeContent(result.getString(indexWordColumn)); strContent = Utility.decodeContent(result.getString(indexContentColumn)); lstCurrentWord.add(i,strWord); lstCurrentContent.add(i,strContent); i++; } } result.close(); } } public Cursor getCursorWordList(String word) { String query; // encode input String wordEncode = Utility.encodeContent(word); if (word.equals("") || word == null) { query = "SELECT id,word FROM " + mDBName + " LIMIT 0,15" ; } else { query = "SELECT id,content,word FROM " + mDBName + " WHERE word >= '"+wordEncode+"' LIMIT 0,15"; } //Log.i(SQL_TAG, "query = " + query); Cursor result = mDB.rawQuery(query,null); return result; } public Cursor getCursorContentFromId(int wordId) { String query; // encode input if (wordId <= 0) { return null; } else { query = "SELECT id,content,word FROM " + mDBName + " WHERE Id = " + wordId ; } //Log.i(SQL_TAG, "query = " + query); Cursor result = mDB.rawQuery(query,null); return result; } public Cursor getCursorContentFromWord(String word) { String query; // encode input if (word == null || word.equals("")) { return null; } else { query = "SELECT id,content,word FROM " + mDBName + " WHERE word = '" + word + "' LIMIT 0,1"; } //Log.i(SQL_TAG, "query = " + query); Cursor result = mDB.rawQuery(query,null); return result; } public void closeDatabase() { mDB.close(); } public boolean isOpen() { return mDB.isOpen(); } public boolean isReadOnly() { return mDB.isReadOnly(); } } And here is the code below the Favourite button to save to and load the Favourite list: btnAddFavourite = (ImageButton) findViewById(R.id.btnAddFavourite); btnAddFavourite.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Add code here to save the favourite, e.g. in the db. Toast toast = Toast.makeText(ContentView.this, R.string.messageWordAddedToFarvourite, Toast.LENGTH_SHORT); toast.show(); } }); btnAddFavourite.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { // Open the favourite Activity, which in turn will fetch the saved favourites, to show them. Intent intent = new Intent(getApplicationContext(), FavViewFavourite.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getApplicationContext().startActivity(intent); return false; } }); }

    Read the article

  • VS2008 C# error ".ctor' not supported by language

    - by Jim Jones
    C# code: class Program { static void Main(string[] args) { TFWrapper tf; String lexDir = "......."; String lic = "........"; String key = "........."; ArrayList cats = new ArrayList(); Boolean useConj = false; String lang = "english"; String encoding = "auto"; tf = new TFWrapper(lexDir, lic, key, useConj, lang, encoding); } } Managed C++ method being called: TFWrapper::TFWrapper(String^ mlexDir, String^ mlic, String^ mkey, ArrayList catList, Boolean^ m_useConj, String^ m_lang, String^ m_encoding); Getting '.ctor' is not supported by the language error on the last line of C#

    Read the article

  • populate jsp drop down with database info

    - by Cano63
    Hello, people, i,m looking for the way to populate a jsp dropdown. I want that when the jsp load it fill the dropdown with the info that i have in a database table. Down I,m icluding the code of my class that will create the array and fill it with the database info. Whant i don,t know is how to call that class from my jsp and fill the dropdown. '// this will create my array public static ArrayList getBrandsMakes() { ArrayList arrayBrandsMake = new ArrayList(); while(rs.next()) { arrayBrandsMake.add(loadOB(rs)); // CARGO MI ARREGLO CON UN OBJETO } return arrayBrandsMake; } } //this will load my array object private static DropDownBrands loadOB(ResultSet rs)throws SQLException { DropDownBrands OB = new DropDownBrands (); OB.setBrands("BRAN"); return OB; } '

    Read the article

  • Java :Interface for this code

    - by ibrahim
    Please i neeed help to make interface for this code: package com.ejada.alinma.edh.xsdtransform; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Properties; import java.util.StringTokenizer; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; /*import org.apache.log4j.Logger;*/ import org.apache.log4j.PropertyConfigurator; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.sun.org.apache.xml.internal.serialize.OutputFormat; import com.sun.org.apache.xml.internal.serialize.XMLSerializer; /** * An XSD Transformer that replaces the "name" attribute's value in T24 XSDs * with the "shortname" attribute's value * * @author ahusseiny * */ public class XSDTransformer { /** * constants representing the XSD tags and attributes' names used in the parse process */ public static final String TAG_SCHEMA = "xsd:schema"; public static final String TAG_TEXT = "#text"; public static final String TAG_COMPLEX_TYPE = "xsd:complexType"; public static final String TAG_SIMPLE_TYPE = "xsd:simpleType"; public static final String TAG_SEQUENCE = "xsd:sequence"; public static final String TAG_ATTRIBUTE = "xsd:attribute"; public static final String TAG_ELEMENT = "xsd:element"; public static final String TAG_ANNOTATION = "xsd:annotation"; public static final String TAG_APP_INFO = "xsd:appinfo"; public static final String TAG_HAS_PROPERTY = "xsd:hasProperty"; public static final String TAG_RESTRICTION = "xsd:restriction"; public static final String TAG_MAX_LENGTH = "xsd:maxLength"; public static final String ATTR_NAME = "name"; public static final String ATTR_VALUE = "value"; public static final String ATTR_TYPE = "type"; public static final String ATTR_MIXED = "mixed"; public static final String ATTR_USE = "use"; public static final String ATTR_REF = "ref"; public static final String ATTR_MAX_OCCURS = "maxOccurs"; /** * constants representing specific XSD attributes' values used in the parse process */ public static final String FIELD_TAG = "fieldtag"; public static final String FIELD_NUMBER = "fieldnumber"; public static final String FIELD_DATA_TYPE = "fielddatatype"; public static final String FIELD_FMT = "fieldfmt"; public static final String FIELD_LEN = "fieldlen"; public static final String FIELD_INPUT_LEN = "fieldinputlen"; public static final String FIELD_GROUP_NUMBER = "fieldgroupnumber"; public static final String FIELD_MV_GROUP_NUMBER = "fieldmvgroupnumber"; public static final String FIELD_SHORT_NAME = "fieldshortname"; public static final String FIELD_NAME = "fieldname"; public static final String FIELD_COLUMN_NAME = "fieldcolumnname"; public static final String FIELD_GROUP_NAME = "fieldgroupname"; public static final String FIELD_MV_GROUP_NAME = "fieldmvgroupname"; public static final String FIELD_JUSTIFICATION = "fieldjustification"; public static final String FIELD_TYPE = "fieldtype"; public static final String FIELD_SINGLE_OR_MULTI = "singleormulti"; public static final String DELIMITER_COLUMN_TYPE = "#"; public static final String COLUMN_FK_ROW = "FK_ROW"; public static final String COLUMN_XPK_ROW = "XPK_ROW"; public static final int SQL_VIEW_MULTI = 1; public static final int SQL_VIEW_SINGLE = 2; public static final String DATA_TYPE_XSD_NUMERIC = "numeric"; public static final String DATA_TYPE_XSD_DECIMAL = "decimal"; public static final String DATA_TYPE_XSD_STRING = "string"; public static final String DATA_TYPE_XSD_DATE = "date"; /** * application configuration properties */ public static final String PROP_LOG4J_CONFIG_FILE = "log4j_config"; public static final String PROP_MAIN_VIEW_NAME_SINGLE = "view_name_single"; public static final String PROP_MAIN_VIEW_NAME_MULTI = "view_name_multi"; public static final String PROP_MAIN_TABLE_NAME = "main_edh_table_name"; public static final String PROP_SUB_TABLE_PREFIX = "sub_table_prefix"; public static final String PROP_SOURCE_XSD_FULLNAME = "source_xsd_fullname"; public static final String PROP_RESULTS_PATH = "results_path"; public static final String PROP_NEW_XSD_FILENAME = "new_xsd_filename"; public static final String PROP_CSV_FILENAME = "csv_filename"; /** * static holders for application-level utilities */ private static Properties appProps; private static Logger appLogger; /** * */ private StringBuffer sqlViewColumnsSingle = null; private StringBuffer sqlViewSelectSingle = null; private StringBuffer columnsCSV = null; private ArrayList<String> singleValueTableColumns = null; private HashMap<String, String> multiValueTablesSQL = null; private HashMap<Object, HashMap<String, Object>> groupAttrs = null; public XSDTransformer(String appConfigPropsPath) { if (appProps == null) { appProps = new Properties(); } try { init(appConfigPropsPath); } catch (Exception e) { appLogger.error(e.getMessage()); } } /** * initialization */ private void init(String appConfigPropsPath) throws Exception { // init the properties object FileReader in = new FileReader(appConfigPropsPath); appProps.load(in); // init the logger if ((appProps.getProperty(XSDTransformer.PROP_LOG4J_CONFIG_FILE) != null) && (!appProps.getProperty(XSDTransformer.PROP_LOG4J_CONFIG_FILE).equals(""))) { PropertyConfigurator.configure(appProps.getProperty(XSDTransformer.PROP_LOG4J_CONFIG_FILE)); if (appLogger == null) { appLogger = Logger.getLogger(XSDTransformer.class.getName()); } appLogger.info("Application initialization successful."); } sqlViewColumnsSingle = new StringBuffer(); sqlViewSelectSingle = new StringBuffer(); columnsCSV = new StringBuffer(XSDTransformer.FIELD_TAG + "," + XSDTransformer.FIELD_NUMBER + "," + XSDTransformer.FIELD_DATA_TYPE + "," + XSDTransformer.FIELD_FMT + "," + XSDTransformer.FIELD_LEN + "," + XSDTransformer.FIELD_INPUT_LEN + "," + XSDTransformer.FIELD_GROUP_NUMBER + "," + XSDTransformer.FIELD_MV_GROUP_NUMBER + "," + XSDTransformer.FIELD_SHORT_NAME + "," + XSDTransformer.FIELD_NAME + "," + XSDTransformer.FIELD_COLUMN_NAME + "," + XSDTransformer.FIELD_GROUP_NAME + "," + XSDTransformer.FIELD_MV_GROUP_NAME + "," + XSDTransformer.FIELD_JUSTIFICATION + "," + XSDTransformer.FIELD_TYPE + "," + XSDTransformer.FIELD_SINGLE_OR_MULTI + System.getProperty("line.separator")); singleValueTableColumns = new ArrayList<String>(); singleValueTableColumns.add(XSDTransformer.COLUMN_XPK_ROW + XSDTransformer.DELIMITER_COLUMN_TYPE + XSDTransformer.DATA_TYPE_XSD_NUMERIC); multiValueTablesSQL = new HashMap<String, String>(); groupAttrs = new HashMap<Object, HashMap<String, Object>>(); } /** * initialize the <code>DocumentBuilder</code> and read the XSD file * * @param docPath * @return the <code>Document</code> object representing the read XSD file */ private Document retrieveDoc(String docPath) { Document xsdDoc = null; File file = new File(docPath); try { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); xsdDoc = builder.parse(file); } catch (Exception e) { appLogger.error(e.getMessage()); } return xsdDoc; } /** * perform the iteration/modification on the document * iterate to the level which contains all the elements (Single-Value, and Groups) and start processing each * * @param xsdDoc * @return */ private Document transformDoc(Document xsdDoc) { ArrayList<Object> newElementsList = new ArrayList<Object>(); HashMap<String, Object> docAttrMap = new HashMap<String, Object>(); Element sequenceElement = null; Element schemaElement = null; // get document's root element NodeList nodes = xsdDoc.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { if (XSDTransformer.TAG_SCHEMA.equals(nodes.item(i).getNodeName())) { schemaElement = (Element) nodes.item(i); break; } } // process the document (change single-value elements, collect list of new elements to be added) for (int i1 = 0; i1 < schemaElement.getChildNodes().getLength(); i1++) { Node childLevel1 = (Node) schemaElement.getChildNodes().item(i1); // <ComplexType> element if (childLevel1.getNodeName().equals(XSDTransformer.TAG_COMPLEX_TYPE)) { // first, get the main attributes and put it in the csv file for (int i6 = 0; i6 < childLevel1.getChildNodes().getLength(); i6++) { Node child6 = childLevel1.getChildNodes().item(i6); if (XSDTransformer.TAG_ATTRIBUTE.equals(child6.getNodeName())) { if (child6.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME) != null) { String attrName = child6.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME).getNodeValue(); if (((Element) child6).getElementsByTagName(XSDTransformer.TAG_SIMPLE_TYPE).getLength() != 0) { Node simpleTypeElement = ((Element) child6).getElementsByTagName(XSDTransformer.TAG_SIMPLE_TYPE) .item(0); if (((Element) simpleTypeElement).getElementsByTagName(XSDTransformer.TAG_RESTRICTION).getLength() != 0) { Node restrictionElement = ((Element) simpleTypeElement).getElementsByTagName( XSDTransformer.TAG_RESTRICTION).item(0); if (((Element) restrictionElement).getElementsByTagName(XSDTransformer.TAG_MAX_LENGTH).getLength() != 0) { Node maxLengthElement = ((Element) restrictionElement).getElementsByTagName( XSDTransformer.TAG_MAX_LENGTH).item(0); HashMap<String, String> elementProperties = new HashMap<String, String>(); elementProperties.put(XSDTransformer.FIELD_TAG, attrName); elementProperties.put(XSDTransformer.FIELD_NUMBER, "0"); elementProperties.put(XSDTransformer.FIELD_DATA_TYPE, XSDTransformer.DATA_TYPE_XSD_STRING); elementProperties.put(XSDTransformer.FIELD_FMT, ""); elementProperties.put(XSDTransformer.FIELD_NAME, attrName); elementProperties.put(XSDTransformer.FIELD_SHORT_NAME, attrName); elementProperties.put(XSDTransformer.FIELD_COLUMN_NAME, attrName); elementProperties.put(XSDTransformer.FIELD_SINGLE_OR_MULTI, "S"); elementProperties.put(XSDTransformer.FIELD_LEN, maxLengthElement.getAttributes().getNamedItem( XSDTransformer.ATTR_VALUE).getNodeValue()); elementProperties.put(XSDTransformer.FIELD_INPUT_LEN, maxLengthElement.getAttributes() .getNamedItem(XSDTransformer.ATTR_VALUE).getNodeValue()); constructElementRow(elementProperties); // add the attribute as a column in the single-value table singleValueTableColumns.add(attrName + XSDTransformer.DELIMITER_COLUMN_TYPE + XSDTransformer.DATA_TYPE_XSD_STRING + XSDTransformer.DELIMITER_COLUMN_TYPE + maxLengthElement.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE).getNodeValue()); // add the attribute as a column in the single-values view sqlViewColumnsSingle.append(System.getProperty("line.separator") + attrName + ", "); sqlViewSelectSingle.append(System.getProperty("line.separator") + attrName + ", "); appLogger.debug("added attribute: " + attrName); } } } } } } // now, loop on the elements and process them for (int i2 = 0; i2 < childLevel1.getChildNodes().getLength(); i2++) { Node childLevel2 = (Node) childLevel1.getChildNodes().item(i2); // <Sequence> element if (childLevel2.getNodeName().equals(XSDTransformer.TAG_SEQUENCE)) { sequenceElement = (Element) childLevel2; for (int i3 = 0; i3 < childLevel2.getChildNodes().getLength(); i3++) { Node childLevel3 = (Node) childLevel2.getChildNodes().item(i3); // <Element> element if (childLevel3.getNodeName().equals(XSDTransformer.TAG_ELEMENT)) { // check if single element or group if (isGroup(childLevel3)) { processGroup(childLevel3, true, null, docAttrMap, xsdDoc, newElementsList); // insert a new comment node with the contents of the group tag sequenceElement.insertBefore(xsdDoc.createComment(serialize(childLevel3)), childLevel3); // remove the group tag sequenceElement.removeChild(childLevel3); } else { processElement(childLevel3); } } } } } } } // add new elements // this step should be after finishing processing the whole document. when you add new elements to the document // while you are working on it, those new elements will be included in the processing. We don't need that! for (int i = 0; i < newElementsList.size(); i++) { sequenceElement.appendChild((Element) newElementsList.get(i)); } // write the new required attributes to the schema element Iterator<String> attrIter = docAttrMap.keySet().iterator(); while(attrIter.hasNext()) { Element attr = (Element) docAttrMap.get(attrIter.next()); Element newAttrElement = xsdDoc.createElement(XSDTransformer.TAG_ATTRIBUTE); appLogger.debug("appending attr. [" + attr.getAttribute(XSDTransformer.ATTR_NAME) + "]..."); newAttrElement.setAttribute(XSDTransformer.ATTR_NAME, attr.getAttribute(XSDTransformer.ATTR_NAME)); newAttrElement.setAttribute(XSDTransformer.ATTR_TYPE, attr.getAttribute(XSDTransformer.ATTR_TYPE)); schemaElement.appendChild(newAttrElement); } return xsdDoc; } /** * check if the <code>element</code> sent is single-value element or group * element. the comparison depends on the children of the element. if found one of type * <code>ComplexType</code> then it's a group element, and if of type * <code>SimpleType</code> then it's a single-value element * * @param element * @return <code>true</code> if the element is a group element, * <code>false</code> otherwise */ private boolean isGroup(Node element) { for (int i = 0; i < element.getChildNodes().getLength(); i++) { Node child = (Node) element.getChildNodes().item(i); if (child.getNodeName().equals(XSDTransformer.TAG_COMPLEX_TYPE)) { // found a ComplexType child (Group element) return true; } else if (child.getNodeName().equals(XSDTransformer.TAG_SIMPLE_TYPE)) { // found a SimpleType child (Single-Value element) return false; } } return false; /* String attrName = null; if (element.getAttributes() != null) { Node attribute = element.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME); if (attribute != null) { attrName = attribute.getNodeValue(); } } if (attrName.startsWith("g")) { // group element return true; } else { // single element return false; } */ } /** * process a group element. recursively, process groups till no more group elements are found * * @param element * @param isFirstLevelGroup * @param attrMap * @param docAttrMap * @param xsdDoc * @param newElementsList */ private void processGroup(Node element, boolean isFirstLevelGroup, Node parentGroup, HashMap<String, Object> docAttrMap, Document xsdDoc, ArrayList<Object> newElementsList) { String elementName = null; HashMap<String, Object> groupAttrMap = new HashMap<String, Object>(); HashMap<String, Object> parentGroupAttrMap = new HashMap<String, Object>(); if (element.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME) != null) { elementName = element.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME).getNodeValue(); } appLogger.debug("processing group [" + elementName + "]..."); // get the attributes if a non-first-level-group // attributes are: groups's own attributes + parent group's attributes if (!isFirstLevelGroup) { // get the current element (group) attributes for (int i1 = 0; i1 < element.getChildNodes().getLength(); i1++) { if (XSDTransformer.TAG_COMPLEX_TYPE.equals(element.getChildNodes().item(i1).getNodeName())) { Node complexTypeNode = element.getChildNodes().item(i1); for (int i2 = 0; i2 < complexTypeNode.getChildNodes().getLength(); i2++) { if (XSDTransformer.TAG_ATTRIBUTE.equals(complexTypeNode.getChildNodes().item(i2).getNodeName())) { appLogger.debug("add group attr: " + ((Element) complexTypeNode.getChildNodes().item(i2)).getAttribute(XSDTransformer.ATTR_NAME)); groupAttrMap.put(((Element) complexTypeNode.getChildNodes().item(i2)).getAttribute(XSDTransformer.ATTR_NAME), complexTypeNode.getChildNodes().item(i2)); docAttrMap.put(((Element) complexTypeNode.getChildNodes().item(i2)).getAttribute(XSDTransformer.ATTR_NAME), complexTypeNode.getChildNodes().item(i2)); } } } } // now, get the parent's attributes parentGroupAttrMap = groupAttrs.get(parentGroup); if (parentGroupAttrMap != null) { Iterator<String> iter = parentGroupAttrMap.keySet().iterator(); while (iter.hasNext()) { String attrName = iter.next(); groupAttrMap.put(attrName, parentGroupAttrMap.get(attrName)); } } // put the attributes in the attributes map groupAttrs.put(element, groupAttrMap); } for (int i = 0; i < element.getChildNodes().getLength(); i++) { Node childLevel1 = (Node) element.getChildNodes().item(i); if (childLevel1.getNodeName().equals(XSDTransformer.TAG_COMPLEX_TYPE)) { for (int j = 0; j < childLevel1.getChildNodes().getLength(); j++) { Node childLevel2 = (Node) childLevel1.getChildNodes().item(j); if (childLevel2.getNodeName().equals(XSDTransformer.TAG_SEQUENCE)) { for (int k = 0; k < childLevel2.getChildNodes().getLength(); k++) { Node childLevel3 = (Node) childLevel2.getChildNodes().item(k); if (childLevel3.getNodeName().equals(XSDTransformer.TAG_ELEMENT)) { // check if single element or group if (isGroup(childLevel3)) { // another group element.. // unfortunately, a recursion is // needed here!!! :-( processGroup(childLevel3, false, element, docAttrMap, xsdDoc, newElementsList); } else { // reached a single-value element.. copy it under the // main sequence and apply the name-shorname // replacement processGroupElement(childLevel3, element, isFirstLevelGroup, xsdDoc, newElementsList); } } } } } } } appLogger.debug("finished processing group [" + elementName + "]."); } /** * process the sent <code>element</code> to extract/modify required * information: * 1. replace the <code>name</code> attribute with the <code>shortname</code>. * * @param element */ private void processElement(Node element) { String fieldShortName = null; String fieldColumnName = null; String fieldDataType = null; String fieldFormat = null; String fieldInputLength = null; String elementName = null; HashMap<String, String> elementProperties = new HashMap<String, String>(); if (element.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME) != null) { elementName = element.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME).getNodeValue(); } appLogger.debug("processing element [" + elementName + "]..."); for (int i = 0; i < element.getChildNodes().getLength(); i++) { Node childLevel1 = (Node) element.getChildNodes().item(i); if (childLevel1.getNodeName().equals(XSDTransformer.TAG_ANNOTATION)) { for (int j = 0; j < childLevel1.getChildNodes().getLength(); j++) { Node childLevel2 = (Node) childLevel1.getChildNodes().item(j); if (childLevel2.getNodeName().equals(XSDTransformer.TAG_APP_INFO)) { for (int k = 0; k < childLevel2.getChildNodes().getLength(); k++) { Node childLevel3 = (Node) childLevel2.getChildNodes().item(k); if (childLevel3.getNodeName().equals(XSDTransformer.TAG_HAS_PROPERTY)) { if (childLevel3.getAttributes() != null) { String attrName = null; Node attribute = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME); if (attribute != null) { attrName = attribute.getNodeValue(); elementProperties.put(attrName, childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue()); if (attrName.equals(XSDTransformer.FIELD_SHORT_NAME)) { fieldShortName = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue(); } else if (attrName.equals(XSDTransformer.FIELD_COLUMN_NAME)) { fieldColumnName = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue(); } else if (attrName.equals(XSDTransformer.FIELD_DATA_TYPE)) { fieldDataType = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue(); } else if (attrName.equals(XSDTransformer.FIELD_FMT)) { fieldFormat = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue(); } else if (attrName.equals(XSDTransformer.FIELD_INPUT_LEN)) { fieldInputLength = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue(); } } } } } } } } } if (element.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME) != null) { element.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME).setNodeValue(fieldShortName); } sqlViewColumnsSingle.append(System.getProperty("line.separator") + fieldColumnName + ", "); sqlViewSelectSingle.append(System.getProperty("line.separator") + fieldShortName + ", "); elementProperties.put(XSDTransformer.FIELD_SINGLE_OR_MULTI, "S"); constructElementRow(elementProperties); singleValueTableColumns.add(fieldShortName + XSDTransformer.DELIMITER_COLUMN_TYPE + fieldDataType + fieldFormat + XSDTransformer.DELIMITER_COLUMN_TYPE + fieldInputLength); appLogger.debug("finished processing element [" + elementName + "]."); } /** * process the sent <code>element</code> to extract/modify required * information: * 1. copy the element under the main sequence * 2. replace the <code>name</code> attribute with the <code>shortname</code>. * 3. add the attributes of the parent groups (if non-first-level-group) * * @param element */ private void processGroupElement(Node element, Node parentGroup, boolean isFirstLevelGroup, Document xsdDoc, ArrayList<Object> newElementsList) { String fieldShortName = null; String fieldColumnName = null; String fieldDataType = null; String fieldFormat = null; String fieldInputLength = null; String elementName = null; Element newElement = null; HashMap<String, String> elementProperties = new HashMap<String, String>(); ArrayList<String> tableColumns = new ArrayList<String>(); HashMap<String, Object> groupAttrMap = null; if (element.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME) != null) { elementName = element.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME).getNodeValue(); } appLogger.debug("processing element [" + elementName + "]..."); // 1. copy the element newElement = (Element) element.cloneNode(true); newElement.setAttribute(XSDTransformer.ATTR_MAX_OCCURS, "unbounded"); // 2. if non-first-level-group, replace the element's SimpleType tag with a ComplexType tag if (!isFirstLevelGroup) { if (((Element) newElement).getElementsByTagName(XSDTransformer.TAG_SIMPLE_TYPE).getLength() != 0) { // there should be only one tag of SimpleType Node simpleTypeNode = ((Element) newElement).getElementsByTagName(XSDTransformer.TAG_SIMPLE_TYPE).item(0); // create the new ComplexType element Element complexTypeNode = xsdDoc.createElement(XSDTransformer.TAG_COMPLEX_TYPE); complexTypeNode.setAttribute(XSDTransformer.ATTR_MIXED, "true"); // get the list of attributes for the parent group groupAttrMap = groupAttrs.get(parentGroup); Iterator<String> attrIter = groupAttrMap.keySet().iterator(); while(attrIter.hasNext()) { Element attr = (Element) groupAttrMap.get(attrIter.next()); Element newAttrElement = xsdDoc.createElement(XSDTransformer.TAG_ATTRIBUTE); appLogger.debug("adding attr. [" + attr.getAttribute(XSDTransformer.ATTR_NAME) + "]..."); newAttrElement.setAttribute(XSDTransformer.ATTR_REF, attr.getAttribute(XSDTransformer.ATTR_NAME)); newAttrElement.setAttribute(XSDTransformer.ATTR_USE, "optional"); complexTypeNode.appendChild(newAttrElement); } // replace the old SimpleType node with the new ComplexType node newElement.replaceChild(complexTypeNode, simpleTypeNode); } } // 3. replace the name with the shortname in the new element for (int i = 0; i < newElement.getChildNodes().getLength(); i++) { Node childLevel1 = (Node) newElement.getChildNodes().item(i); if (childLevel1.getNodeName().equals(XSDTransformer.TAG_ANNOTATION)) { for (int j = 0; j < childLevel1.getChildNodes().getLength(); j++) { Node childLevel2 = (Node) childLevel1.getChildNodes().item(j); if (childLevel2.getNodeName().equals(XSDTransformer.TAG_APP_INFO)) { for (int k = 0; k < childLevel2.getChildNodes().getLength(); k++) { Node childLevel3 = (Node) childLevel2.getChildNodes().item(k); if (childLevel3.getNodeName().equals(XSDTransformer.TAG_HAS_PROPERTY)) { if (childLevel3.getAttributes() != null) { String attrName = null; Node attribute = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME); if (attribute != null) { attrName = attribute.getNodeValue(); elementProperties.put(attrName, childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue()); if (attrName.equals(XSDTransformer.FIELD_SHORT_NAME)) { fieldShortName = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue(); } else if (attrName.equals(XSDTransformer.FIELD_COLUMN_NAME)) { fieldColumnName = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue(); } else if (attrName.equals(XSDTransformer.FIELD_DATA_TYPE)) { fieldDataType = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue(); } else if (attrName.equals(XSDTransformer.FIELD_FMT)) { fieldFormat = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE)

    Read the article

  • Java getMethod with superclass parameters in method

    - by Jonathon
    Given: class A { public void m(List l) { ... } } Let's say I want to invoke method m with reflection, passing an ArrayList as the parameter to m: List myList = new ArrayList(); A a = new A(); Method method = A.class.getMethod("m", new Class[] { myList.getClass() }); method.invoke(a, Object[] { myList }); The getMethod on line 3 will throw NoSuchMethodException because the runtime type of myList is ArrayList, not List. Is there a good generic way around this that doesn't require knowledge of class A's parameter types?

    Read the article

  • How do I store an array of a particular type into my settings file?

    - by joebeazelman
    For some reason, I can't seem to store an array of my class into the settings. Here's the code: var newLink = new Link(); Properties.Settings.Default.Links = new ArrayList(); Properties.Settings.Default.Links.Add(newLink); Properties.Settings.Default.Save(); In my Settings.Designer.cs I specified the field to be an array list: [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public global::System.Collections.ArrayList Links { get { return ((global::System.Collections.ArrayList)(this["Links"])); } set { this["Links"] = value; } } For some reason, it won't save any of the data even though the Link class is serializable and I've tested it.

    Read the article

  • Populate JSP dropdown with database info

    - by Cano63
    I'm looking for the way to populate a JSP dropdown. I want that when the JSP loads it fills the dropdown with the info that I have in a database table. I'm including the code of my class that will create the array and fill it with the database info. What I don't know is how to call that class from my JSP and fill the dropdown. // this will create my array public static ArrayList<DropDownBrands> getBrandsMakes() { ArrayList<DropDownBrands> arrayBrandsMake = new ArrayList<DropDownBrands>(); while (rs.next()) { arrayBrandsMake.add(loadOB(rs)); // CARGO MI ARREGLO CON UN OBJETO } return arrayBrandsMake; } // this will load my array object private static DropDownBrands loadOB(ResultSet rs) throws SQLException { DropDownBrands OB = new DropDownBrands(); OB.setBrands("BRAN"); return OB; }

    Read the article

  • stringtoList issue

    - by alpdog14
    I have a stringtoList ArrayList that needs to return tokens from a StreamTokenizer but the s.sval is not compiling at run-time, can anyone help me with this problem: private List<Token> stringToList(final String string) { // TODO your job // follow Main.main but put the tokens into a suitable list ArrayList<Token> al = new ArrayList<Token>(); String word = ""; String in = string; StreamTokenizer s = new StreamTokenizer(new StringReader(in)); int token; while ((token = s.nextToken()) != StreamTokenizer.TT_EOF) { if (token == StreamTokenizer.TT_WORD) { DefaultToken t = (s.sval, s.lineno()); //problem here, not reading the sval from the StreamTokenizer!!! al.add(t); } return al; } } Any help would be most appreciated

    Read the article

  • concurrency in Java

    - by p1
    1]What is Non-blocking Concurrency and how is it different. 2] I have heard that this is available in Java. Are there any particular scenarios we should use this feature 3] Is there a difference/advantage of using one of these methods for a collection. What are the trade offs class List { private final ArrayList<String> list = new ArrayList<String>(); void add(String newValue) { synchronized (list) { list.add(newValue); } } } OR private final ArrayList<String> list = Collections.synchronizedMap(); The questions are more from a learning/understanding point of view. Thanks for attention.

    Read the article

  • ListView adapter data change without ListView being notified

    - by brockoli
    I've written a ListActivity that has a custom list adapter. The list is being updated from a ContentProvider when onCreate is run. I also have a service that gets started when I run the app and it first updates the ContentProvider, then sends a Broadcast that the content has been updated. My ListActivity recieves the broadcast and tries to update my ListView. My problem is, I'm getting intermittent errors about the ListView adapter data changing without the ListView being notified. I call the notifyDataSetChanged() method on my list adapter right after I update it. What it seems like is happening is the list is still in the process of being updated after first call in onCreate when it recieves the broadcast from the service to update, so it tries to update my ListView before it's finished updating from it's first run. Does this make sense? Here is some of my code. NOTE: The service is working properly, it gets new data and updates my ContentProvider, and I do get the broadcast in my activity when it is updated. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ctx = this; getPrefs(); setContentView(R.layout.main); // Setup preference listener preferences = PreferenceManager.getDefaultSharedPreferences(this); preferences.registerOnSharedPreferenceChangeListener(listener); // Setup report list adapter ListView nzbLv = (ListView) findViewById(R.id.report_list); nzbla = new NZBReportListAdaptor(ctx); getReports(); nzbla.setListItems(report_list); nzbLv.setAdapter(nzbla); // Broadcast receiver to get notification from NZBService to update ReportList registerReceiver(receiver, new IntentFilter(NZBService.BROADCAST_ACTION)); startService(new Intent(ctx, NZBService.class)); } @Override public void onResume() { super.onResume(); timerHandler.resume(); new updateSabQueue().execute(); //updateList(); } @Override public void onPause() { super.onPause(); timerHandler.pause(); unregisterReceiver(receiver); } private BroadcastReceiver receiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { Toast.makeText(ctx, "NZBService broadcast recieved", Toast.LENGTH_SHORT).show(); updateReportList(); } }; private void updateReportList() { new updateReportList().execute(); } private class updateReportList extends AsyncTask<Void, Void, Boolean> { /* (non-Javadoc) * @see android.os.AsyncTask#onPreExecute() * Show progress dialog */ protected void onPreExecute() { } /* (non-Javadoc) * @see android.os.AsyncTask#doInBackground(Params[]) * Get new articles from the internet */ protected Boolean doInBackground(Void...unused) { getReports(); return true; } /** * On post execute. * Close the progress dialog */ @Override protected void onPostExecute(Boolean updated) { if (updated) { Log.d(TAG, "NZB report list adapter updated"); synchronized(this) { nzbla.setListItems(report_list); } Log.d(TAG, "NZB report list notified of change"); nzbla.notifyDataSetChanged(); } } } Now that this question is answered, I will post my updated code in an effort to help others who might come across it. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ctx = this; getPrefs(); setContentView(R.layout.main); // Setup preference listener preferences = PreferenceManager.getDefaultSharedPreferences(this); preferences.registerOnSharedPreferenceChangeListener(listener); // Setup report list adapter ListView nzbLv = (ListView) findViewById(R.id.report_list); nzbla = new NZBReportListAdaptor(ctx); report_list.addAll(getReports()); nzbla.setListItems(report_list); nzbLv.setAdapter(nzbla); // Broadcast receiver to get notification from NZBService to update ReportList registerReceiver(receiver, new IntentFilter(NZBService.BROADCAST_ACTION)); startService(new Intent(ctx, NZBService.class)); } private class updateReportList extends AsyncTask<Void, Void, ArrayList<Report>> { /* (non-Javadoc) * @see android.os.AsyncTask#onPreExecute() * Show progress dialog */ protected void onPreExecute() { } /* (non-Javadoc) * @see android.os.AsyncTask#doInBackground(Params[]) * Get new articles from the internet */ protected ArrayList<Report> doInBackground(Void...unused) { return getReports(); } /** * On post execute. * Close the progress dialog */ @Override protected void onPostExecute(ArrayList<Report> updated) { nzbla.setListItems(updated); nzbla.notifyDataSetChanged(); } } private ArrayList<Report> getReports() { ArrayList<Report> reports = new ArrayList<Report>(); ContentResolver r = getContentResolver(); Cursor c = r.query(NZBReportProvider.CONTENT_URI, null, null, null, NZBReportProvider.ARTICLE_KEY_ROWID + " DESC"); startManagingCursor(c); Log.d(TAG, "NZBReport cursor.getCount=" + c.getCount()); int title = c.getColumnIndex(NZBReportProvider.ARTICLE_KEY_TITLE); int desc = c.getColumnIndex(NZBReportProvider.ARTICLE_KEY_DESCRIPTION); int cat = c.getColumnIndex(NZBReportProvider.ARTICLE_KEY_CAT); int size = c.getColumnIndex(NZBReportProvider.ARTICLE_KEY_SIZE); int link = c.getColumnIndex(NZBReportProvider.ARTICLE_KEY_LINK); int catid = c.getColumnIndex(NZBReportProvider.ARTICLE_KEY_CATID); int date = c.getColumnIndex(NZBReportProvider.ARTICLE_KEY_DATE_ADDED); int group = c.getColumnIndex(NZBReportProvider.ARTICLE_KEY_GROUP); if (c.getCount() > 0) { c.moveToFirst(); do { URL url = null; try { url = new URL(c.getString(link)); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } reports.add(new Report(c.getString(title), url, c.getString(desc), c.getString(cat), c.getString(date), c.getString(size), c.getInt(catid), c.getString(group))); } while (c.moveToNext()); } return reports; }

    Read the article

< Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >