Search Results

Search found 547 results on 22 pages for 'hashmap'.

Page 7/22 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Can I pass data into a HashMap<String,Object> from JSP to a JavaBean?

    - by Parris
    Hi Everyone, I am just starting out with JSP, Java, etc web development... I would love to use some sort of framework, but for this project I can't do that. In any case I want to potentially pass essentially limitless data (for flexibility) to my javabeans. My idea was if I can have key value pairs that would really easy. The values will always be strings or integers. HashMap seems ideal in this case. Is this possible? Any ideas? Can I do this with JSP Bean tags or should I write scriptlets? Thanks!!!

    Read the article

  • How do I create an instance of this class in Android?

    - by Lloyd Banks
    I was wondering if it is possible to create an instance of this class (from the link, which creates a listview) from another class so that I can call on either lazyadapter.java or customizedlistview.java (not sure which one) to inflate that same listview. Is this possible? This is what I tried (obviously incorrect): CustomizedListView clv = new CustomizedListView(); clv.onCreate(...); source: http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/ LazyAdapter.java import java.util.ArrayList; import java.util.HashMap; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class LazyAdapter extends BaseAdapter { private Activity activity; private ArrayList&lt;HashMap&lt;String, String&gt;&gt; data; private static LayoutInflater inflater=null; public ImageLoader imageLoader; public LazyAdapter(Activity a, ArrayList&lt;HashMap&lt;String, String&gt;&gt; d) { activity = a; data=d; inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); imageLoader=new ImageLoader(activity.getApplicationContext()); } public int getCount() { return data.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { View vi=convertView; if(convertView==null) vi = inflater.inflate(R.layout.list_row, null); TextView title = (TextView)vi.findViewById(R.id.title); // title TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name TextView duration = (TextView)vi.findViewById(R.id.duration); // duration ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image HashMap&lt;String, String&gt; song = new HashMap&lt;String, String&gt;(); song = data.get(position); // Setting all values in listview title.setText(song.get(CustomizedListView.KEY_TITLE)); artist.setText(song.get(CustomizedListView.KEY_ARTIST)); duration.setText(song.get(CustomizedListView.KEY_DURATION)); imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), thumb_image); return vi; } } CustomizedListView.java import java.util.ArrayList; import java.util.HashMap; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; public class CustomizedListView extends Activity { // All static variables static final String URL = "http://api.androidhive.info/music/music.xml"; // XML node keys static final String KEY_SONG = "song"; // parent node static final String KEY_ID = "id"; static final String KEY_TITLE = "title"; static final String KEY_ARTIST = "artist"; static final String KEY_DURATION = "duration"; static final String KEY_THUMB_URL = "thumb_url"; ListView list; LazyAdapter adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ArrayList&lt;HashMap&lt;String, String&gt;&gt; songsList = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;(); XMLParser parser = new XMLParser(); String xml = parser.getXmlFromUrl(URL); // getting XML from URL Document doc = parser.getDomElement(xml); // getting DOM element NodeList nl = doc.getElementsByTagName(KEY_SONG); // looping through all song nodes &lt;song&gt; for (int i = 0; i &lt; nl.getLength(); i++) { // creating new HashMap HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(); Element e = (Element) nl.item(i); // adding each child node to HashMap key =&gt; value map.put(KEY_ID, parser.getValue(e, KEY_ID)); map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE)); map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST)); map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION)); map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL)); // adding HashList to ArrayList songsList.add(map); } list=(ListView)findViewById(R.id.list); // Getting adapter by passing xml data ArrayList adapter=new LazyAdapter(this, songsList); list.setAdapter(adapter); // Click event for single list row list.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { } }); } }

    Read the article

  • android listview loadmore button with xml parsing

    - by user1780331
    Hi i have to developed listview with load more button using xml parsing in android application. Here i have faced some problem. my xml feed is empty means how can hide the load more button on last page. i have used below code here. public class CustomizedListView extends Activity { // All static variables private String URL = "http://dev.mmm.com/xctesting/xcart444pro/retrieve.php?page=1"; // XML node keys static final String KEY_SONG = "Order"; static final String KEY_TITLE = "orderid"; static final String KEY_DATE = "date"; static final String KEY_ARTIST = "payment_method"; int current_page = 1; ListView lv; LazyAdapter adapter; ProgressDialog pDialog; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); lv = (ListView) findViewById(R.id.list); ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>(); XMLParser parser = new XMLParser(); String xml = parser.getXmlFromUrl(URL); // getting XML from URL Document doc = parser.getDomElement(xml); // getting DOM element NodeList nl = doc.getElementsByTagName(KEY_SONG); // looping through all song nodes <song> for (int i = 0; i < nl.getLength(); i++) { // creating new HashMap HashMap<String, String> map = new HashMap<String, String>(); Element e = (Element) nl.item(i); // adding each child node to HashMap key => value map.put(KEY_ID, parser.getValue(e, KEY_ID)); map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE)); map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST)); songsList.add(map); } Button btnLoadMore = new Button(this); btnLoadMore.setText("Load More"); btnLoadMore.setBackgroundResource(R.drawable.lgnbttn); // Adding Load More button to lisview at bottom lv.addFooterView(btnLoadMore); // Getting adapter adapter = new LazyAdapter(this, songsList); lv.setAdapter(adapter); btnLoadMore.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // Starting a new async task new loadMoreListView().execute(); } }); } private class loadMoreListView extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { // Showing progress dialog before sending http request pDialog = new ProgressDialog( CustomizedListView.this); pDialog.setMessage("Please wait.."); //pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.my_progress_indeterminate)); pDialog.setIndeterminate(true); pDialog.setCancelable(false); pDialog.show(); pDialog.setContentView(R.layout.custom_dialog); } protected Void doInBackground(Void... unused) { current_page += 1; // Next page request URL = "http://dev.mmm.com/xctesting/xcart444pro/retrieve.php?page=" + current_page; ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>(); XMLParser parser = new XMLParser(); String xml = parser.getXmlFromUrl(URL); // getting XML from URL Document doc = parser.getDomElement(xml); // getting DOM element NodeList nl = doc.getElementsByTagName(KEY_SONG); NodeList nl = doc.getElementsByTagName(KEY_SONG); if (nl.getLength() == 0) { btnLoadMore.setVisibility(View.GONE); pDialog.dismiss(); } else // looping through all item nodes <item> for (int i = 0; i < nl.getLength(); i++) { // creating new HashMap HashMap<String, String> map = new HashMap<String, String>(); Element e = (Element) nl.item(i); // adding each child node to HashMap key => value map.put(KEY_ID, parser.getValue(e, KEY_ID)); map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE)); map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST)); songsList.add(map); } // get listview current position - used to maintain scroll position int currentPosition = lv.getFirstVisiblePosition(); // Appending new data to menuItems ArrayList adapter = new LazyAdapter( CustomizedListView.this, songsList); lv.setAdapter(adapter); lv.setSelectionFromTop(currentPosition + 1, 0); } }); return (null); } protected void onPostExecute(Void unused) { // closing progress dialog pDialog.dismiss(); } } } EDIT: Here i have to run the app means the listview is displayed on perpage 4 items.my last page having 1 item.please refer this screenshot:http://screencast.com/t/fTl4FETd In last page i have to click the load more button means have to go next activity and successfully hide the button on empty page..please refer this screenshot:http://screencast.com/t/wyG5zdp3r i have to check the condition for empty page: if (nl.getLength() == 0) { btnLoadMore.setVisibility(View.GONE); pDialog.dismiss(); } How can i write the conditon fot last page?????pleas ehelp me Here i wish to need the o/p is hide the button on last page. Please help me.how can i check the condition.give me some code programmatically.

    Read the article

  • Using AsyncTask to display data in ListView, but onPostExecute not being called

    - by sumisu
    I made a simple AsyncTask class to display data in ListView with the help of this stackoverflow question. But the AsyncTask onPostExecute is not being called. This is my code: public class Start extends SherlockActivity { // JSON Node names private static final String TAG_ID = "id"; private static final String TAG_NAME = "name"; // category JSONArray JSONArray category = null; private ListView lv; @Override public void onCreate(Bundle savedInstanceState) { setTheme(SampleList.THEME); //Used for theme switching in samples super.onCreate(savedInstanceState); setContentView(R.layout.test); new MyAsyncTask().execute("http://...."); // Launching new screen on Selecting Single ListItem lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // getting values from selected ListItem String name = ((TextView) view.findViewById(R.id.name)).getText().toString(); String cost = ((TextView) view.findViewById(R.id.mail)).getText().toString(); // Starting new intent Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class); in.putExtra("categoryname", name); System.out.println(cost); in.putExtra("categoryid", cost); startActivity(in); } }); } public class MyAsyncTask extends AsyncTask<String, Void, ArrayList<HashMap<String, String>> > { // Hashmap for ListView ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>(); @Override protected ArrayList<HashMap<String, String>> doInBackground(String... params) { // Creating JSON Parser instance JSONParser jParser = new JSONParser(); // getting JSON string from URL category = jParser.getJSONArrayFromUrl(params[0]); try { // looping through All Contacts for(int i = 0; i < category.length(); i++){ JSONObject c = category.getJSONObject(i); // Storing each json item in variable String id = c.getString(TAG_ID); String name = c.getString(TAG_NAME); // creating new HashMap HashMap<String, String> map = new HashMap<String, String>(); // adding each child node to HashMap key => value map.put(TAG_ID, id); map.put(TAG_NAME, name); // adding HashList to ArrayList contactList.add(map); } } catch (JSONException e) { Log.e("log_tag", "Error parsing data "+e.toString()); } return contactList; } @Override protected void onPostExecute(ArrayList<HashMap<String, String>> result) { ListAdapter adapter = new SimpleAdapter(Start.this, result , R.layout.list_item, new String[] { TAG_NAME, TAG_ID }, new int[] { R.id.name, R.id.mail }); // selecting single ListView item lv = (ListView) findViewById(R.id.ListView); lv.setAdapter(adapter); } } } Eclipse: 11-25 11:40:31.896: E/AndroidRuntime(917): java.lang.RuntimeException: Unable to start activity ComponentInfo{de.essentials/de.main.Start}: java.lang.NullPointerException

    Read the article

  • In Java, can a final field be initialized from a constructor helper?

    - by csj
    I have a final non-static member: private final HashMap<String,String> myMap; I would like to initialize it using a method called by the constructor. Since myMap is final, my "helper" method is unable to initialize it directly. Of course I have options: I could implement the myMap initialization code directly in the constructor. MyConstructor (String someThingNecessary) { myMap = new HashMap<String,String>(); myMap.put("blah","blahblah"); // etc... // other initialization stuff unrelated to myMap } I could have my helper method build the HashMap, return it to the constructor, and have the constructor then assign the object to myMap. MyConstructor (String someThingNecessary) { myMap = InitializeMyMap(someThingNecessary); // other initialization stuff unrelated to myMap } private HashMap<String,String> InitializeMyMap(String someThingNecessary) { HashMap<String,String> initializedMap = new HashMap<String,String>(); initializedMap.put("blah","blahblah"); // etc... return initializedMap; } Method #2 is fine, however, I'm wondering if there's some way I could allow the helper method to directly manipulate myMap. Perhaps a modifier that indicates it can only be called by the constructor? MyConstructor (String someThingNecessary) { InitializeMyMap(someThingNecessary); // other initialization stuff unrelated to myMap } // helper doesn't work since it can't modify a final member private void InitializeMyMap(String someThingNecessary) { myMap = new HashMap<String,String>(); myMap.put("blah","blahblah"); // etc... }

    Read the article

  • variables in jasper report

    - by ed1t
    Is there a way I could declare a variable of type HashMap which would call some java method to populate the HashMap? I want to have a hashmap in a report so depending on what the value of a certain field is, I would like to get the full description of it from an Hashmap.

    Read the article

  • Easiest way to pass a javascript array or its values to a servlet and convert to a HashMap

    - by Ankur
    I have a Javascript array. I want to pass it's data to a servlet using the ajax() method of jQuery. What is the easiest way to do this. The index values i.e. the i in array[i] are not in order, they are numbers that have meaning themselves, hence I cannot simply loop through and create a GET queryString, or so I believe. Maybe I should be converting the JavaScript array to a JSON Object and sending that to the server ?? I am stumped on this one.

    Read the article

  • How expensive is a call to java.util.HashMap.keySet()?

    - by fx42
    I implemented a sparse matrix as List<Map<Integer,Double>>. To get all entries of row i I call list.get(i).keySet(). How expensive is this call? I also used the trove library for an alternative implementation as List<TIntDoubleHashMap>. What's the cost of calling list.get(i).keys(), here? Do you have any further ideas of how to implement an efficient sparse matrix? Or can you provide a list of existing implementations in java?

    Read the article

  • What is a good java data structure for storing nested items (like cities in states)?

    - by anotherAlan
    I'm just getting started in Java and am looking for advice on a good way to store nested sets of data. For example, I'm interested in storing city population data that can be accessed by looking up the city in a given state. (Note: eventually, other data will be stored with each city as well, this is just the first attempt at getting started.) The current approach I'm using is to have a StateList Object which contains a HashMap that stores State Objects via a string key (i.e. HashMap<String, State>). Each State Object contains its own HashMap of City Objects keyed off the city name (i.e. HashMap<String, City>). A cut down version of what I've come up with looks like this: // TestPopulation.java public class TestPopulation { public static void main(String [] args) { // build the stateList Object StateList sl = new StateList(); // get a test state State stateAl = sl.getState("AL"); // make sure it's there. if(stateAl != null) { // add a city stateAl.addCity("Abbeville"); // now grab the city City cityAbbevilleAl = stateAl.getCity("Abbeville"); cityAbbevilleAl.setPopulation(2987); System.out.print("The city has a pop of: "); System.out.println(Integer.toString(cityAbbevilleAl.getPopulation())); } // otherwise, print an error else { System.out.println("That was an invalid state"); } } } // StateList.java import java.util.*; public class StateList { // define hash map to hold the states private HashMap<String, State> theStates = new HashMap<String, State>(); // setup constructor that loads the states public StateList() { String[] stateCodes = {"AL","AK","AZ","AR","CA","CO"}; // etc... for (String s : stateCodes) { State newState = new State(s); theStates.put(s, newState); } } // define method for getting a state public State getState(String stateCode) { if(theStates.containsKey(stateCode)) { return theStates.get(stateCode); } else { return null; } } } // State.java import java.util.*; public class State { // Setup the state code String stateCode; // HashMap for cities HashMap<String, City> cities = new HashMap<String, City>(); // define the constructor public State(String newStateCode) { System.out.println("Creating State: " + newStateCode); stateCode = newStateCode; } // define the method for adding a city public void addCity(String newCityName) { City newCityObj = new City(newCityName); cities.put(newCityName, newCityObj); } // define the method for getting a city public City getCity(String cityName) { if(cities.containsKey(cityName)) { return cities.get(cityName); } else { return null; } } } // City.java public class City { // Define the instance vars String cityName; int cityPop; // setup the constructor public City(String newCityName) { cityName = newCityName; System.out.println("Created City: " + newCityName); } public void setPopulation(int newPop) { cityPop = newPop; } public int getPopulation() { return cityPop; } } This is working for me, but I'm wondering if there are gotchas that I haven't run into, or if there are alternate/better ways to do the same thing. (P.S. I know that I need to add some more error checking in, but right now, I'm focused on trying to figure out a good data structure.) (NOTE: Edited to change setPop() and getPop() to setPopulation() and getPopulation() respectively to avoid confucsion)

    Read the article

  • JSP Page HttpServletRequest getAttribute Typecasting

    - by MontyBongo
    Hi There, Any ideas on the correct method of typecasting an Object out of a getAttribute request from a JSP page HttpServletRequest? I have googled but it seems that the common solution is just sticking suppresswarnings in your code... Something I would very much like to avoid. I currently have: HashMap<String, ArrayList<HashMap<String, String>>> accounts = (HashMap<String, ArrayList<HashMap<String, String>>>)request.getAttribute("accounts"); And the complier is giving me this warning: Unchecked cast from Object to HashMap Thanks in Advance!! MB.

    Read the article

  • Android: Creating custom class of resources

    - by Sebastian
    Hi, R class on android has it's limitations. You can't use the resources dynamically for loading audio, pictures or whatever. If you wan't for example, load a set of audio files for a choosen object you can't do something like: R.raw."string-upon-choosen-object" I'm new to android and at least I didn't find how you could do that, depending on what objects are choosen or something more dynamic than that. So, I thought about making it dynamic with a little of memory overhead. But, I'm in doubt if it's worth it or just working different with external resources. The idea is this: Modify the ant build xml to execute my own task. This task, is a java program that parses the R.java file building a set of HashMaps with it's pair (key, value). I have done this manually and It's working good. So I need some experts voice about it. This is how I will manage the whole thing: Generate a base Application class, e.g. MainApplicationResources that builds up all the require methods and attributes. Then, you can access those methods invoking getApplication() and then the desired method. Something like this: package [packageName] import android.app.Application; import java.util.HashMap; public class MainActivityResources extends Application { private HashMap<String,Integer> [resNameObj1]; private HashMap<String,Integer> [resNameObj2]; ... private HashMap<String,Integer> [resNameObjN]; public MainActivityResources() { super(); [resNameObj1] = new HashMap<String,Integer>(); [resNameObj1].put("[resNameObj1_Key1]", new Integer([resNameObj1_Value1])); [resNameObj1].put("[resNameObj1_Key2]", new Integer([resNameObj1_Value2])); [resNameObj2] = new HashMap<String,Integer>(); [resNameObj2].put("[resNameObj2_Key1]", new Integer([resNameObj2_Value1])); [resNameObj2].put("[resNameObj2_Key2]", new Integer([resNameObj2_Value2])); ... [resNameObjN] = new HashMap<String,Integer>(); [resNameObjN].put("[resNameObjN_Key1]", new Integer([resNameObjN_Value1])); [resNameObjN].put("[resNameObjN_Key2]", new Integer([resNameObjN_Value2])); } public int get[ResNameObj1](String resourceName) { return [resNameObj1].get(resourceName).intValue(); } public int get[ResNameObj2](String resourceName) { return [resNameObj2].get(resourceName).intValue(); } ... public int get[ResNameObjN](String resourceName) { return [resNameObjN].get(resourceName).intValue(); } } The question is: Will I add too much memory use of the device? Is it worth it? Regards,

    Read the article

  • Why is the remove function not working for hashmaps? [migrated]

    - by John Marston
    I am working on a simple project that obtains data from an input file, gets what it needs and prints it to a file. I am basically getting word frequency so each key is a string and the value is its frequency in the document. The problem however, is that I need to print out these values to a file in descending order of frequency. After making my hashmap, this is the part of my program that sorts it and writes it to a file. //Hashmap I create Map<String, Integer> map = new ConcurrentHashMap<String, Integer>(); //function to sort hashmap while (map.isEmpty() == false){ for (Entry<String, Integer> entry: map.entrySet()){ if (entry.getValue() > valueMax){ max = entry.getKey(); System.out.println("max: " + max); valueMax = entry.getValue(); System.out.println("value: " + valueMax); } } map.remove(max); out.write(max + "\t" + valueMax + "\n"); System.out.println(max + "\t" + valueMax); } When I run this i get: t 9 t 9 t 9 t 9 t 9 .... so it appears the remove function is not working as it keeps getting the same value. I'm thinking i have an issue with a scope rule or I just don't understand hashmaps very well. If anyone knows of a better way to sort a hashmap and print it, I would welcome a suggestion. thanks

    Read the article

  • Using a SimpleAdapter, how can i map images to a ListAdapter Row? using android sdk

    - by nathanjosiah
    Here is the code that i have for the adapter. ArrayList<HashMap<String, Object>> mylist = new ArrayList<HashMap<String, Object>>(); for (CustomClass imageObject : myArray) { HashMap<String, Object> map = new HashMap<String, Object>(); BmpFromURL myBmp = new BmpFromURL(image.getURL()); map.put("image", myBmp.getMyBitmap()); mylist.add(map); } SimpleAdapter adapter = new SimpleAdapter(this, mylist, R.layout.series_list_row, new String[]{"image"}, new int[]{R.id.ImageView01}); this.setListAdapter(adapter); getMyBitmap() returns a Bitmap.

    Read the article

  • Hibernate Mapping Annotation Question?

    - by paddydub
    I've just started using hibernate and I'm trying to map walking distance between two coordinates into a hashmap, There can be many connections from one "FromCoordinate" to another "ToCoordinate". I'm not sure if i've implemented this correctly, What annotations do i need to map this MashMap? Thanks @Entity @Table(name = "COORDCONNECTIONS") public class CoordinateConnection implements Serializable{ private static final long serialVersionUID = -1624745319005591573L; /** auto increasing id number */ @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID") @id private int id; @Embedded public FromCoordinate fromCoord; @Embedded public ToCoordinate toCoord; HashMap<Coordinate, ArrayList<Coordinate>> coordWalkingConnections = new HashMap<Coordinate, ArrayList<Coordinate>>(); } public class FromCoordinate implements ICoordinate { @Column(name = "FROM_LAT") private double latitude; @Column(name = "FROM_LNG") private double longitude; } public class ToCoordinate implements ICoordinate { @Column(name = "TO_LAT") private double latitude; @Column(name = "TO_LNG") private double longitude; @Column(name = "DISTANCE") private double distance; } DATABASE STRUCTURE id FROM_LAT FROM_LNG TO_LAT TO_LNG Dist 1 43.352669 -6.264341 43.350012 -6.260653 0.38 2 43.352669 -6.264341 43.352669 -6.264341 0.00 3 46.352669 -6.264341 43.353373 -6.262013 0.17 4 47.352465 -6.265865 43.351290 -6.261200 0.25 5 45.452578 -6.265768 43.352788 -6.264396 0.01 6 45.452578 -6.265768 45.782788 -6.234523 0.01 ..... ... . Example HashMap for HashMap<Coordinate, ArrayList<Coordinate>> <KEY{43.352669 -6.264341}, Arraylist VALUES{(43.350012,-6.260653,0.383657), (43.352669, -6.264341, 0.000095), (43.353373, -6.262013, 0.173201)}> <KEY{47.352465 -6.265865}, Arraylist VALUES{(43.351290,-6.261200,0.258781)}> <KEY{45.452578 -6.265768}, Arraylist VALUES{(43.352788,-6.264396,0.013726),(45.782788,-6.234523,0.017726)}>

    Read the article

  • Class Cast Exception

    - by iaagty
    why do i get this exception? Map myHash = null myHash = (HashMap)Collections.synchronizedMap(new HashMap()); If i try to use this hashmap, i get java.lang.ClassCastException

    Read the article

  • Forcing deallocation of large cache object in Java

    - by Jack
    I use a large (millions) entries hashmap to cache values needed by an algorithm, the key is a combination of two objects as a long. Since it grows continuously (because keys in the map changes, so old ones are not needed anymore) it would be nice to be able to force wiping all the data contained in it and start again during the execution, is there a way to do effectively in Java? I mean release the associated memory (about 1-1.5gb of hashmap) and restart from the empty hashmap..

    Read the article

  • click buttons error

    - by sara
    I will retrieve student information (id -number- name) from a database (MySQL) as a list view, each student have 2 buttons (delete - alert ) and radio buttons Every thing is ok, but how can I make an onClickListener, for example for the delete button because I try lots of examples, I heard that I can use (custom list or get view or direct onClickListener as in my code (but it is not working ) or Simple Cursor Adapter) I do not know what to use, I looked around for examples that can help me, but in my case but I did not find any so I hope this be reference for anyone have the same problem. this is my code which I use direct onClick with Simple Adapter public class ManageSection extends ListActivity { //ProgresogressDialog pDialog; private ProgressDialog pDialog; // Creating JSON Parser object // Creating JSON Parser object JSONParser jParser = new JSONParser(); //class boolean x =true; Button delete; ArrayList<HashMap<String, String>> studentList; //url to get all products list private static String url_all_student = "http://10.0.2.2/SmsPhp/view_student_info.php"; String cl; // JSON Node names private static final String TAG_SUCCESS = "success"; private static final String TAG_student = "student"; private static final String TAG_StudentID = "StudentID"; private static final String TAG_StudentNo = "StudentNo"; private static final String TAG_FullName = "FullName"; private static final String TAG_Avatar="Avatar"; HashMap<String, String> selected_student; // course JSONArray JSONArray student = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.manage_section); studentList = new ArrayList<HashMap<String, String>>(); ListView list1 = getListView(); list1.setAdapter(getListAdapter()); list1.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) { selected_student =(HashMap<String, String>) studentList.get(pos); //member of your activity. delete =(Button)view.findViewById(R.id.DeleteStudent); cl=selected_student.get(TAG_StudentID); Toast.makeText(getBaseContext(),cl,Toast.LENGTH_LONG).show(); delete.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Log.d("id: ",cl); Toast.makeText(getBaseContext(),cl,Toast.LENGTH_LONG).show(); } }); } }); new LoadAllstudent().execute(); } /** * Background Async Task to Load all student by making HTTP Request * */ class LoadAllstudent extends AsyncTask<String, String, String> { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(ManageSection.this); pDialog.setMessage("Loading student. Please wait..."); pDialog.setIndeterminate(false); } /** * getting All student from u r l * */ @Override protected String doInBackground(String... args) { // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); // getting JSON string from URL JSONObject json = jParser.makeHttpRequest(url_all_student, "GET", params); // Check your log cat for JSON response Log.d("All student : ", json.toString()); try { // Checking for SUCCESS TAG int success = json.getInt(TAG_SUCCESS); if (success == 1) { // student found // Getting Array of course student = json.getJSONArray(TAG_student); // looping through All courses for (int i = 0; i < student.length(); i++)//course JSONArray { JSONObject c = student.getJSONObject(i); // read first // Storing each json item in variable String StudentID = c.getString(TAG_StudentID); String StudentNo = c.getString(TAG_StudentNo); String FullName = c.getString(TAG_FullName); // String Avatar = c.getString(TAG_Avatar); // creating new HashMap HashMap<String, String> map = new HashMap<String, String>(); // adding each child node to HashMap key => value map.put(TAG_StudentID, StudentID); map.put(TAG_StudentNo, StudentNo); map.put(TAG_FullName, FullName); // adding HashList to ArrayList studentList.add(map); } } else { x=false; } } catch (JSONException e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // dismiss the dialog after getting all products pDialog.dismiss(); if (x==false) Toast.makeText(getBaseContext(),"no student" ,Toast.LENGTH_LONG).show(); ListAdapter adapter = new SimpleAdapter( ManageSection.this, studentList, R.layout.list_student, new String[] { TAG_StudentID, TAG_StudentNo,TAG_FullName}, new int[] { R.id.StudentID, R.id.StudentNo,R.id.FullName}); setListAdapter(adapter); // Updating parsed JSON data into ListView } } } So what do you think, why doesn't the delete button work? There is no error in my log cat. What is the alternative way ?.. what should I do ?

    Read the article

  • Can I have two names for the same variable?

    - by Roman
    The short version of the question: I do: x = y. Then I change x, and y is unchanged. What I want is to "bind" x and y in such a way that I change y whenever I change x. The extended version (with some details): I wrote a class ("first" class) which generates objects of another class ("second" class). In more details, every object of the second class has a name as a unique identifier. I call a static method of the first class with a name of the object from the second class. The first class checks if such an object was already generated (if it is present in the static HashMap of the first class). If it is already there, it is returned. If it is not yet there, it is created, added to the HashMap and returned. And then I have the following problem. At some stage of my program, I take an object with a specific name from the HashMap of the first class. I do something with this object (for example change values of some fields). But the object in the HashMap does not see these changes! So, in fact, I do not "take" an object from the HashMap, I "create a copy" of this object and this is what I would like to avoid.

    Read the article

  • Load/Store Objects in file in Java

    - by brain_damage
    I want to store an object from my class in file, and after that to be able to load the object from this file. But somewhere I am making a mistake(s) and cannot figure out where. May I receive some help? public class GameManagerSystem implements GameManager, Serializable { private static final long serialVersionUID = -5966618586666474164L; HashMap<Game, GameStatus> games; HashMap<Ticket, ArrayList<Object>> baggage; HashSet<Ticket> bookedTickets; Place place; public GameManagerSystem(Place place) { super(); this.games = new HashMap<Game, GameStatus>(); this.baggage = new HashMap<Ticket, ArrayList<Object>>(); this.bookedTickets = new HashSet<Ticket>(); this.place = place; } public static GameManager createManagerSystem(Game at) { return new GameManagerSystem(at); } public boolean store(File f) { try { FileOutputStream fos = new FileOutputStream(f); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(games); oos.writeObject(bookedTickets); oos.writeObject(baggage); oos.close(); fos.close(); } catch (IOException ex) { return false; } return true; } public boolean load(File f) { try { FileInputStream fis = new FileInputStream(f); ObjectInputStream ois = new ObjectInputStream(fis); this.games = (HashMap<Game,GameStatus>)ois.readObject(); this.bookedTickets = (HashSet<Ticket>)ois.readObject(); this.baggage = (HashMap<Ticket,ArrayList<Object>>)ois.readObject(); ois.close(); fis.close(); } catch (IOException e) { return false; } catch (ClassNotFoundException e) { return false; } return true; } . . . } public class JUnitDemo { GameManager manager; @Before public void setUp() { manager = GameManagerSystem.createManagerSystem(Place.ENG); } @Test public void testStore() { Game g = new Game(new Date(), Teams.LIONS, Teams.SHARKS); manager.registerGame(g); File file = new File("file.ser"); assertTrue(airport.store(file)); } }

    Read the article

  • Why does this compile?

    - by akf
    I was taken aback earlier today when debugging some code to find that something like the following does not throw a compile-time exception: public Test () { HashMap map = (HashMap) getList(); } private List getList(){ return new ArrayList(); } As you can imagine, a ClassCastException is thrown at runtime, but can someone explain why the casting of a List to a HashMap is considered legal at compile time?

    Read the article

  • OIM 11g notification framework

    - by Rajesh G Kumar
    OIM 11g has introduced an improved and template based Notifications framework. New release has removed the limitation of sending text based emails (out-of-the-box emails) and enhanced to support html features. New release provides in-built out-of-the-box templates for events like 'Reset Password', 'Create User Self Service' , ‘User Deleted' etc. Also provides new APIs to support custom templates to send notifications out of OIM. OIM notification framework supports notification mechanism based on events, notification templates and template resolver. They are defined as follows: Ø Events are defined as XML file and imported as part of MDS database in order to make notification event available for use. Ø Notification templates are created using OIM advance administration console. The template contains the text and the substitution 'variables' which will be replaced with the data provided by the template resolver. Templates support internationalization and can be defined as HTML or in form of simple text. Ø Template resolver is a Java class that is responsible to provide attributes and data to be used at runtime and design time. It must be deployed following the OIM plug-in framework. Resolver data provided at design time is to be used by end user to design notification template with available entity variables and it also provides data at runtime to replace the designed variable with value to be displayed to recipients. Steps to define custom notifications in OIM 11g are: Steps# Steps 1. Define the Notification Event 2. Create the Custom Template Resolver class 3. Create Template with notification contents to be sent to recipients 4. Create Event triggering spots in OIM 1. Notification Event metadata The Notification Event is defined as XML file which need to be imported into MDS database. An event file must be compliant with the schema defined by the notification engine, which is NotificationEvent.xsd. The event file contains basic information about the event.XSD location in MDS database: “/metadata/iam-features-notification/NotificationEvent.xsd”Schema file can be viewed by exporting file from MDS using weblogicExportMetadata.sh script.Sample Notification event metadata definition: 1: <?xml version="1.0" encoding="UTF-8"?> 2: <Events xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xsi:noNamespaceSchemaLocation="../../../metadata/NotificationEvent.xsd"> 3: <EventType name="Sample Notification"> 4: <StaticData> 5: <Attribute DataType="X2-Entity" EntityName="User" Name="Granted User"/> 6: </StaticData> 7: <Resolver class="com.iam.oim.demo.notification.DemoNotificationResolver"> 8: <Param DataType="91-Entity" EntityName="Resource" Name="ResourceInfo"/> 9: </Resolver> 10: </EventType> 11: </Events> Line# Description 1. XML file notation tag 2. Events is root tag 3. EventType tag is to declare a unique event name which will be available for template designing 4. The StaticData element lists a set of parameters which allow user to add parameters that are not data dependent. In other words, this element defines the static data to be displayed when notification is to be configured. An example of static data is the User entity, which is not dependent on any other data and has the same set of attributes for all event instances and notification templates. Available attributes are used to be defined as substitution tokens in the template. 5. Attribute tag is child tag for StaticData to declare the entity and its data type with unique reference name. User entity is most commonly used Entity as StaticData. 6. StaticData closing tag 7. Resolver tag defines the resolver class. The Resolver class must be defined for each notification. It defines what parameters are available in the notification creation screen and how those parameters are replaced when the notification is to be sent. Resolver class resolves the data dynamically at run time and displays the attributes in the UI. 8. The Param DataType element lists a set of parameters which allow user to add parameters that are data dependent. An example of the data dependent or a dynamic entity is a resource object which user can select at run time. A notification template is to be configured for the resource object. Corresponding to the resource object field, a lookup is displayed on the UI. When a user selects the event the call goes to the Resolver class provided to fetch the fields that are displayed in the Available Data list, from which user can select the attribute to be used on the template. Param tag is child tag to declare the entity and its data type with unique reference name. 9. Resolver closing tag 10 EventType closing tag 11. Events closing tag Note: - DataType needs to be declared as “X2-Entity” for User entity and “91-Entity” for Resource or Organization entities. The dynamic entities supported for lookup are user, resource, and organization. Once notification event metadata is defined, need to be imported into MDS database. Fully qualified resolver class name need to be define for XML but do not need to load the class in OIM yet (it can be loaded later). 2. Coding the notification resolver All event owners have to provide a resolver class which would resolve the data dynamically at run time. Custom resolver class must implement the interface oracle.iam.notification.impl.NotificationEventResolver and override the implemented methods with actual implementation. It has 2 methods: S# Methods Descriptions 1. public List<NotificationAttribute> getAvailableData(String eventType, Map<String, Object> params); This API will return the list of available data variables. These variables will be available on the UI while creating/modifying the Templates and would let user select the variables so that they can be embedded as a token as part of the Messages on the template. These tokens are replaced by the value passed by the resolver class at run time. Available data is displayed in a list. The parameter "eventType" specifies the event Name for which template is to be read.The parameter "params" is the map which has the entity name and the corresponding value for which available data is to be fetched. Sample code snippet: List<NotificationAttribute> list = new ArrayList<NotificationAttribute>(); long objKey = (Long) params.get("resource"); //Form Field details based on Resource object key HashMap<String, Object> formFieldDetail = getObjectFormName(objKey); for (Iterator<?> itrd = formFieldDetail.entrySet().iterator(); itrd.hasNext(); ) { NotificationAttribute availableData = new NotificationAttribute(); Map.Entry formDetailEntrySet = (Entry<?, ?>)itrd.next(); String fieldLabel = (String)formDetailEntrySet.getValue(); availableData.setName(fieldLabel); list.add(availableData); } return list; 2. Public HashMap<String, Object> getReplacedData(String eventType, Map<String, Object> params); This API would return the resolved value of the variables present on the template at the runtime when notification is being sent. The parameter "eventType" specifies the event Name for which template is to be read.The parameter "params" is the map which has the base values such as usr_key, obj_key etc required by the resolver implementation to resolve the rest of the variables in the template. Sample code snippet: HashMap<String, Object> resolvedData = new HashMap<String, Object>();String firstName = getUserFirstname(params.get("usr_key"));resolvedData.put("fname", firstName); String lastName = getUserLastName(params.get("usr_key"));resolvedData.put("lname", lastname);resolvedData.put("count", "1 million");return resolvedData; This code must be deployed as per OIM 11g plug-in framework. The XML file defining the plug-in is as below: <?xml version="1.0" encoding="UTF-8"?> <oimplugins xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <plugins pluginpoint="oracle.iam.notification.impl.NotificationEventResolver"> <plugin pluginclass= " com.iam.oim.demo.notification.DemoNotificationResolver" version="1.0" name="Sample Notification Resolver"/> </plugins> </oimplugins> 3. Defining the template To create a notification template: Log in to the Oracle Identity Administration Click the System Management tab and then click the Notification tab From the Actions list on the left pane, select Create On the Create page, enter values for the following fields under the Template Information section: Template Name: Demo template Description Text: Demo template Under the Event Details section, perform the following: From the Available Event list, select the event for which the notification template is to be created from a list of available events. Depending on your selection, other fields are displayed in the Event Details section. Note that the template Sample Notification Event created in the previous step being used as the notification event. The contents of the Available Data drop down are based on the event XML StaticData tag, the drop down basically lists all the attributes of the entities defined in that tag. Once you select an element in the drop down, it will show up in the Selected Data text field and then you can just copy it and paste it into either the message subject or the message body fields prefixing $ symbol. Example if list has attribute like First_Name then message body will contains this as $First_Name which resolver will parse and replace it with actual value at runtime. In the Resource field, select a resource from the lookup. This is the dynamic data defined by the Param DataType element in the XML definition. Based on selected resource getAvailableData method of resolver will be called to fetch the resource object attribute detail, if method is overridden with required implementation. For current scenario, Map<String, Object> params will get populated with object key as value and key as “resource” in the map. This is the only input will be provided to resolver at design time. You need to implement the further logic to fetch the object attributes detail to populate the available Data list. List string should not have space in between, if object attributes has space for attribute name then implement logic to replace the space with ‘_’ before populating the list. Example if attribute name is “First Name” then make it “First_Name” and populate the list. Space is not supported while you try to parse and replace the token at run time with real value. Make a note that the Available Data and Selected Data are used in the substitution tokens definition only, they do not define the final data that will be sent in the notification. OIM will invoke the resolver class to get the data and make the substitutions. Under the Locale Information section, enter values in the following fields: To specify a form of encoding, select either UTF-8 or ASCII. In the Message Subject field, enter a subject for the notification. From the Type options, select the data type in which you want to send the message. You can choose between HTML and Text/Plain. In the Short Message field, enter a gist of the message in very few words. In the Long Message field, enter the message that will be sent as the notification with Available data token which need to be replaced by resolver at runtime. After you have entered the required values in all the fields, click Save. A message is displayed confirming the creation of the notification template. Click OK 4. Triggering the event A notification event can be triggered from different places in OIM. The logic behind the triggering must be coded and plugged into OIM. Examples of triggering points for notifications: Event handlers: post process notifications for specific data updates in OIM users Process tasks: to notify the users that a provisioning task was executed by OIM Scheduled tasks: to notify something related to the task The scheduled job has two parameters: Template Name: defines the notification template to be sent User Login: defines the user record that will provide the data to be sent in the notification Sample Code Snippet: public void execute(String templateName , String userId) { try { NotificationService notService = Platform.getService(NotificationService.class); NotificationEvent eventToSend=this.createNotificationEvent(templateName,userId); notService.notify(eventToSend); } catch (Exception e) { e.printStackTrace(); } } private NotificationEvent createNotificationEvent(String poTemplateName, String poUserId) { NotificationEvent event = new NotificationEvent(); String[] receiverUserIds= { poUserId }; event.setUserIds(receiverUserIds); event.setTemplateName(poTemplateName); event.setSender(null); HashMap<String, Object> templateParams = new HashMap<String, Object>(); templateParams.put("USER_LOGIN",poUserId); event.setParams(templateParams); return event; } public HashMap getAttributes() { return null; } public void setAttributes() {} }

    Read the article

  • Not able to get data from Json completely

    - by Abhinav Raja
    i am getting JSON data from http://abinet.org/?json=1 and displaying the titles in a ListView. the code is working fine but the problem is, it is skipping few titles in my ListView and one title is being repeated. You can see the json data from url given above by copy paste it in JSON editor online http://www.jsoneditoronline.org/ i want titles in the "posts" array to be displayed in ListView, however it is being displayed like this: if you see the JSON data from the link above, its missing like 3 titles (they should come between the first and second title) and 5th title is being repeated. Dont know why this is happening. What minor adjustments i need to do? Please help me. this is my code : public class MainActivity extends Activity { // URL to get contacts JSON private static String url = "http://abinet.org/?json=1"; // JSON Node names private static final String TAG_POSTS = "posts"; static final String TAG_TITLE = "title"; private ProgressDialog pDialog; JSONArray contacts = null; TextView img_url; ArrayList<HashMap<String, Object>> contactList; ListView lv; LazyAdapter adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv = (ListView) findViewById(R.id.newslist); contactList = new ArrayList<HashMap<String, Object>>(); new GetContacts().execute(); } private class GetContacts extends AsyncTask<Void, Void, Void> { protected void onPreExecute() { super.onPreExecute(); // Showing progress dialog pDialog = new ProgressDialog(MainActivity.this); pDialog.setMessage("Please wait..."); pDialog.setCancelable(false); pDialog.show(); } protected Void doInBackground(Void... arg0) { // Making a request to url and getting response JSONParser jParser = new JSONParser(); // Getting JSON from URL JSONObject jsonObj = jParser.getJSONFromUrl(url); // if (jsonStr != null) { try { // Getting JSON Array node contacts = jsonObj.getJSONArray(TAG_POSTS); // looping through All Contacts for (int i = 0; i < contacts.length(); i++) { // JSONObject c = contacts.getJSONObject(i); JSONObject posts = contacts.getJSONObject(i); String title = posts.getString(TAG_TITLE).replace("&#8217;", "'"); JSONArray attachment = posts.getJSONArray("attachments"); for (int j = 0; j< attachment.length(); j++){ JSONObject obj = attachment.getJSONObject(j); JSONObject image = obj.getJSONObject("images"); JSONObject image_small = image.getJSONObject("thumbnail"); String imgurl = image_small.getString("url"); HashMap<String, Object> contact = new HashMap<String, Object>(); contact.put("image_url", imgurl); contact.put(TAG_TITLE, title); contactList.add(contact); } } } catch (JSONException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); // Dismiss the progress dialog if (pDialog.isShowing()) pDialog.dismiss(); adapter=new LazyAdapter(MainActivity.this, contactList); lv.setAdapter(adapter); } } } this is my JsonParser class (although its not required): public JSONParser() { } public JSONObject getJSONFromUrl(String url) { // Making HTTP request try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } } and this is adapter class: public class LazyAdapter extends BaseAdapter { private Activity activity; private ArrayList<HashMap<String, Object>> data; private static LayoutInflater inflater=null; public LazyAdapter(Activity a,ArrayList<HashMap<String, Object>> d) { activity = a; data=d; inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public int getCount() { return data.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { View vi=convertView; if(convertView==null) vi = inflater.inflate(R.layout.third_row, null); TextView title = (TextView)vi.findViewById(R.id.headline3); // title SmartImageView iv = (SmartImageView) vi.findViewById(R.id.imageicon); HashMap<String, Object> song = new HashMap<String, Object>(); song = data.get(position); // Setting all values in listview title.setText((CharSequence) song.get(MainActivity.TAG_TITLE)); iv.setImageUrl((String) song.get("image_url")); thumb_image); return vi; } } Please help me. I am stuck at this for more than a week now. I think there is just something to be changed in my MainActivity class.

    Read the article

  • how to display bitmaps in listview?

    - by mary
    hi i want to show images downloaded in listview.images downloaded with function DownloadImage and are as bitmap.how to show in listview . name photoes with book_id in tabel book are aqual.i want each book has its own image. i can show in listview book_name and book_price just the problem with image book please help me class: package bookstore.category; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.http.NameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Typeface; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.widget.ImageView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import bookstore.pack.JSONParser; import bookstore.pack.R; import android.app.Activity; import android.app.ProgressDialog; public class Computer extends Activity { Bitmap bm = null; // progress dialog private ProgressDialog pDialog; // Creating JSON Parser object JSONParser jParser = new JSONParser(); ArrayList<HashMap<String, String>> computerBookList; private static String url_books = "http://10.0.2.2/project/computer.php"; // JSON Node names private static final String TAG_SUCCESS = "success"; private static final String TAG_BOOK = "book"; private static final String TAG_BOOK_NAME = "book_name"; private static final String TAG_BOOK_PRICE = "book_price"; private static final String TAG_BOOK_ID = "book_id"; private static final String TAG_MESSAGE = "massage"; // category JSONArray JSONArray book = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.category); Typeface font1 = Typeface.createFromAsset(getAssets(), "font/bnazanin.TTF"); // Hashmap for ListView computerBookList = new ArrayList<HashMap<String, String>>(); new LoadBook().execute(); } class LoadBook extends AsyncTask<String, String, String> { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(Computer.this); pDialog.setMessage("Please wait..."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } protected String doInBackground(String... args) { // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); // getting JSON string from URL JSONObject json = jParser.makeHttpRequest(url_books, "GET", params); // Check your log cat for JSON reponse Log.d("book:", json.toString()); try { // Checking for SUCCESS TAG int success = json.getInt(TAG_SUCCESS); if (success == 1) { DownloadImage("10.0.2.2/project/images/100.png"); DownloadImage("10.0.2.2/project/images/101.png"); DownloadImage("10.0.2.2/project/images/102.png"); DownloadImage("10.0.2.2/project/images/103.png"); DownloadImage("10.0.2.2/project/images/104.png"); DownloadImage("10.0.2.2/project/images/105.png"); DownloadImage("10.0.2.2/project/images/106.png"); DownloadImage("10.0.2.2/project/images/107.png"); DownloadImage("10.0.2.2/project/images/108.png"); DownloadImage("10.0.2.2/project/images/109.png"); DownloadImage("10.0.2.2/project/images/110.png"); // books found book = json.getJSONArray(TAG_BOOK); for (int i = 0; i < book.length(); i++) { JSONObject c = book.getJSONObject(i); // Storing each json item in variable String book_name = c.getString(TAG_BOOK_NAME); String book_price = c.getString(TAG_BOOK_PRICE); String book_id = c.getString(TAG_BOOK_ID); // creating new HashMap HashMap<String, String> map = new HashMap<String, String>(); // adding each child node to HashMap key => value map.put(TAG_BOOK_NAME, book_name); map.put(TAG_BOOK_PRICE, book_price); // map.put(TAG_AUTHOR_NAME, author_name); // adding HashList to ArrayList computerBookList.add(map); } return json.getString(TAG_MESSAGE); } else { System.out.println("no book found"); } } catch (JSONException e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { pDialog.dismiss(); // updating UI from Background Thread runOnUiThread(new Runnable() { ListView view1 = (ListView) findViewById(R.id.list_view); public void run() { ImageView iv = (ImageView) findViewById(R.id.list_image); // bm=BitmapFactory.decodeResource(getResources(), resId); //bm=BitmapFactory.decodeResource(null,R.id.list_image); // iv.setImageBitmap(bm); /* * */ /** * Updating parsed JSON data into ListView * */ ListAdapter adapter = new SimpleAdapter(Computer.this, computerBookList, R.layout.search_item, new String[] { TAG_BOOK_NAME, TAG_BOOK_PRICE }, new int[] { R.id.book_name, R.id.book_price }); view1.setAdapter(adapter); } }); } } private Bitmap DownloadImage(String URL) { Bitmap bitmap = null; InputStream in = null; try { in = OpenHttpConnection(URL); bitmap = BitmapFactory.decodeStream(in); in.close(); } catch (IOException e1) { e1.printStackTrace(); } return bitmap; } private InputStream OpenHttpConnection(String urlString) throws IOException { InputStream in = null; int response = -1; URL url = new URL(urlString); URLConnection conn = url.openConnection(); if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection"); try { HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.connect(); response = httpConn.getResponseCode(); if (response == HttpURLConnection.HTTP_OK) { in = httpConn.getInputStream(); } } catch (Exception ex) { throw new IOException("Error connecting"); } return in; } }

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >