Search Results

Search found 9 results on 1 pages for 'hashlist'.

Page 1/1 | 1 

  • Android string formatiing from xml

    - by mann
    I am parsing xml from server. One of its node contains data like <distance>16.3432434324354324km</distance> I am putting it into hashmap like for (int i = 0; i < nl.getLength(); i++) { map.put(KEY_DISTANCE, parser.getValue(e, KEY_DISTANCE)); // adding HashList to ArrayList menuItems.add(map); } Everything is nice. But i want it two decimal places for example i want its value should be 16.34km rather then 16.343234324342342km I tried with DecimalFormat twoDForm=new DecimalFormat("##.00"); try{ Double StartVTwo=Double.valueOf(KEY_DISTANCE); Double resultDouble1 = Double.valueOf(twoDForm.format(StartVTwo)); Log.e("check", String.valueOf(resultDouble1)); }catch (NumberFormatException e){ Log.e("error"," This is error "); } But it shows exception and prints this message. Any help would be appreciated!!

    Read the article

  • Progressbar blocks notiyfyDatasetChanged() method in Android

    - by pathfinder
    I'm trying to display a ProgressBar while a listview is being populated. This is my XML <FrameLayout android:layout_width="fill_parent" android:layout_height="wrap_content" > <ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" android:divider="@null" android:dividerHeight="0dp" android:fadingEdge="none" > </ListView> <ProgressBar android:id="@+id/doProgress" android:layout_width="60dp" android:layout_height="60dp" android:layout_gravity="center" /> </FrameLayout> ProgressBar's visibiliy has been changed in the onPostExecuteMethod when the whole listview is loaded. AsyncTask Code: public class WhatToDoLoader extends AsyncTask<String, String, String> { ProgressDialog progress = new ProgressDialog(WhatToDo.this); String url = "http://wearedesigners.net/clients/clients12/tourism/fetchWhatToDoList.php"; final String TAG_MAIN = "item"; final String TAG_ID = "itemId"; final String TAG_NAME = "itemName"; final String TAG_DETAIL = "itemDetailText"; final String TAG_ITEM_IMAGE = "itemImages"; final String TAG_MAP = "itemMapData"; final String TAG_MAP_IMAGE = "mapImage"; @Override protected void onProgressUpdate(String... values) { // TODO Auto-generated method stub super.onProgressUpdate(values); adapter.notifyDataSetChanged(); } @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); /* * progress.setMessage("Loading What To Do List"); progress.show(); */ } @Override protected String doInBackground(String... params) { XMLParser parser = new XMLParser(); String xml = parser.getXmlFromUrl(url); // getting XML Document doc = parser.getDomElement(xml); // getting DOM element NodeList nl = doc.getElementsByTagName(TAG_MAIN); // TODO Auto-generated method stub 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(TAG_ID, parser.getValue(e, TAG_ID)); map.put(TAG_NAME, parser.getValue(e, TAG_NAME)); map.put(TAG_DETAIL, parser.getValue(e, TAG_DETAIL)); map.put(TAG_MAP, parser.getValue(e, TAG_MAP)); map.put(TAG_MAP_IMAGE, parser.getValue(e, TAG_MAP_IMAGE)); map.put(TAG_ITEM_IMAGE, parser.getValue(e, TAG_ITEM_IMAGE)); System.out.println("Test : " + parser.getValue(e, TAG_ID)); // adding HashList to ArrayList whatToDoInfo.add(map); publishProgress(""); } return null; } @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); ProgressBar pb = (ProgressBar) findViewById(R.id.doProgress); pb.setVisibility(pb.INVISIBLE); } } When i run the code it throws the following exception. *java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread.* But the same code works fine when the progressbar feature is omitted. I can't find where i'm going wrong. can someone please help me ? Thank you in advance.

    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

  • 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

  • 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

  • how can i update view when fragment change?

    - by user1524393
    i have a activity that have 2 sherlockfragment in this The first two pages display fragments with custom list views which are built from xml from server using AsyncTask. However, when the app runs, only one list view is displayed, the other page is just blank public class VpiAbsTestActivity extends SherlockFragmentActivity { private static final String[] CONTENT = new String[] { "1","2"}; TestFragmentAdapter mAdapter; ViewPager mPager; PageIndicator mIndicator; protected void onCreate(Bundle savedInstanceState) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); super.onCreate(savedInstanceState); setContentView(R.layout.simple_tabs); mAdapter = new TestFragmentAdapter(getSupportFragmentManager()); mPager = (ViewPager)findViewById(R.id.pager); mPager.setAdapter(mAdapter); mIndicator = (TabPageIndicator)findViewById(R.id.indicator); mIndicator.setViewPager(mPager); mIndicator.notifyDataSetChanged(); } class TestFragmentAdapter extends FragmentPagerAdapter { private int mCount = CONTENT.length; public TestFragmentAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { switch(position) { case 0: return new customlist(); case 1: return new customlistnotuser(); default: return null; } } @Override public int getCount() { return mCount; } public CharSequence getPageTitle(int position) { return VpiAbsTestActivity.CONTENT[position % VpiAbsTestActivity.CONTENT.length].toUpperCase(); } @Override public void destroyItem(View collection, int position, Object view) { ((ViewPager) collection).removeView((View) view); } } } what can i update viewpager when change pages ? the customlistnotuser page likes customlist page but not show public class customlistnotuser extends SherlockFragment { // All static variables static final String URL = "url"; // XML node keys static final String KEY_TEST = "test"; // parent node static final String KEY_ID = "id"; static final String KEY_TITLE = "title"; static final String KEY_Description = "description"; static final String KEY_DURATION = "duration"; static final String KEY_THUMB_URL = "thumb_url"; static final String KEY_PRICE = "price"; static final String KEY_URL = "url"; private ProgressDialog pDialog; ListView list; LazyAdapterbeth adapter; XMLParser parser = new XMLParser(); public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); new getFeed().execute(); } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View thisfragment = inflater.inflate(R.layout.dovomi, container, false); return thisfragment; } private class getFeed extends AsyncTask<Void, Void, Document> { } protected Document doInBackground(Void... params) { XMLParser parser = new XMLParser(); String xml = parser.getXmlFromUrl(URL); // getting XML from URL Document doc = parser.getDomElement(xml); // getting DOM element return doc; } protected void onPostExecute(Document doc) { ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>(); NodeList nl = doc.getElementsByTagName(KEY_TEST); // 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_Description, parser.getValue(e, KEY_Description)); map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION)); map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL)); map.put(KEY_PRICE, parser.getValue(e, KEY_PRICE)); map.put(KEY_URL, parser.getValue(e, KEY_URL)); // adding HashList to ArrayList songsList.add(map); pDialog.dismiss(); } list=(ListView)getActivity().findViewById(R.id.list); // Getting adapter by passing xml data ArrayList adapter=new LazyAdapterbeth(getActivity(), songsList); list.setAdapter(adapter); // Click event for single list row list.setOnItemClickListener(new OnItemClickListener() {

    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

  • How to set message when I get Exception

    - by user1748932
    public class XMLParser { // constructor public XMLParser() { } public String getXmlFromUrl(String url) { String responseBody = null; getset d1 = new getset(); String d = d1.getData(); // text String y = d1.getYear(); // year String c = d1.getCircular(); String p = d1.getPage(); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("YearID", y)); nameValuePairs.add(new BasicNameValuePair("CircularNo", c)); nameValuePairs.add(new BasicNameValuePair("SearchText", d)); nameValuePairs.add(new BasicNameValuePair("pagenumber", p)); try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); responseBody = EntityUtils.toString(entity); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // return XML return responseBody; } public Document getDomElement(String xml) { Document doc = null; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); doc = db.parse(is); } catch (ParserConfigurationException e) { Log.e("Error: ", e.getMessage()); return null; } catch (SAXException e) { Log.e("Error: ", e.getMessage()); // i m getting Exception here return null; } catch (IOException e) { Log.e("Error: ", e.getMessage()); return null; } return doc; } /** * Getting node value * * @param elem * element */ public final String getElementValue(Node elem) { Node child; if (elem != null) { if (elem.hasChildNodes()) { for (child = elem.getFirstChild(); child != null; child = child .getNextSibling()) { if (child.getNodeType() == Node.TEXT_NODE) { return child.getNodeValue(); } } } } return ""; } /** * Getting node value * * @param Element * node * @param key * string * */ public String getValue(Element item, String str) { NodeList n = item.getElementsByTagName(str); return this.getElementValue(n.item(0)); } } I am getting Exception in this class for parsing data. I want print this message in another class which extends from Activity. Can you please tell me how? I tried much but not able to do.. public class AndroidXMLParsingActivity extends Activity { public int currentPage = 1; public ListView lisView1; static final String KEY_ITEM = "docdetails"; static final String KEY_NAME = "heading"; public Button btnNext; public Button btnPre; public static String url = "http://dev.taxmann.com/TaxmannService/TaxmannService.asmx/GetNotificationList"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // listView1 lisView1 = (ListView) findViewById(R.id.listView1); // Next btnNext = (Button) findViewById(R.id.btnNext); // Perform action on click btnNext.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { currentPage = currentPage + 1; ShowData(); } }); // Previous btnPre = (Button) findViewById(R.id.btnPre); // Perform action on click btnPre.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { currentPage = currentPage - 1; ShowData(); } }); ShowData(); } public void ShowData() { XMLParser parser = new XMLParser(); String xml = parser.getXmlFromUrl(url); // getting XML Document doc = parser.getDomElement(xml); // getting DOM element NodeList nl = doc.getElementsByTagName(KEY_ITEM); int displayPerPage = 5; // Per Page int TotalRows = nl.getLength(); int indexRowStart = ((displayPerPage * currentPage) - displayPerPage); int TotalPage = 0; if (TotalRows <= displayPerPage) { TotalPage = 1; } else if ((TotalRows % displayPerPage) == 0) { TotalPage = (TotalRows / displayPerPage); } else { TotalPage = (TotalRows / displayPerPage) + 1; // 7 TotalPage = (int) TotalPage; // 7 } int indexRowEnd = displayPerPage * currentPage; // 5 if (indexRowEnd > TotalRows) { indexRowEnd = TotalRows; } // Disabled Button Next if (currentPage >= TotalPage) { btnNext.setEnabled(false); } else { btnNext.setEnabled(true); } // Disabled Button Previos if (currentPage <= 1) { btnPre.setEnabled(false); } else { btnPre.setEnabled(true); } // Load Data from Index int RowID = 1; ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>(); HashMap<String, String> map; // RowID if (currentPage > 1) { RowID = (displayPerPage * (currentPage - 1)) + 1; } for (int i = indexRowStart; i < indexRowEnd; i++) { Element e = (Element) nl.item(i); // adding each child node to HashMap key => value map = new HashMap<String, String>(); map.put("RowID", String.valueOf(RowID)); map.put(KEY_NAME, parser.getValue(e, KEY_NAME)); // adding HashList to ArrayList menuItems.add(map); RowID = RowID + 1; } SimpleAdapter sAdap; sAdap = new SimpleAdapter(AndroidXMLParsingActivity.this, menuItems, R.layout.list_item, new String[] { "RowID", KEY_NAME }, new int[] { R.id.ColRowID, R.id.ColName }); lisView1.setAdapter(sAdap); } } This my class where I want to Print that message

    Read the article

1