Search Results

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

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

  • Can't get recursive function to work in Java

    - by Ahmed Salah
    I read docs about java recorsion and I thought I have understood it, but when I try to use it in the following example, it does not work as expected. I a class account, which has amount and can have forther subAccount. I would have implemented one method getSum, which has to return the summ of the amount of the account and amount of all of its subaccount. In the following code, the call of the method getSumm() should return 550, but it behaves strange. can somebody help please? public class Balance{ ArrayList<Balance> subAccounts = new ArrayList<Balance>(); String accountID = null; Double amount = null; double result=0; public double getSum(ArrayList<Balance> subAccounts){ if(subAccounts !=null && subAccounts.size()>0){ for (int i = 0; i < subAccounts.size(); i++) { result = result + getSum(subAccounts.get(i).subAccounts); } } else { return amount; } return result; } public static void main(String[] args) { Balance bs1 = new Balance(); Balance bs2 = new Balance(); Balance bs3 = new Balance(); bs1.amount=100.0; bs2.amount=150.0; bs3.amount=300.0; ArrayList<Balance> subAccounts1 = new ArrayList<Balance>(); bs2.subAccounts=null; bs3.subAccounts=null; subAccounts1.add(bs2); subAccounts1.add(bs3); bs1.subAccounts=subAccounts1; double sum= bs1.getSum(subAccounts1); System.out.println(sum); } }

    Read the article

  • JAX-WS wsgen and collections of collections: wsgen broken?

    - by ayang
    I've been playing around with "bottom-up" JAX-WS and have come across something odd when running wsgen. If I have a service class that does something like: @WebService public class Foo { public ArrayList<Bar> getBarList(String baz) { ... } } then running wsgen gets me a FooService_schema1.xsd that has something like this: <xs:complexType name="getBarListResponse"> <xs:sequence> <xs:element name="return" type="tns:bar" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> which seems reasonable. However, if I want a collection of collections like: public BarCollection getBarCollection(String baz) { ... } // BarCollection is just a container for an ArrayList<Bar> then the generated schema ends up with stuff like: <xs:complexType name="barCollection"> <xs:sequence/> </xs:complexType> <xs:complexType name="getBookCollectionsResponse"> <xs:sequence> <xs:element name="return" type="tns:barCollection" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> An empty sequence is not what I had in mind at all. My original approach was to go with: public ArrayList<ArrayList<Bar>> getBarLists(String baz) { ... } but that ends up with a big chain of complexTypes that just wind up with an empty sequence at the end as well: <xs:complexType name="getBarListsResponse"> <xs:sequence> <xs:element name="return" type="tns:arrayList" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> <xs:complexType name="arrayList"> <xs:complexContent> <xs:extension base="tns:abstractList"> <xs:sequence/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="abstractList" abstract="true"> <xs:complexContent> <xs:extension base="tns:abstractCollection"> <xs:sequence/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="abstractCollection" abstract="true"> <xs:sequence/> </xs:complexType> Am I missing something or is this a known hole in wsgen? JAXB? Andy

    Read the article

  • "Cannot convert to IComparer"

    - by Odrade
    I have the following IComparer defined for boxed RegistryItem objects: public class BoxedRegistryItemComparer : IComparer<object> { public int Compare(object left, object right) { RegistryItem leftReg = (RegistryItem)left; RegistryItem rightReg = (RegistryItem)right; return string.Compare(leftReg.Name, rightReg.Name); } } I want to use this to sort an ArrayList of boxed RegistryItems (It really should be a List<RegistryItem, but that's out of my control). ArrayList regItems = new ArrayList(); // fill up the list ... BoxedRegistryItemComparer comparer = new BoxedRegistryItemComparer(); ArrayList.sort(comparer); However, the last line gives the compiler error: "Cannot convert from BoxedRegistryItemComparer to System.Collections.IComparer". I would appreciate it if someone could point out my mistake.

    Read the article

  • Android ExpandableListView From Database

    - by SterAllures
    I want to create a two level ExpandableListView from a local database. The group level I want to get the names from the database Category table category_id | name ------------------- 1 | NameOfCategory the children level I want to get the names from the List table list_id | name | foreign_category_id -------------------------------- 1 | Listname | 1 I've got a method in DatabaseDAO to get all the values from the table public List<Category> getAllCategories() { database = dbHelper.getReadableDatabase(); List<Category> categories = new ArrayList<Category>(); Cursor cursor = database.query(SQLiteHelper.TABLE_CATEGORY, null, null, null, null, null, null); cursor.moveToFirst(); while(!cursor.isAfterLast()) { Category category = cursorToCategory(cursor); categories.add(category); cursor.moveToNext(); } cursor.close(); return categories; } Now adding the names to the group level is easy I do it the following way: ArrayList<String> groups; for(Category c : databaseDao.getAllCategories()) { groups.add(c.getName()); } Now I want to add the children to the ExpandableListView in the following array ArrayList<ArrayList<ArrayList<String>>> children;. How do I get the children under the correct group name? I think it has to do somenthing with groups.indexOf() but in the list table I only have a foreign category_id and not the actual name.

    Read the article

  • Binding key/value pairs loaded from xml

    - by Hichem
    I want to load key/values configuration pairs stored in XML file. To bind a collection of data i know i need to use the ArrayList class, but the problem is that i want to be able to bind the loaded values using their corresponding keys and not by their indexes in the ArrayList object. For example i want to be able to do this : <mx:Text id="errorText" text="{Config.params['someKey']}" /> instead of : <mx:Text id="errorText" text="{Config.params[0]}" /> where Config.params is ArrayList (obviously i couldn't use ArrayList since it doesn't allow selecting a value by key) So the question is how to bind the key/value pairs loaded form XML. I don't want to go manually set variables, i want to bind them so when they are loaded the are set automatically. Did anyone had to do something like that ?

    Read the article

  • Lan Chatting system [closed]

    - by jay prakash singh
    Possible Duplicate: LAN chating system or LAN chat server displaying list of user to all the user window my code is i m use RMI so this is the interface declaration public void sendPublicMessage(String keyword, String username, String message) throws RemoteException; public void sendPrivateMessage(String keyword, String username, String message) throws RemoteException; public ArrayList getClientList() throws RemoteException; public void connect(String username) throws RemoteException; public void disconnect(String username) throws RemoteException; } chat Server here connectedUser is the HasMap object we use the follo0wing code for connection here ChatImpl is the stub try { InetAddress Address = InetAddress.getLocalHost(); ChatImpl csi = new ChatImpl(this); Naming.rebind("rmi://"+Address.getHostAddress()+":1099/ChatService", csi); } public ArrayList getClientList() { ArrayList myUser = new ArrayList(); Iterator i = connectedUser.keySet().iterator(); String user = null; while(i.hasNext()) { user = i.next().toString(); myUser.add(user); } return myUser; } public void addClient(Socket clientSocket) throws RemoteException { connectedUser.put(getUsername(), clientSocket); sendPublicMessage(ONLINE, getUsername(), "CLIENT"); } this is the client side code for array list public void updateClient(ArrayList allClientList) throws RemoteException { listClient.clear(); int i = 0; String username; for(i=0; i<allClientList.size(); i++) { username = allClientList.get(i).toString(); listClient.addElement(username); } }

    Read the article

  • Question about gets and sets and when to use super classes

    - by Nazgulled
    Hi, I have the following get method: public List<PersonalMessage> getMessagesList() { List<PersonalMessage> newList = new ArrayList<PersonalMessage>(); for(PersonalMessage pMessage : this.listMessages) { newList.add(pMessage.clone()); } return newList; } And you can see that if I need to change the implementation from ArrayList to something else, I can easily do it and I just have to change the initialization of newList and all other code that depends on what getMessageList() returns will still work. Then I have this set method: public void setMessagesList(ArrayList<PersonalMessage> listMessages) { this.listMessages = listMessages; } My question is, should I use List instead of `ArrayList in the method signature? I have decided to use ArrayList because this way I can force the implementation I want, otherwise there could be a mess with different types of lists here and there. But I'm not sure if this is the way to go...

    Read the article

  • NullPointerException using EndlessAdapter with SimpleAdapter

    - by android_dev
    Hello, I am using EndlessAdapter from commonsguy with a SimpleAdapter. I can load data when I make a scroll down without problems, but I have a NullPointerException when I make a scroll up. The problem is in the method @Override public View getView(int position, View convertView,ViewGroup parent) { return wrapped.getView(position, convertView, parent); } from the class AdapterWrapper. The call to wrapped.getView(position, convertView,parent) raises the exception and I don´t know why. This is my implementation of EndlessAdapter: //Inner class in SearchTextActivity class DemoAdapter extends EndlessAdapter { private RotateAnimation rotate = null; DemoAdapter(ArrayList<HashMap<String, String>> result) { super(new SimpleAdapter(SearchTracksActivity.this, result, R.layout.textlist_item, PROJECTION_COLUMNS, VIEW_MAPPINGS)); rotate = new RotateAnimation( 0f, 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); rotate.setDuration(600); rotate.setRepeatMode(Animation.RESTART); rotate.setRepeatCount(Animation.INFINITE); } @Override protected View getPendingView(ViewGroup parent) { View row=getLayoutInflater().inflate(R.layout.textlist_item, null); View child=row.findViewById(R.id.title); child.setVisibility(View.GONE); child=row.findViewById(R.id.username); child.setVisibility(View.GONE); child=row.findViewById(R.id.throbber); child.setVisibility(View.VISIBLE); child.startAnimation(rotate); return row; } @Override @SuppressWarnings("unchecked") protected void rebindPendingView(int position, View row) { HashMap<String, String> res = (HashMap<String, String>)getWrappedAdapter().getItem(position); View child=row.findViewById(R.id.title); ((TextView)child).setText(res.get("title")); child.setVisibility(View.VISIBLE); child=row.findViewById(R.id.username); ((TextView)child).setText(res.get("username")); child.setVisibility(View.VISIBLE); ImageView throbber=(ImageView)row.findViewById(R.id.throbber); throbber.setVisibility(View.GONE); throbber.clearAnimation(); } boolean mFinal = true; @Override protected boolean cacheInBackground() { EditText searchText = (EditText)findViewById(R.id.searchText); String textToSearch = searchText.getText().toString(); Util.getSc().searchText(textToSearch , offset, limit, new ResultListener<ArrayList<Text>>() { @Override public void onError(Exception e) { e.toString(); mFinal = false; } @Override public void onSuccess(ArrayList<Text> result) { if(result.size() == 0){ mFinal = false; }else{ texts.addAll(result); offset++; } } }); return mFinal; } @Override protected void appendCachedData() { for(Text text : texts){ result.add(text.getMapValues()); } texts.clear(); } } And I use it this way: public class SearchTextActivity extends AbstractListActivity { private static final String[] PROJECTION_COLUMNS = new String[] { TextStore.Text.TITLE, TextStore.Text.USER_NAME}; private static final int[] VIEW_MAPPINGS = new int[] { R.id.Text_title, R.id.Text_username}; ArrayList<HashMap<String, String>> result; static ArrayList<Text> texts; static int offset = 0; static int limit = 1; @Override void onAbstractCreate(Bundle savedInstance) { setContentView(R.layout.search_tracks); setupViews(); } private void setupViews() { ImageButton searchButton = (ImageButton)findViewById(R.id.searchButton); updateView(); } SimpleAdapter adapter; void updateView(){ if(result == null) { result = new ArrayList<HashMap<String, String>>(); } if(tracks == null) { texts = new ArrayList<Text>(); } } public void sendQuery(View v){ offset = 0; texts.clear(); result.clear(); setListAdapter(new DemoAdapter(result)); } } Does anybody knows what could be the problem? Thank you in advance

    Read the article

  • How to combine array list string in java ?

    - by tiendv
    I have some arraylist string with keyword inside like that ! A windows is arraylist string with keyword is bold Struct of window : 9 words before + keyword + 9 words after You can see some window overlaping How to i combine that arraylist to receive like that : Thanks

    Read the article

  • How to pass date parameters to Crystal Reports 2008 from an ASP.NET App?

    - by Unlimited071
    Hello all, I'm passing some parameters to a CR report programatically and it was working fine, but now that I have added a new date parameter to the report, for some reason, it is prompting me to enter that parameter on screen (the user isn't allowed to set that parameter is the system who must set it.), I haven't changed a thing other than adding the new date parameter, and all the other parameters behave normal, just the date parameter is prompted even thought I've already set a value for the parameter. This is the code I've got: private void ConfigureCrystalReports() { crystalReportViewer.ReportSource = GetReportPath(); crystalReportViewer.DataBind(); ConnectionInfo connectionInfo = GetConnectionInfo(); TableLogOnInfos tableLogOnInfos = crystalReportViewer.LogOnInfo; foreach (TableLogOnInfo tableLogOnInfo in tableLogOnInfos) { tableLogOnInfo.ConnectionInfo = connectionInfo; } ArrayList totOriValues = new ArrayList(); totOriValues.Add(date.ToString("MM/dd/yyyy HH:mm:ss")); ParameterFields parameterFields = crystalReportViewer.ParameterFieldInfo; SetCurrentValuesForParameterField(parameterFields, totOriValues, "DateParameter"); } private static void SetCurrentValuesForParameterField(ParameterFields parameterFields, ArrayList arrayList, string parameterName) { ParameterValues currentParameterValues = new ParameterValues(); foreach (object submittedValue in arrayList) { ParameterDiscreteValue parameterDiscreteValue = new ParameterDiscreteValue(); parameterDiscreteValue.Value = submittedValue.ToString(); currentParameterValues.Add(parameterDiscreteValue); } ParameterField parameterField = parameterFields[parameterName]; parameterField.CurrentValues = currentParameterValues; } Just for the sake of things: I have checked that the parameter is indeed a date and that it is well formed. CR prompts me to enter it in the format (mm/dd/yyyy hh:mm:ss) so I pass date in that exact format (In fact I've even tried hard coding a well-formed date and it still prompts me to enter the date). Am I doing something wrong?

    Read the article

  • How change Castor mapping to remove "xmlns:xsi" and "xsi:type" attributes from element in XML output

    - by Derek Mahar
    How do I change the Castor mapping <?xml version="1.0"?> <!DOCTYPE mapping PUBLIC "-//EXOLAB/Castor Mapping DTD Version 1.0//EN" "http://castor.org/mapping.dtd"> <mapping> <class name="java.util.ArrayList" auto-complete="true"> <map-to xml="ArrayList" /> </class> <class name="com.db.spgit.abstrack.ws.response.UserResponse"> <map-to xml="UserResponse" /> <field name="id" type="java.lang.String"> <bind-xml name="id" node="element" /> </field> <field name="deleted" type="boolean"> <bind-xml name="deleted" node="element" /> </field> <field name="name" type="java.lang.String"> <bind-xml name="name" node="element" /> </field> <field name="typeId" type="java.lang.Integer"> <bind-xml name="typeId" node="element" /> </field> <field name="regionId" type="java.lang.Integer"> <bind-xml name="regionId" node="element" /> </field> <field name="regionName" type="java.lang.String"> <bind-xml name="regionName" node="element" /> </field> </class> </mapping> to suppress the xmlns:xsi and xsi:type attributes in the element of the XML output? For example, instead of the output XML <?xml version="1.0" encoding="UTF-8"?> <ArrayList> <UserResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="UserResponse"> <name>Tester</name> <typeId>1</typeId> <regionId>2</regionId> <regionName>US</regionName> </UserResponse> </ArrayList> I'd prefer <?xml version="1.0" encoding="UTF-8"?> <ArrayList> <UserResponse> <name>Tester</name> <typeId>1</typeId> <regionId>2</regionId> <regionName>US</regionName> </UserResponse> </ArrayList> such that the element name implies the xsi:type.

    Read the article

  • Data Structures for Junior Java Developer

    - by user1639637
    Ok,still learning Arrays. I wrote this code which fills the array named "rand" with random numbers between 0 and 1( exclusive). I want to start learning Complexity. the For loop executes n times (100 times) ,every time it takes O(1) time,so the worse case scenario is O(n),am I right? Also,I used ArrayList to store the 100 elements and I imported "Collections" and used Collections.sort() method to sort the elements. import java.util.Arrays; public class random { public static void main(String args[]) { double[] rand=new double[10]; for(int i=0;i<rand.length;i++) { rand[i]=(double) Math.random(); System.out.println(rand[i]); } Arrays.sort(rand); System.out.println(Arrays.toString(rand)); } } ArrayList: import java.util.ArrayList; import java.util.Collections; public class random { public static void main(String args[]) { ArrayList<Double> MyArrayList=new ArrayList<Double>(); for(int i=0;i<100;i++) { MyArrayList.add(Math.random()); } Collections.sort(MyArrayList); for(int j=0;j<MyArrayList.size();j++) { System.out.println(MyArrayList.get(j)); } } }

    Read the article

  • Serialization of Mouse cursors over network

    - by Ehtsham
    hi I am working a client/server application in C#. My server Capture current Mouse Cursors and send these to client so that Cursor of the cleint also chage accordingly.I can detect windows Cursors and serialize them over binaryformatter. it works fine but but problem is there are many cursors that can not be detected like mspaint cursors so i have to take its handler and create the cursor and its x nad y hotspots and add them in an arraylist and serialize it over network but after 10 to 15 minute it thorws exception "Error HRESULT E_FAIL has been returned from a call to a COM Compeonet" and cleint throws the exception of "method of invocation" Can anybody guid me what going wrong ort some better way to do like this Some code is here IntPtr curInfo = GetCurrentCursor(); Cursor cur; Icon ic; byte cursor = 0; if (curInfo != null && curInfo.ToInt32() != 0) { cur = CheckForCusrors(curInfo); try { if (!isLinuxClient) { if (cur == null) { PlatformInvokeUSER32.GetIconInfo(curInfo, out temp); ic = Icon.FromHandle(curInfo); //bitmap = ic.ToBitmap(); ArrayList ar = new ArrayList(); ar.Add(ic); ar.Add(temp.xHotspot); ar.Add(temp.yHotspot); b.Serialize(stm, ar); } else { ArrayList ar = new ArrayList(); ar.Add(cur); b.Serialize(stm, ar); } } public Cursor CheckForCusrors(IntPtr hCur) { if (hCur == Cursors.AppStarting.Handle) return Cursors.AppStarting; else if (hCur == Cursors.Arrow.Handle) return Cursors.Arrow; . . . else if (hCur == Cursors.PanWest.Handle) return Cursors.PanWest; return null; } `

    Read the article

  • Java CRTP: Works for container but not for methods?

    - by Daniel
    I have a baseclass with a protected static ArrayList. I want to have a seperate ArrayList for each kind of subclass that extends this baseclass. This is when I applied CRTP: public class BaseExample<T> { protected static ArrayList<Integer> data = new ArrayList<Integer>(); } This works just fine. However, when I try to implement the following static method in the same base class, it doesn't adhere to CRTP: public static void clear() { data.clear(); } For example: class SubExample extends BaseExample<SubExample> { // insertion methods accessing 'data' field // these work fine :) } SubExample.clear(); // does not seem to clear data container Do I need to somehow explicitly specify T in my baseclass clear method? Note: These are all pure static classes.

    Read the article

  • C# MultiThread Safe Class Design

    - by Robert
    I'm trying to designing a class and I'm having issues with accessing some of the nested fields and I have some concerns with how multithread safe the whole design is. I would like to know if anyone has a better idea of how this should be designed or if any changes that should be made? using System; using System.Collections; namespace SystemClass { public class Program { static void Main(string[] args) { System system = new System(); //Seems like an awkward way to access all the members dynamic deviceInstance = (((DeviceType)((DeviceGroup)system.deviceGroups[0]).deviceTypes[0]).deviceInstances[0]); Boolean checkLocked = deviceInstance.locked; //Seems like this method for accessing fields might have problems with multithreading foreach (DeviceGroup dg in system.deviceGroups) { foreach (DeviceType dt in dg.deviceTypes) { foreach (dynamic di in dt.deviceInstances) { checkLocked = di.locked; } } } } } public class System { public ArrayList deviceGroups = new ArrayList(); public System() { //API called to get names of all the DeviceGroups deviceGroups.Add(new DeviceGroup("Motherboard")); } } public class DeviceGroup { public ArrayList deviceTypes = new ArrayList(); public DeviceGroup() {} public DeviceGroup(string deviceGroupName) { //API called to get names of all the Devicetypes deviceTypes.Add(new DeviceType("Keyboard")); deviceTypes.Add(new DeviceType("Mouse")); } } public class DeviceType { public ArrayList deviceInstances = new ArrayList(); public bool deviceConnected; public DeviceType() {} public DeviceType(string DeviceType) { //API called to get hardwareIDs of all the device instances deviceInstances.Add(new Mouse("0001")); deviceInstances.Add(new Keyboard("0003")); deviceInstances.Add(new Keyboard("0004")); //Start thread CheckConnection that updates deviceConnected periodically } public void CheckConnection() { //API call to check connection and returns true this.deviceConnected = true; } } public class Keyboard { public string hardwareAddress; public bool keypress; public bool deviceConnected; public Keyboard() {} public Keyboard(string hardwareAddress) { this.hardwareAddress = hardwareAddress; //Start thread to update deviceConnected periodically } public void CheckKeyPress() { //if API returns true this.keypress = true; } } public class Mouse { public string hardwareAddress; public bool click; public Mouse() {} public Mouse(string hardwareAddress) { this.hardwareAddress = hardwareAddress; } public void CheckClick() { //if API returns true this.click = true; } } }

    Read the article

  • Java consistent synchronization

    - by ring0
    We are facing the following problem in a Spring service, in a multi-threaded environment: three lists are freely and independently accessed for Read once in a while (every 5 minutes), they are all updated to new values. There are some dependencies between the lists, making that, for instance, the third one should not be read while the second one is being updated and the first one already has new values ; that would break the three lists consistency. My initial idea is to make a container object having the three lists as properties. Then the synchronization would be first on that object, then one by one on each of the three lists. Some code is worth a thousands words... so here is a draft private class Sync { final List<Something> a = Collections.synchronizedList(new ArrayList<Something>()); final List<Something> b = Collections.synchronizedList(new ArrayList<Something>()); final List<Something> c = Collections.synchronizedList(new ArrayList<Something>()); } private Sync _sync = new Sync(); ... void updateRunOnceEveryFiveMinutes() { final List<Something> newa = new ArrayList<Something>(); final List<Something> newb = new ArrayList<Something>(); final List<Something> newc = new ArrayList<Something>(); ...building newa, newb and newc... synchronized(_sync) { synchronized(_sync.a) { _synch.a.clear(); _synch.a.addAll(newa); } synchronized(_sync.b) { ...same with newb... } synchronized(_sync.c) { ...same with newc... } } // Next is accessed by clients public List<Something> getListA() { return _sync.a; } public List<Something> getListB() { ...same with b... } public List<Something> getListC() { ...same with c... } The question would be, is this draft safe (no deadlock, data consistency)? would you have a better implementation suggestion for that specific problem? update Changed the order of _sync synchronization and newa... building. Thanks

    Read the article

  • Interface name as a Type

    - by user1889148
    I am trying to understand interfaces in Java and have this task to do which I am a stack with. It must be something easy, but I don't seem to see the solution. Interface contains a few methods, one of them should return true if all elements of this set are also in the set. I.e. public interface ISet{ //some methods boolean isSubsetOf(ISet x); } Then the class: public class myClass implements ISet{ ArrayList<Integer> mySet; public myClass{ mySet = new ArrayList<Integer>(); } //some methods public boolean isSubsetOf(ISet x){ //method body } } What do I need to write in method body? How do I check that the instance of myClass is a subset of ISet collection? I was trying to cast, but it gives an error: ArrayList<Integer> param = (ArrayList<Integer>)x; return param.containsAll(mySet);

    Read the article

  • Android onClickListener options and help on creating a non-static array adapter

    - by CoderInTraining
    I am trying to make an application that gets data dynamically and displays it in a listView. Here is my code that I have with static data. There are a couple of things I want to try and do and can't figure out how. MainActivity.java package text.example.project; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import android.app.ListActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends ListActivity { //declarations private boolean isItem; private ArrayAdapter<String> item1Adapter; private ArrayAdapter<String> item2Adapter; private ArrayAdapter<String> item3Adapter; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Collections.sort(ITEM1); Collections.sort(ITEM2); Collections.sort(ITEM3); item1Adapter = new ArrayAdapter<String>(this, R.layout.list_item, ITEM1); item2Adapter = new ArrayAdapter<String>(this, R.layout.list_item, ITEM2); item3Adapter = new ArrayAdapter<String>(this, R.layout.list_item, ITEM3); setListAdapter(item1Adapter); isItem = true; ListView lv = getListView(); lv.setTextFilterEnabled(true); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // When clicked, show a toast with the TextView text if (isItem) { //ITEM1.add("another\n\t" + Calendar.getInstance().getTime()); Collections.sort(ITEM1); item2Adapter.notifyDataSetChanged(); setListAdapter(item2Adapter); isItem = false; } else { item1Adapter.notifyDataSetChanged(); setListAdapter(item1Adapter); isItem = true; } Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show(); } }); } // need to turn dynamic static ArrayList<String> ITEM1 = new ArrayList<String> (Arrays.asList( "ITEM1-1", "ITEM1-2" )); static ArrayList<String> ITEM2 = new ArrayList<String> (Arrays.asList( "ITEM2-1", "ITEM2-2" )); static ArrayList<String> ITEM3 = new ArrayList<String> (Arrays.asList("ITEM3-1", "ITEM3-2")); } list_item.xml <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" android:textSize="16sp" > </TextView> What I want to do is first pull from a dynamic source. I need to do what is almost exactly like this tutorial... http://androiddevelopement.blogspot.in/2011/06/android-xml-parsing-tutorial-using.html ... however, I can't get the tutorial to work... I also would like to know how I can make the list item clicks so that if I click on "ITEM1-1" it goes to the menu "ITEM2-1" and "ITEM2-2". and if "ITEM1-2" is clicked, then it goes to the menu with "ITEM3-1" and "ITEM3-2"... I am totally a noob at this whole android development thing. So any suggestions would be great!

    Read the article

  • Java jList add item based on combobox selection

    - by Stephan Badert
    I have a csv file that is being loaded in my programme. It contains citys and areas and some other stuff (not important here). Once the csv is selected I load the data into several comboboxes. 1 Thing is not working, I have a combobox containing all the citys and now I need to list all the areas for that country based on selection from the combobox. Here is the event: private void cboProvinciesItemStateChanged(java.awt.event.ItemEvent evt) { //System.out.println(Arrays.asList(gemeentesPerProvincie(gemeentes))); invullenListProvincie(gemeentes); } Here is the method: private void invullenListProvincie(ArrayList<Gemeentes> gemeentes) { Gemeentes gf = (Gemeentes) cboProvincies.getSelectedItem(); DefaultListModel model = new DefaultListModel(); JList list = new JList(model); for (Gemeentes gemeente : gemeentesPerProvincie(gemeentes)) { model.addElement(gemeente); } lstGemeentes.setModel(model); } and this is the method to filter all the areas that equal the selection from the combobox: private ArrayList<Gemeentes> gemeentesPerProvincie(ArrayList<Gemeentes> gemeentes) { String GemPerProv = (String) cboProvincies.getSelectedItem(); ArrayList<Gemeentes> selectie = new ArrayList<Gemeentes>(); for (Gemeentes gemeente : gemeentes) { if (gemeente.getsProvincie().equals(GemPerProv)) { selectie.add(gemeente); } } return selectie; } I am convinced the error is the way I am trying to add items to the jList gemeentesPerProvincie(), I have tried so many things already. I really hope someone can see what i am clearly missing...

    Read the article

  • "Dereference" var in C#

    - by chris12892
    I have some code in C# that uses a structure as such: ArrayList addrs = new ArrayList(); byte[] addr = new byte[8]; while (oneWire.Search_GetNextDevice(addr)) { addrs.Add(addr); } In this example, every element in the ArrayList is the same as the last device that was found because it would appear as though addr is passed out by reference and I am simply copying that reference into the ArrayList. Is there any way to "Dereference" addr to only extract it's value? It's also possible my assessment of the situation is incorrect, if that appears to be the case, please let me know Thanks!

    Read the article

  • mvc design in a card game

    - by Hong
    I'm trying to make a card game. some classes I have are: CardModel, CardView; DeckModel, DeckView. The deck model has a list of card model, According to MVC, if I want to send a card to a deck, I can add the card model to the deck model, and the card view will be added to the deck view by a event handler. So I have a addCard(CardModel m) in the DeckModel class, but if I want to send a event to add the card view of that model to the deck view, I only know let the model has a reference to view. So the question is: If the card model and deck model have to have a reference to their view classes to do it? If not, how to do it better? Update, the code: public class DeckModel { private ArrayList<CardModel> cards; private ArrayList<EventHandler> actionEventHandlerList; public void addCard(CardModel card){ cards.add(card); //processEvent(event x); //must I pass a event that contain card view here? } CardModel getCards(int index){ return cards.get(index); } public synchronized void addEventHandler(EventHandler l){ if(actionEventHandlerList == null) actionEventHandlerList = new ArrayList<EventHandler>(); if(!actionEventHandlerList.contains(l)) actionEventHandlerList.add(l); } public synchronized void removeEventHandler(EventHandler l){ if(actionEventHandlerList!= null && actionEventHandlerList.contains(l)) actionEventHandlerList.remove(l); } private void processEvent(Event e){ ArrayList list; synchronized(this){ if(actionEventHandlerList!= null) list = (ArrayList)actionEventHandlerList.clone(); else return; } for(int i=0; i<actionEventHandlerList.size(); ++i){ actionEventHandlerList.get(i).handle(e); } } }

    Read the article

  • ASP.NET Custom Control - Template Allowing Literal Content

    - by Bob Fincheimer
    I want my User Control to be able to have Literal Content inside of it. For Example: <fc:Text runat="server">Please enter your login information:</fc:Text> Currently the code for my user control is: <ParseChildren(True, "Content")> _ Partial Public Class ctrFormText Inherits FormControl Private _content As ArrayList <PersistenceMode(PersistenceMode.InnerDefaultProperty), _ DesignerSerializationVisibility(DesignerSerializationVisibility.Content), _ TemplateInstance(TemplateInstance.Single)> _ Public Property Content() As ArrayList Get If _content Is Nothing Then Return New ArrayList End If Return _content End Get Set(ByVal value As ArrayList) _content = value End Set End Property Protected Overrides Sub CreateChildControls() If _content IsNot Nothing Then ctrChildren.Controls.Clear() For Each i As Control In _content ctrChildren.Controls.Add(i) Next End If MyBase.CreateChildControls() End Sub End Class And when I put text inside this control (like above) i get this error: Parser Error Message: Literal content ('Please enter your login information to access CKMS:') is not allowed within a 'System.Collections.ArrayList'. This control could have other content than just the text, so making the Content property an attribute will not solve my problem. I found in some places that I need to implement a ControlBuilder Class, along with another class that implements IParserAccessor. Anyway I just want my default "Content" property to have all types of controls allowed in it, both literal and actual controls.

    Read the article

  • Container of Generic Types in java

    - by Cyker
    I have a generic class Foo<T> and parameterized types Foo<String> and Foo<Integer>. Now I want to put different parameterized types into a single ArrayList. What is the correct way of doing this? Candidate 1: public class MMM { public static void main(String[] args) { Foo<String> fooString = new Foo<String>(); Foo<Integer> fooInteger = new Foo<Integer>(); ArrayList<Foo<?> > list = new ArrayList<Foo<?> >(); list.add(fooString); list.add(fooInteger); for (Foo<?> foo : list) { // Do something on foo. } } } class Foo<T> {} Candidate 2: public class MMM { public static void main(String[] args) { Foo<String> fooString = new Foo<String>(); Foo<Integer> fooInteger = new Foo<Integer>(); ArrayList<Foo> list = new ArrayList<Foo>(); list.add(fooString); list.add(fooInteger); for (Foo foo : list) { // Do something on foo. } } } class Foo<T> {} In a word, it is related to the difference between Foo<?> and the raw type Foo. Update: Grep What is the difference between the unbounded wildcard parameterized type and the raw type? on this link may be helpful.

    Read the article

  • Easy way to cast an object array into another type in C#

    - by Na7coldwater
    I want to be able to be able to quickly cast an array of objects to a different type, such as String, but the following code doesn't work: String[] a = new String[2]; a[0] = "Hello"; a[1] = "World"; ArrayList b = new ArrayList(a); String[] c = (String[]) b.ToArray(); And I don't want to have to do this: String[] a = new String[2]; a[0] = "Hello"; a[1] = "World"; ArrayList b = new ArrayList(a); Object[] temp = b.ToArray(); Object[] temp = b.ToArray(); String[] c = new String[temp.Length]; for(int i=0;i<temp.Length;i++) { c[i] = (String) temp[i]; } Is there an easy way to do this without using a temporary variable?

    Read the article

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