I am trying to parse Weather data in Android Studio from this link...
http://metwdb-openaccess.ichec.ie/metno-wdb2ts/locationforecast?lat=54.7210798611;long=-8.7237392806
I have tried using a XmlPullParser but I know I am making a mistake somewhere.
Here is the code so far...
public class WeatherParser extends AsyncTask {
URL url;
ArrayList<Weather> w = new ArrayList<>();
#Override
protected Object doInBackground(Object[] objects) {
try {
url = new URL("http://metwdb-openaccess.ichec.ie/metno-wdb2ts/locationforecast?lat=54.7210798611;long=-8.7237392806");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser parser = factory.newPullParser();
parser.setInput(url.openConnection().getInputStream(), "UTF_8");
ArrayList<Weather> weatherArrayList = parseXML(parser);
for(Weather weather: weatherArrayList ){
w.add(weather);
}
}catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return w;
}
private ArrayList<Weather> parseXML(XmlPullParser parser) throws XmlPullParserException, IOException{
ArrayList<Weather> weathers = null;
int eventType = parser.getEventType();
Weather weather = null;
while(eventType != XmlPullParser.END_DOCUMENT){
String name;
switch(eventType){
case XmlPullParser.START_DOCUMENT:
weathers = new ArrayList<>();
break;
case XmlPullParser.START_TAG:
name = parser.getName();
if(name.equals("time")){
weather = new Weather();
weather.time = parser.getAttributeValue(null, "from");
}
else if(weather != null){
if(name.equals("temperature")){
weather.temperature = parser.getAttributeValue(null, "value");
}
else if(name.equals("symbol")){
weather.weatherType = parser.getAttributeValue(null, "id");
}
}
}
}
return weathers;
}
public InputStream getInputStream(URL url) {
try {
return url.openConnection().getInputStream();
} catch (IOException e) {
return null;
}
}
public ArrayList<Weather> weathers()
{
return w;
}
}
Is an XMLParser the right tool to use or should i be looking into something else. I tried using a DOMParser in eclipse and it worked but I have no idea how to use one in Android Studio.
Related
This question already has answers here:
How to download and save an image in Android
(10 answers)
Closed 3 years ago.
I want to download an image from url. if the url does not have an image format at the end of the link? Example of url:
https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=1937530436393797&height=200&width=200&ext=1579152762&hash=AeQEq164H_oXIMjx
Try this code :
Create LocalImageSaver.java :
public class LocalImageSaver extends AsyncTask<Void, String, Boolean> {
private final SaveCompletionInterface saveCompletionInterface;
private final String originalImageUrl;
private final Context context;
private String savedImagePath;
private String fUrl;
public LocalImageSaver(Context context, String originalImageUrl, SaveCompletionInterface saveCompletionInterface) {
this.context = context;
this.saveCompletionInterface = saveCompletionInterface;
this.originalImageUrl = originalImageUrl;
}
/**
* Downloading file in background thread
*/
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
protected Boolean doInBackground(Void... f_url) {
this.fUrl = originalImageUrl;
FileOutputStream output = null;
InputStream is = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(fUrl);
HttpContext context = new BasicHttpContext();
HttpResponse response = client.execute(get, context);
is = response.getEntity().getContent();
int status = response.getStatusLine().getStatusCode();
if (status == 200 && is != null) {
String imageNameToSave;
String extension = originalImageUrl.substring(originalImageUrl.lastIndexOf(".") + 1); // Without dot jpg, png
if (extension.contains("mp4")) {
extension = "mp4";
}
String fileName = "";//originalImageUrl.substring(originalImageUrl.lastIndexOf("/") + 1); // Without dot jpg, png
fileName = "05Media_" + Calendar.getInstance().getTimeInMillis() + "." + extension;
imageNameToSave = fileName;
Uri savedImagePathUri = CommonImageUtil.createImageFile(imageNameToSave);
savedImagePath = savedImagePathUri.getPath();
// Output stream to write file
output = new FileOutputStream(savedImagePathUri.getPath());
int read = 0;
byte[] buffer = new byte[32768];
while ((read = is.read(buffer)) > 0) {
output.write(buffer, 0, read);
}
// flushing output
output.flush();
// closing streams
output.close();
is.close();
return true;
}
} catch (ClientProtocolException e) {
Lg.printStackTrace(e);
} catch (IOException e) {
Lg.printStackTrace(e);
} catch (Exception e) {
Lg.printStackTrace(e);
} finally {
// flushing output
try {
if (output != null) {
output.flush();
}
} catch (IOException e) {
Lg.printStackTrace(e);
}
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
Lg.printStackTrace(e);
}
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
Lg.printStackTrace(e);
}
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
saveCompletionInterface.onSaved(result, savedImagePath);
}
public interface SaveCompletionInterface {
public void onSaved(boolean result, String imageNameToSave);
}
}
and call this :
LocalImageSaver localImageSaver = new LocalImageSaver(getActivity(), url, new LocalImageSaver.SaveCompletionInterface() {
#Override
public void onSaved(boolean result, String savedImagePath) {
if (result) {
//showToast(getActivity(), (R.string.image_save_succesfull));
// refresh gallery
try {
MediaScannerConnection.scanFile(getActivity(), new String[]{savedImagePath}, null, new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
}
});
} catch (Exception e) {
}
} else {
//showToast(getActivity(), (R.string.error_saving_image));
}
}
});
localImageSaver.execute();
Hi I am using AsyncTaskLoader in my app and I have implemented that in MovieTaskLoader class but when I am implementing Loader callbacks in my fragment I am getting type conversion error in onCreateLoader() method.
MovieTaskLoader class:
class MovieTaskLoader extends AsyncTaskLoader<ArrayList<Movies>> {
MovieTaskLoader(Context context) {
super(context);
}
#Override
protected void onStartLoading() {
forceLoad();
}
#Override
public ArrayList<Movies> loadInBackground() {
//Building URL
URL url = null;
String jsonData = null;
Uri uri = Uri.parse(Utility.BASE_URL).buildUpon()
.appendPath("popular")
.appendQueryParameter("api_key", BuildConfig.api_key)
.build();
try {
url = new URL(uri.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
//Downloading json data
HttpURLConnection urlConnection;
try {
assert url != null;
urlConnection = (HttpURLConnection) url.openConnection();
if(urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
jsonData = readStream(urlConnection.getInputStream());
}
} catch (IOException e) {
e.printStackTrace();
}
return getMovieData(jsonData);
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuilder response = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
private ArrayList<Movies> getMovieData(String jsonData){
ArrayList<Movies> movies = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(jsonData);
JSONArray results = jsonObject.getJSONArray("results");
for(int i=0; i<20; i++){
Movies movie = new Movies();
JSONObject object = results.getJSONObject(i);
movie.setTitle(object.getString("title"));
movie.setSynopsis("overview");
movie.setVote_avg("vote_average");
movie.setDate("release_date");
movies.add(movie);
}
} catch (JSONException e) {
e.printStackTrace();
}
return movies;
}
}
Fragment class:
public class PopularFragment extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<Movies>> {
public PopularFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_popular, container, false);
RecyclerView popularView = (RecyclerView) view.findViewById(R.id.popular_view);
GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
popularView.setLayoutManager(layoutManager);
popularView.setAdapter(new RecyclerViewAdapter());
return view;
}
#Override
public Loader<ArrayList<Movies>> onCreateLoader(int id, Bundle args) {
return new MovieTaskLoader(getContext());
}
#Override
public void onLoadFinished(Loader<ArrayList<Movies>> loader, ArrayList<Movies> data) {
}
#Override
public void onLoaderReset(Loader<ArrayList<Movies>> loader) {
}
}
I am getting error in onCreateLoader() method and type conversion error is:
Required: "Loader"
Found: MovieTaskLoader
Check your imports. Make sure both are same versions like this
android.support.v4.content.AsyncTaskLoader<D>
android.support.v4.app.LoaderManager.LoaderCallbacks<D>
I have created a restful web service using this tutorial http://www.tutecentral.com/restful-api-for-android-part-1/ after running this i got an auto generated java file which contains the following code.
public class RestAPI {
private final String urlString = "http://125.0.0.174/Handler1.ashx";
private static String convertStreamToUTF8String(InputStream stream) throws IOException {
String result = "";
StringBuilder sb = new StringBuilder();
try {
InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[4096];
int readedChars = 0;
while (readedChars != -1) {
readedChars = reader.read(buffer);
if (readedChars > 0)
sb.append(buffer, 0, readedChars);
}
result = sb.toString();
} catch (UnsupportedEncodingException e){
e.printStackTrace();
}
return result;
}
private String load(String contents) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(60000);
Log.e("load r2","load r2");
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter w = new OutputStreamWriter(conn.getOutputStream());
w.write(contents);
w.flush();
InputStream istream = conn.getInputStream();
String result = convertStreamToUTF8String(istream);
return result;
}
private Object mapObject(Object o) {
Object finalValue = null;
if (o.getClass() == String.class) {
finalValue = o;
}
else if (Number.class.isInstance(o)) {
finalValue = String.valueOf(o);
} else if (Date.class.isInstance(o)) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss", new Locale("en", "USA"));
finalValue = sdf.format((Date)o);
}
else if (Collection.class.isInstance(o)) {
Collection<?> col = (Collection<?>) o;
JSONArray jarray = new JSONArray();
for (Object item : col) {
jarray.put(mapObject(item));
}
finalValue = jarray;
} else {
Map<String, Object> map = new HashMap<String, Object>();
Method[] methods = o.getClass().getMethods();
for (Method method : methods) {
if (method.getDeclaringClass() == o.getClass()
&& method.getModifiers() == Modifier.PUBLIC
&& method.getName().startsWith("get")) {
String key = method.getName().substring(3);
try {
Object obj = method.invoke(o, null);
Object value = mapObject(obj);
map.put(key, value);
finalValue = new JSONObject(map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return finalValue;
}
public JSONObject GetDoctors(String Terr_Code) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface","RestAPI");
o.put("method", "GetDoctors");
p.put("Terr_Code",mapObject(Terr_Code));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
public JSONObject GetUserDetail(String IMEINO) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface","RestAPI");
o.put("method", "GetUserDetail");
p.put("IMEINO",mapObject(IMEINO));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
}
I'm calling this class in async task and everything is working good but I want to use it through volley as async task is slow.
this class has only one url I don't understand how to call this url for individual methods I tried the below code but I'm getting bad url exception. Please show me how access the methods of rest api with separate urls.
public void requestJSON() {
String tag_json_obj = "json_obj_req";
final ProgressDialog pDialog = new ProgressDialog(context);
pDialog.setMessage("Loading...");
pDialog.show();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, null,
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
RestAPI restAPI = new RestAPI();
response = restAPI.GetDoctors(terrcode);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
display.setText(response.toString());
pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
display.setText(error.toString());
pDialog.hide();
}
});
// Adding request to request queue
VolleySingleton.getInstance().addToRequestQueue(jsonObjReq,
tag_json_obj);
}
Use Volley as VolleyService :
public class VolleyService {
private static VolleyService instance;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private VolleyService(Context context) {
requestQueue = Volley.newRequestQueue(context);
imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url,bitmap);
}
});
}
public static VolleyService getInstance(Context context) {
if (instance == null) {
synchronized(VolleyService.class) {
if (instance == null) {
instance = new VolleyService(context);
}
}
}
return instance;
}
public RequestQueue getRequestQueue() {
return requestQueue;
}
public ImageLoader getImageLoader() {
return imageLoader;
}
}
Then use your VolleyService in Activity or Fragment as this :
RequestQueue queue = VolleyService.getInstance(this.getContext()).getRequestQueue();
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// we got the response, now our job is to handle it
try {
//Here you parse your JSON - best approach is to use GSON for deserialization
getJsonFromResponse(response);
} catch (RemoteException | OperationApplicationException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//something happened, treat the error.
Log.e("Error", error.toString());
}
});
queue.add(request);
I'm trying to parse xml data from this URL:http://cloud.tfl.gov.uk/TrackerNet/LineStatus but am getting a NullPointerException on the line that read:
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
Before I show the code, I'd just like to say whats going on. First I download the XML file to the SDCard in
saveToSdCard();
Then I retrieve it with
getDataFromSDcard();
Here is my code:
Main Activity:
public class DashboardFragment extends SherlockFragment {
private CardUI mCardView;
String TUBE_STATUS_URL;
String KEY_ITEM = "LineStatus";
String KEY_LINE = "Line";
String KEY_NAME = "name";
String KEY_STATUS_DETAILS = "StatusDetails";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
View rootView = inflater.inflate(R.layout.activity_dashboard,
container, false);
// Get the URL's
TUBE_STATUS_URL = "http://cloud.tfl.gov.uk/TrackerNet/LineStatus";
// Find the cards in inflated layout
CardUI cardGroup = (CardUI) rootView.findViewById(R.id.cardsview);
fillCards(cardGroup);
DownloadFeedsTask task = new DownloadFeedsTask();
task.execute(new String[] { "" });
return rootView;
}
private void fillCards(CardUI cardGroup) {
// Fill cards with data
// init CardView
mCardView = cardGroup;
mCardView.setSwipeable(true);
// create a stack
CardStack delayStack = new CardStack();
delayStack.setTitle("Tube Lines with delays");
// add cards to stack
delayStack.add(new MyCard("Jubilee Line", MyCard.LINE_UNAVAILABLE));
delayStack.add(new MyCard("Victoria Line", MyCard.LINE_AVAILABLE));
delayStack
.add(new MyCard("Piccadilly Line", MyCard.LINE_IN_MAINTENANCE));
delayStack.add(new MyCard("Northern", MyCard.LINE_AVAILABLE));
// create a stack
CardStack activeStack = new CardStack();
activeStack.setTitle("Active Tube Lines");
// add cards to stack
activeStack.add(new MyCard("Jubilee Line", MyCard.LINE_HIDE_STATUS));
activeStack.add(new MyCard("Victoria Line", MyCard.LINE_HIDE_STATUS));
// add stack to cardView
mCardView.addStack(delayStack);
mCardView.addStack(activeStack);
// draw cards
mCardView.refresh();
}
#Override
public boolean onOptionsItemSelected(
com.actionbarsherlock.view.MenuItem item) {
return super.onOptionsItemSelected(item);
}
private class DownloadFeedsTask extends AsyncTask<String, Void, String> {
ArrayList<HashMap<String, String>> menuItems;
#Override
protected String doInBackground(String... urls) {
try {
saveToSdCard();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String response = "";
XMLParser parser = new XMLParser();
String xml = getDataFromSDcard(); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// 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_NAME, e.getAttribute(KEY_NAME));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
// adapter = new SimpleAdapter(
// mCtx,
// menuItems,
// R.layout.list_item,
// new String[] { KEY_ADVERT, KEY_CONTACT, KEY_DATE },
// new int[] { R.id.textView1, R.id.textView2, R.id.textView3 });
return response;
}
private String getDataFromSDcard() {
// Get data from SDCard
// Find the directory for the SD Card using the API
// *Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
// Get the text file
File file = new File(sdcard, "Folder/test.xml");
// Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e) {
// You'll need to add proper error handling here
}
return text.toString();
}
private void saveToSdCard() throws IOException {
try {
URL url = new URL(TUBE_STATUS_URL);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream is = url.openStream();
File testDirectory = new File(
Environment.getExternalStorageDirectory() + "/Folder");
if (!testDirectory.exists()) {
testDirectory.mkdir();
}
FileOutputStream fos = new FileOutputStream(testDirectory
+ "/test.xml");
byte data[] = new byte[1024];
int count = 0;
long total = 0;
int progress = 0;
while ((count = is.read(data)) != -1) {
total += count;
int progress_temp = (int) total * 100 / lenghtOfFile;
if (progress_temp % 10 == 0 && progress != progress_temp) {
progress = progress_temp;
}
fos.write(data, 0, count);
}
is.close();
fos.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onPostExecute(String result) {
// Toast.makeText(getActivity(), String.valueOf(menuItems.size()),
// Toast.LENGTH_LONG).show();
// Log.d("Commuter+", String.valueOf(menuItems.size()));
}
}
}
And my XMLParser class:
public class XMLParser {
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
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());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
Log.d("Commuter+", String.valueOf(doc.toString().length()));
// return DOM
return doc;
}
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
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 "";
}
}
I tried fixing this by testing my code with other URLs that had XML data and it worked, but there seems to be a problem when I use this URL.
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
You can simply surround your code with a Try/Catch block like this:
String xml;
Document doc;
NodeList nl;
try {
xml = parser.getXmlFromUrl(url); // getting XML
doc = parser.getDomElement(xml); // getting DOM element
nl = doc.getElementsByTagName(KEY_ITEM);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
This way you don't have to make any changes in your XMLParser class and you can easily handle any exceptions occurring while parsing your code in the main class itself. Also, for displaying error messages, Toast is the best thing according to me.
Hope this helps.. Thanks.
I would say, add throws SAXException in XMLParser.getDomElement() method and don't catch SAXException in this method as:
public Document getDomElement(String xml) throws SAXException {
Catch the SAXException in AndroidXMLParsingActivity.ShowData() where you are calling getDomElement() method and print the message in the desired way e.g.
public void ShowData() {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(url); // getting XML
Document doc = null;
try{
doc = parser.getDomElement(xml); // getting DOM element
}catch(SAXException sae){
//print the desired message here
}
.......
.......
}
For showing Message from Non Activity Class you will need to pass Current Activity Context as:
public class XMLParser {
Context context
// constructor
public XMLParser(Context conts) {
context =conts;
}
///YOUR CODE
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());
Toast.makeToast(context, e.toString(), Toast.Long).show();
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
Toast.makeToast(context, e.toString(), Toast.Long).show();
// i m getting Exception here
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
Toast.makeToast(context, e.toString(), Toast.Long).show();
return null;
}
Simply pass the constructor to your XMLParser class and used that there as your constructor. Or, you can try with use of getApplicationContext() You can simply show the Toast when you getting an exception like below -
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());
Toast.makeToast(con, e.toString(), Toast.Long).show(); // Will show the message of exception
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
Toast.makeToast(con, e.toString(), Toast.Long).show(); // Will show the message of exception
// i m getting Exception here
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
Toast.makeToast(con, e.toString(), Toast.Long).show(); // Will show the message of exception
return null;
}
Update
Okay, just pass the constructor as per below - Where you are calling that XMLparser class just call like below -
....
XMLParser xml = new XMLParser(AndroidXMLParsingActivity.this);
....
And, in XMLParser class there mention your constructor like below -
public class XMLParser {
Context con;
public XMLParser(Context context) {
con = context;
}
......
}
And, use this con as your constructor in your XMLParser class.