Search code examples
javaandroidxmlfeedassets

Take an xml feed from the internet and put it in my assets


Currently i am developping an android application and i'm using an xml feed that i take from the internet.the problem is when my phone doesn't have an internet connection, my application crashs. I would like to obtain my xml file and put it in the assets.

My question is : is it possible ? And if yes, what's the best solution to do it ?


Solution

    1. Check for Network connection:

          public static boolean isConnectedToInternet(Context context) {
          ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivity != null)
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null)
                  for (int i = 0; i < info.length; i++)
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }
          }
          return false;
      }
      
    2. Download XML String

        public String getXMLString(String url) {
      
          try
          {
              URL url1 = new URL(url);
              URLConnection tc = url1.openConnection();
              tc.setConnectTimeout(timeout);
              tc.setReadTimeout(timeout);
              BufferedReader br = new BufferedReader((new InputStreamReader(tc.getInputStream())));
              StringBuilder sb = new StringBuilder();
              String line;
              while ((line = br.readLine()) != null)
              {
                  sb.append(line + "\n");
              }
              br.close();
              return sb.toString();
          } catch (Exception e)
          {
              Log.d("Error", "In XMLdownloading");
          }
      
          return null;
      }
      
    3. Save String to any directory in SD Card:

         private void writeStringToTextFile(String s, String f) {
      
          File sdCard = Environment.getExternalStorageDirectory();
          File dir = new File(sdCard.getAbsolutePath());
          dir.mkdirs();
      
          File file = new File(dir, f);
          try
          {
              FileOutputStream f1 = new FileOutputStream(file, false);
              PrintStream p = new PrintStream(f1);
              p.print(s);
              p.close();
              f1.close();
          } catch (FileNotFoundException e)
          {
          } catch (IOException e)
          {
          }
          }
          }