Auto Generate #String reference in Android Studio for all hardcoded strings - android

When I started coding my project I did not know the string resource. Now I would like to use this resource for all my string. How do you do it all of a sudden? Knowing that I have more than 10000 strings currently I do not want to do it one by one by hand ...

To automate this completely you need a special tool (I haven't found one), outside of Android Studio to:
Find the string (and replace with the reference)
Update strings.xml
optionally translate strings
For one at a time manual extract (See also link):Alt+Enter, Extract String Resource while the caret is inside the hardcoded string in code:
and in XML:

I don't think, that there is a slink workaround considering, that you need to name all string somehow with a unique and useful identifier. When you let this be done automatically, your code will get quite hard to read :/

Just highlight every instance of a string,then click on the yellow hint icon on the left of the statemnt to extract string resource.Then you can remove duplicated strings later.

I wrote a java script for xml layouts at least, for anyone who needs it... There might be some minor fixes required later.
package com.cameron.smelevel.lib;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class StringResourceCreator {
public static void main(String [] args){
String mainDirPath = "S:\\androidProject\\src";
String layoutDirPath = "\\main\\res\\layout";
String outputDirPath = mainDirPath+"-out";
String stringFilePath = outputDirPath+"\\strings.txt";
String line;
File layoutDir = new File(mainDirPath + layoutDirPath);
File layoutOutDir = new File(outputDirPath + layoutDirPath);
layoutOutDir.mkdirs();
HashMap<String, String> stringEnteries = new HashMap<>();
for (File file : layoutDir.listFiles()) {
String fileName = file.getName();
PrintWriter pr = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(file);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
FileWriter outputStream = new FileWriter(layoutOutDir.getAbsolutePath() + "\\"+ fileName);
pr = new PrintWriter(outputStream);
while ((line = bufferedReader.readLine()) != null) {
line = getModifiedLine(line, stringEnteries);
pr.write(line);
pr.println();
}
} catch(FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}finally {
if(pr != null) pr.close();
}
}
PrintWriter pr = null;
try {
FileWriter outputStream = new FileWriter(stringFilePath);
pr = new PrintWriter(outputStream);
Iterator it = stringEnteries.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
String entry = "<string name=\"" + pair.getKey() + "\">" + pair.getValue() + "</string>";
it.remove(); // avoids a ConcurrentModificationException
pr.write(entry);
pr.println();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(pr != null) pr.close();
}
}
private static String getModifiedLine(String line, HashMap<String, String> stringEnteries) {
if (line.contains(":text=\"") || line.contains(":hint=\"")){
StringBuilder fieldName = new StringBuilder();
String text = line.substring(line.indexOf("\"")+1, line.lastIndexOf("\""));
String textTrimmed = text.replace("\\n","");
if (!textTrimmed.startsWith("#string")){
String[] words = textTrimmed.split(" ");
for (int j = 0; j < words.length; j++) {
String word = words[j];
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (Character.isAlphabetic(c))
if (i == 0 && fieldName.length() != 0)
fieldName.append(Character.toUpperCase(c));
else
fieldName.append(Character.toLowerCase(c));
}
}
if (fieldName.length() > 1) {
String value = stringEnteries.get(fieldName.toString());
if(value != null) {
if (!value.equals(text)) {
fieldName.append("1");
stringEnteries.put(fieldName.toString(), text);
}
}else
stringEnteries.put(fieldName.toString(), text);
line = line.replace(text, "#string/"+fieldName);//replaceLast(line, text, "#string/"+fieldName);
}
}
}
return line;
}
}

Related

How to open epub files with Images and contents and when we click on contents then it move to particular part

i want to open ebub files either in webview or by something else but content click and images,videos should be there
-I have tried using webview but images cant display in that
textView.setText(Html.fromHtml(data, new Html.ImageGetter() {
#Override
public Drawable getDrawable(String source) {
String imageAsStr = source.substring(source.indexOf(";base64,") + 8);
byte[] imageAsBytes = Base64.decode(imageAsStr, Base64.DEFAULT);
Bitmap imageAsBitmap = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
int imageWidthStartPx = (pxScreenWidth - imageAsBitmap.getWidth()) / 2;
int imageWidthEndPx = pxScreenWidth - imageWidthStartPx;
Drawable imageAsDrawable = new BitmapDrawable(getResources(), imageAsBitmap);
imageAsDrawable.setBounds(imageWidthStartPx, 0, imageWidthEndPx, imageAsBitmap.getHeight());
return imageAsDrawable;
}
}, null));
-i tried this also but in this images are display but content click is no there
Use this code provided you have necessary libraries and sampleepubfile.epub in your assets...
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.domain.TOCReference;
import nl.siegmann.epublib.epub.EpubReader;
import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.webkit.WebView;
public class EPubDemo extends Activity {
WebView webview;
String line, line1 = "", finalstr = "";
int i = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
AssetManager assetManager = getAssets();
try {
// find InputStream for book
InputStream epubInputStream = assetManager
.open("sampleepubfile.epub");
// Load Book from inputStream
Book book = (new EpubReader()).readEpub(epubInputStream);
// Log the book's authors
Log.i("author", " : " + book.getMetadata().getAuthors());
// Log the book's title
Log.i("title", " : " + book.getTitle());
/* Log the book's coverimage property */
// Bitmap coverImage =
// BitmapFactory.decodeStream(book.getCoverImage()
// .getInputStream());
// Log.i("epublib", "Coverimage is " + coverImage.getWidth() +
// " by "
// + coverImage.getHeight() + " pixels");
// Log the tale of contents
logTableOfContents(book.getTableOfContents().getTocReferences(), 0);
} catch (IOException e) {
Log.e("epublib exception", e.getMessage());
}
String javascrips = "";
try {
// InputStream input = getResources().openRawResource(R.raw.lights);
InputStream input = this.getAssets().open(
"poe-fall-of-the-house-of-usher.epub");
int size;
size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
// byte buffer into a string
javascrips = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
// String html = readFile(is);
webview.loadDataWithBaseURL("file:///android_asset/", javascrips,
"application/epub+zip", "UTF-8", null);
}
#SuppressWarnings("unused")
private void logTableOfContents(List<TOCReference> tocReferences, int depth) {
if (tocReferences == null) {
return;
}
for (TOCReference tocReference : tocReferences) {
StringBuilder tocString = new StringBuilder();
for (int i = 0; i < depth; i++) {
tocString.append("\t");
}
tocString.append(tocReference.getTitle());
Log.i("TOC", tocString.toString());
try {
InputStream is = tocReference.getResource().getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
while ((line = r.readLine()) != null) {
// line1 = Html.fromHtml(line).toString();
Log.v("line" + i, Html.fromHtml(line).toString());
// line1 = (tocString.append(Html.fromHtml(line).toString()+
// "\n")).toString();
line1 = line1.concat(Html.fromHtml(line).toString());
}
finalstr = finalstr.concat("\n").concat(line1);
// Log.v("Content " + i, finalstr);
i++;
} catch (IOException e) {
}
logTableOfContents(tocReference.getChildren(), depth + 1);
}
webview.loadDataWithBaseURL("", finalstr, "text/html", "UTF-8", "");
}
}
I have tried this and its working for me

Filter HTML Code out of Website (cache it) and load it into WebView (RegEx)

I am relativly new to programming in java and android, so I wanted to ask you guys for a simple and understandable way of filtering two tables and their h3 headings of this website, possibly even cache it, and load it into a transparent WebView, so it doesnt look like a website. I thought of RegEx.. I do this to keep it up to date without having to service that thing.
With "simple and understandable" I mean comments, and possibly show what are just var names, method names or other custom names. And many explanations, comments and other things... Of course you can also just bomb the code in there, that would also work but I probably could not understand all of it.. ;)
Here's some code I tried:
package com.mrousavy.gemeindemuckendorfwipfing;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by Marc on 15.10.2015.
*/
public class Table {
// found on stackoverflow
public static boolean exists2(String url) {
try {
URL u = new URL(url);
HttpURLConnection connection = (HttpURLConnection) u.openConnection();
connection.setRequestMethod("HEAD");
connection.connect();
return connection.getResponseCode() == HttpURLConnection.HTTP_OK;
} catch (Exception ex) {
return false;
}
}
/**
* must NOT be called in main thread!!!
*/
public static String getHTML2(String url) throws Exception {
try {
URL u = new URL(url);
BufferedReader in = new BufferedReader(new InputStreamReader(u.openStream()));
String tmp, html = "";
while ((tmp = in.readLine()) != null) {
html += tmp;
try {
Thread.sleep(10);
} catch (Exception e) {
}
}
return html;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* must NOT be called in main thread!!!
*/
public static List<String> getUrlsFromHTML2(String html) throws Exception {
List<String> urls = new ArrayList();
//init Patterns
Pattern divsPattern = Pattern.compile("<h3>.</table>");
//Pattern urlPattern = Pattern.compile("<a href=\"\\./files/(.*?)\"");
//search for right divs
Matcher divs = divsPattern.matcher(html);
while (divs.find()) {
//search for links
String innerDiv = divs.group(1);
Matcher url = urlPattern.matcher(innerDiv);
if (url.find()) {
if (!urls.contains(url.group(1)))
urls.add(url.group(1));
}
try {
Thread.sleep(10);
} catch (Exception e) {
}
}
return urls;
}
public static List<News> getNewsFromHTML(String html) {
List<News> ret = new ArrayList();
Pattern firstNewsPattern = Pattern.compile("<h3><strong>Aktuelle Meldungen</strong></h3>(.*?)<hr />");
Pattern newsPattern = Pattern.compile("<hr />(.*?)<hr />");
Pattern newsHeaderPattern = Pattern.compile("<h4>(.*?)</h4>");
Pattern hrefPattern = Pattern.compile("href=\"(.*?)\"");
Matcher newsHeader = null;
Matcher href = null;
Matcher firstNews = firstNewsPattern.matcher(html);
if(firstNews.find()) {
String content = firstNews.group(1).replace("./", "http://www.muckendorf-wipfing.at/");
href = hrefPattern.matcher(content);
while(href.find()) {
String url = href.group(1);
if(!url.contains("/")) {
content = content.replace("href=\"" + url + "\"", "href=\"" + "http://www.muckendorf-wipfing.at/" + url + "\"");
}
}
newsHeader = newsHeaderPattern.matcher(content);
if(newsHeader.find())
ret.add(new News(newsHeader.group(1).replaceAll("<(.*?)>", "").replaceAll("&#\\d{4};", ""), content));
}
Matcher news = newsPattern.matcher(html);
while(news.find()) {
String content = news.group(1).replace("./", "http://www.muckendorf-wipfing.at/");
href = hrefPattern.matcher(content);
while(href.find()) {
String url = href.group(1);
if(!url.contains("/")) {
content = content.replace("href=\"" + url + "\"", "href=\"" + "http://www.muckendorf-wipfing.at/" + url + "\"");
}
}
newsHeader = newsHeaderPattern.matcher(content);
if(newsHeader.find())
ret.add(new News(newsHeader.group(1).replaceAll("<(.*?)>", "").replaceAll("&#\\d{4};", ""), content));
}
return ret;
}
public static String listToString(List<String> list) {
String ret = "";
for(String str : list) {
ret += str + "§";
}
ret = ret.substring(0, ret.length()-1);
return ret;
}
public static List<String> stringToList(String str) {
String[] arr = str.split("§");
List <String> ret = new ArrayList();
for(String s : arr) {
if(!s.trim().equals(""))
ret.add(s);
}
return ret;
}
public static String extractContentFromHTML(String html) {
Pattern regex = Pattern.compile("<div id=\"content\">((.*?(<div.*?<\\/div>)*.*?)*)<\\/div>");
Pattern hrefPattern = Pattern.compile("href=\"(.*?)\"");
Matcher match = regex.matcher(html);
if(match.find()) {
String content = match.group(1).replace("./", "http://www.muckendorf-wipfing.at/");
Matcher href = hrefPattern.matcher(content);
while(href.find()) {
String url = href.group(1);
if(!url.contains("/")) {
content = content.replace("href=\"" + url + "\"", "href=\"" + "http://www.muckendorf-wipfing.at/" + url + "\"");
}
}
return content;
}
return "";
}
}
I hope someone can help me out! :)
Thank you! ^^
Don't use regex to parse html/xml, it's error prone. Try using specialized lib as the excellent Jsoup:
import org.jsoup.Jsoup;
import org.jsoup.Connection;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
[...]
final String url = "http://www.muckendorf-wipfing.at/25-0-Wirtschaft+und+Gastronomie.html";
String tablesHtml = parseHTML(url);
[...]
String parseHTML(String url) {
//Retrieve html of {url} via GET
Connection.Response response = Jsoup.connect(url).method(Connection.Method.GET).execute();
//Parse html
Document doc = response.parse();
//Select the div with id="content", where both tables are stored
Element contentDiv = doc.select("div#content").first();
//return the inner html of <div id="content"> selected above
return contentDiv.html();
}
The syntax of the select function can be found here
UPDATE: i've updated the code to parse the content of div too, creating a Table class that store <h3> text and table as 'html' and also as a bidimensional String array. It has a nice toString() method too useful to see what you get.
NB: The trick is in the jsoup select statement "h3:contains(" + h3Text + ") ~ table": it selects the tables after and h3 tag with h3Text (the title of the table) inside. Later we're taking only the first table of the list so we can be sure we're selecting the table coupled with the h3 title.
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
//[...]
/* //CASE 1: if you have to download the html
* String url = "http://www.muckendorf-wipfing.at/25-0-Wirtschaft+und+Gastronomie.html";
* //Retrieve html of "url" via GET
* Connection.Response response = Jsoup.connect(url).method(Connection.Method.GET).execute();
* //Parse html
*Document doc = response.parse();
*/
//CASE 2: If you already have the html in a String called htmlString
Document doc = Jsoup.parse(htmlString);
//Select the div with id="content", where both tables are stored
Element contentDiv = doc.select("div#content").first();
//Create a list for the data
List tables = new ArrayList<Table>();
//Loop on h3 titles and get the coupled table below
for ( Element h3 : contentDiv.select("h3") )
{
//get the text inside <h3> tag
String h3Text = h3.text();
//jsoup select statement to get the table
//immediately after the <h3></h3>
String select = "h3:contains(" + h3Text + ") ~ table";
//Actually get the jsoup table element jTable
Element jTable = contentDiv.select(select).first();
//Load the data on the list
tables.add(new Table(h3Text,jTable));
}
//print them
for ( Table t : tables )
System.out.println(t);
//[...]
class Table
{
String h3Title;
String htmlTable;
String[][] splittedTable;
Table(String h3Title, Element jTable)
{
this.h3Title = h3Title;
this.htmlTable = jTable.html();
this.splittedTable = getSplittedTable(jTable);
}
String[][] getSplittedTable(Element jTable)
{
//Get all the rows of the jTable
Elements trs = jTable.select("tr");
//Get the number of rows
int rows = trs.size();
//Get the columns of the first row (the same of all the rows)
int columns = trs.first().select("td").size();
//Allocate new bidimensional array table
String[][] table = new String[rows][columns];
int i = 0; int j = 0;
for ( Element tr : trs ) {
for ( Element td : tr.select("td") ) {
table[i][j++] = td.text();
}
j = 0; //reset column cursor
i++; //increment row cursor
}
return table;
}
#Override
String toString() {
StringBuilder sb = new StringBuilder();
String ln = System.lineSeparator();
sb.append(h3Title + ln);
sb.append("--" + ln);
sb.append(this.htmlTable + ln);
sb.append("--" + ln);
for (int i = 0; i < splittedTable.length; i++) {
for (int j = 0; j < splittedTable[i].length; j++) {
sb.append(splittedTable[i][j] + " | ")
}
sb.append(ln + "--" + ln);
}
return sb.toString();
}
}

Android Augmented Reality Pro AR 9: activity gets back when displays too many markers

I'm using this very useful tutorial (https://github.com/RaghavSood/ProAndroidAugmentedReality) for developing a custom AR app.
It works pretty fine, but when I display markers extracted from a file folder (sometimes) the app gets blocked and restarts from the previous activity.
I suppose it's because of the big number of markers situated in the same point of the screen.
Infact, when I lower the radius, and then showing a littler number of markers, the activity continues to work.
Besides, I've tried to modify the function "getTextWidth()" as many people suggest on the net.
I don't know how to reduce the number of Markers drawn on the same point of the screen (so indipendently from reducing the radius). Can you suggest me something? THANKS A LOT!!!!!
I show you the LocalDataSource.java modified:
package com.example.pointofinterests;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.example.pointofinterests.R;
import com.example.pointofinterests.IconMarker;
import com.example.pointofinterests.Marker;
/**
* This class should be used as a example local data source. It is an example of
* how to add data programatically. You can add data either programatically,
* SQLite or through any other source.
*
* #author Justin Wetherell <phishman3579#gmail.com>
*/
public class LocalDataSource extends DataSource {
private List<Marker> cachedMarkers = new ArrayList<Marker>();
private static Bitmap icon = null;
public LocalDataSource(Resources res) {
if (res == null) throw new NullPointerException();
createIcon(res);
}
protected void createIcon(Resources res) {
if (res == null) throw new NullPointerException();
icon = BitmapFactory.decodeResource(res, R.drawable.icon);
}
public List<Marker> getMarkers() {
try{
String TestoIDPercorsi = readFileAsString("/sdcard/Epulia/IDPercorsi.txt");
if(TestoIDPercorsi==""){
// DOING NOTHING
}else {
String[] IDPercorso = TestoIDPercorsi.split("#");
for(int l=0; l<IDPercorso.length-1; l++){
String TestoPercorso = readFileAsString("/sdcard/Epulia/Percorso" + IDPercorso[l] + ".txt");
if (TestoPercorso.equals("")){
}else {
ArrayList<String> IDSTEPS2 = new ArrayList<String>();
String[] temp = TestoPercorso.split("#");
for (int j=1; j < temp.length; j++){
Log.d("RIGA_" + j + "_" + IDPercorso[l], temp[j]);
if(temp[j].substring(0,2).contains("P")){//POI
String[] POI = temp[j].split("\\|");
String id = POI[1];
String description = POI[2];
Double lat = Double.parseDouble(POI[3]);
Double lng = Double.parseDouble(POI[4]);
String type = POI[5];
Marker poi = new IconMarker(description, lat,lng, 0, Color.DKGRAY, icon);
cachedMarkers.add(poi);
}
}
}
}
}
}catch (Exception e){
Log.e("EXCEPTION", "> " + e);
}
return cachedMarkers;
}
public static String readFileAsString(String filePath) {
String result = "";
File file = new File(filePath);
if ( file.exists() ) {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
char current;
while (fis.available() > 0) {
current = (char) fis.read();
result = result + String.valueOf(current);
}
} catch (Exception e) {
Log.d("TourGuide", e.toString());
} finally {
if (fis != null)
try {
fis.close();
} catch (IOException ignored) {
}
}
}
return result;
}
}
I would like to thank the Author of the Tutorial who helped me in fixing the problem.
I report his answer that soled my problem:
Not sure why you have that limitation but this should limit the number of Markers drawn on the screen.
In class AugmentedView.java
You can introduce a new member variable:
private static int MAX_NUM_TO_DRAW = 10;
Then in the method onDraw(Canvas canvas):
You can quit the drawing loop early.
int i=0;
ListIterator<Marker> iter = collection.listIterator(collection.size());
while (iter.hasPrevious() && i<MAX_NUM_TO_DRAW ) {
Marker marker = iter.previous();
marker.draw(canvas);
i++;
}

Poor Performance of Android app

I had written a crawler program in C# which used to crawl on a given url or url postfixed with page number and download all the image files from it.It worked fine.
Now I am a newbie in android programming and thought to write the same thing for my android device so that I can also use it on my phone.
The algorithm I followed was...
1) Take the base url,start page no(in case the url is postfixed by page number in query string),end page no,and location to store the images on sdcard.
2) If end page no is less than start page no(means if i only want to crawl a single page) pass it to getHtml method. or else make a loop from start to end page and pass each url to getHtml method.
3) In getHtml method I download web page source and broke it in pieces to find link to image files in it.
4) for each image url found, download the image file to the given save location.
The algo seems easy but when I made the whole program I had some pretty big performance issues. It is so so heavy that while running it in emulator all i could see was gc clearing objects in logcat.Another very common issue is that the UI hangs.But as the program is only for personal use i can do with it because I doesnt know multithreading in android. But atleast the program should be fast. Is there any way I can decrease the number of objects or destroy them myself.
Is there anything I can do to improve this. I wonder how those GBs worth of games works flawlessly and my 20KB app is so so slow.
The whole code is.
package com.dwnldr;
import java.io.*;
import java.net.*;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.app.Activity;
import android.os.*;
import android.util.Log;
import android.view.View;
import android.widget.*;
public class IMGDwnldrActivity extends Activity {
EditText res;
String str;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.button1);
File SDCardRoot = Environment.getExternalStorageDirectory();
EditText saveat = (EditText) findViewById(R.id.editText4);
saveat.setText(SDCardRoot.getAbsolutePath());
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
//Getting URL,Start pageno,End pageno and the save location on sdcard
EditText baseurl = (EditText) findViewById(R.id.editText1);
String url = baseurl.getText().toString();
EditText startpage = (EditText) findViewById(R.id.editText2);
int start = Integer.parseInt(startpage.getText().toString());
EditText endpage = (EditText) findViewById(R.id.editText3);
int end = Integer.parseInt(endpage.getText().toString());
EditText saveat = (EditText) findViewById(R.id.editText4);
String save = saveat.getText().toString();
if (start <= end) {
for (int i = start; i <= end; i++) {
str = "\n--------------------";
str += "\nPage No" + String.valueOf(i);
writemsg(str);
getHtml(url + String.valueOf(i), save);
}
} else
getHtml(url, save);
writemsg("Done");
} catch (Exception ee) {
writemsg("\nException fired::" + ee.getMessage());
}
}
});
}
//method to get the source of a particular url
public void getHtml(String url, String save) throws ClientProtocolException, IOException {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet, localContext);
String result = "";
str = "\nDownloading Page....";
writemsg(str);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().
getContent()));
String line = null;
while ((line = reader.readLine()) != null) {
result += line + "\n";
}
str = "\nPage Downloaded...";
writemsg(str);
String[] pieces;
if (result.contains(".jpg") || result.contains(".jpeg")) {
pieces = result.split("\"");
Log.d("Events", String.valueOf(pieces.length));
for (int i = 0; i < pieces.length; i++) {
if (pieces[i].contains(".jpg") || pieces[i].contains(".jpeg")) {
if (pieces[i].contains("http")) {
Log.d("Events", pieces[i]);
downloadme(pieces[i], save);
} else {
URL u = new URL(url);
if (pieces[i].startsWith("."));
pieces[i] = pieces[i].substring(pieces[i].indexOf("/"), pieces[i].length());
writemsg(u.getProtocol() + "://" + u.getHost() + pieces[i]);
if (pieces[i].startsWith("/"))
downloadme(u.getProtocol() + "://" + u.getHost() + pieces[i], save);
else
downloadme(u.getProtocol() + "://" + u.getHost() + "/" + pieces[i], save);
}
}
}
}
} catch (Exception ee) {
writemsg("\nException fired::" + ee.getMessage());
}
}
//download each image url given
private void downloadme(String url1, String save) {
try {
str = "\nDownloading Image " + url1;
writemsg(str);
URL url = new URL(url1);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File f = new File(save);
if (f.isDirectory() && !f.exists())
f.mkdirs();
String fileName = url1.substring(url1.lastIndexOf('/') + 1, url1.length());
File file = new File(save, fileName);
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
str = "\nImage Size " + String.valueOf(totalSize / 1024);
writemsg(str);
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
str = "\nDownloaded Image " + url1;
writemsg(str);
catch some possible
errors // ...
} catch (MalformedURLException e) {
writemsg("\nException fired::" + e.getMessage());
} catch (IOException e) {
writemsg("\nException fired::" + e.getMessage());
} catch (Exception ee) {
writemsg("\nException fired::" + ee.getMessage());
}
}
//write certain text to the Result textbox
private void writemsg(String msg) {
res = (EditText) findViewById(R.id.result);
String str = res.getText().toString();
str += msg;
res.setText(str);
}
}

Android dom parser error

I'm facing a particular problem while parsing xml so the parser works fine until it encouters <Url/> tag which contains no value, I already made the test il my code :
static final String ImageHotel = "Url";
...
else if (name.equalsIgnoreCase("ImageHotel")){
message.setHotelImage(property.getFirstChild().getNodeValue());
if (!marchand.getImgHtlUrl().equalsIgnoreCase("")){
message.setHotelImageLink(new URL(marchand.getImgHtlUrl() + property.getFirstChild().getNodeValue()));
}else{
message.setHotelImageLink(new URL("http://localhost/noimage.jpg"));
}
}
This keep throwing error even when i tried to bypass by surrounding with try/catch..
any help is welcome
thanks.
Houssem.
I have reference to parse this file try to add your own data and get tag value....
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Vector;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class NewsParsing {
NewsBeen Objnewsbeen;
Vector<NewsBeen> vectParse;
public NewsParsing() {
System.out.println("Constructor is calling Now ...");
try {
vectParse = new Vector<NewsBeen>();
// http://www.npr.org/rss/rss.php?id=1001
URL url = new URL(
"http://www.npr.org/rss/rss.php?id=1001");
URLConnection con = url.openConnection();
System.out.println("Connection is : " + con);
BufferedReader reader = new BufferedReader(new InputStreamReader(
con.getInputStream()));
System.out.println("Reader :" + reader);
String inputLine;
String fullStr = "";
while ((inputLine = reader.readLine()) != null)
fullStr = fullStr.concat(inputLine + "\n");
InputStream istream = url.openStream();
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
System.out.println("Builder : " + builder);
Document doc = builder.parse(istream);
System.out.println("Doc is : " + doc);
doc.getDocumentElement().normalize();
System.out.println("After Normlize : " + doc);
System.out.println("Root is : "
+ doc.getDocumentElement().getNodeName());
System.out
.println("-------------------------------------------------------------------------------------------------------------");
Element element = doc.getDocumentElement();
parseFile(element);
for (int index1 = 0; index1 < vectParse.size(); index1++) {
NewsBeen ObjNB = (NewsBeen) vectParse.get(index1);
System.out.println("Item No : " + index1);
System.out.println();
System.out.println("Title is : " + ObjNB.title);
System.out.println("Description is : " + ObjNB.description);
System.out.println("Pubdate is : " + ObjNB.pubdate);
System.out.println("Link is : " + ObjNB.link);
System.out.println("Guid is : " + ObjNB.guid);
System.out.println();
System.out
.println("-------------------------------------------------------------------------------------------------------------");
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void parseFile(Node node) {
NodeList nodelist = node.getChildNodes();
for (int index = 0; index < nodelist.getLength(); index++) {
Node nodefromList = nodelist.item(index);
if (nodefromList.getNodeType() == Node.ELEMENT_NODE) {
// System.out.println("node.getNodeType() : " +
// nodefromList.getNodeType());
// System.out.println("Node is : " + node.getNodeName());
if (nodefromList.getNodeName().equalsIgnoreCase("item")) {
Objnewsbeen = new NewsBeen();
vectParse.addElement(Objnewsbeen);
}
if (nodefromList.hasChildNodes()) {
if (nodefromList.getChildNodes().item(0).getNodeName()
.equals("#text")) {
if (!nodefromList.getChildNodes().item(0)
.getNodeValue().trim().equals("")
&& Objnewsbeen != null)
if (nodefromList.getNodeName().equalsIgnoreCase(
"title")) {
Objnewsbeen.title = nodefromList
.getChildNodes().item(0).getNodeValue();
} else if (nodefromList.getNodeName()
.equalsIgnoreCase("description")) {
Objnewsbeen.description = nodefromList
.getChildNodes().item(0).getNodeValue();
} else if (nodefromList.getNodeName()
.equalsIgnoreCase("pubDate")) {
Objnewsbeen.pubdate = nodefromList
.getChildNodes().item(0).getNodeValue();
} else if (nodefromList.getNodeName()
.equalsIgnoreCase("link")) {
Objnewsbeen.link = nodefromList.getChildNodes()
.item(0).getNodeValue();
} else if (nodefromList.getNodeName()
.equalsIgnoreCase("guid")) {
Objnewsbeen.guid = nodefromList.getChildNodes()
.item(0).getNodeValue();
} else {
// System.out.println();
}
}
parseFile(nodefromList);
}
}
}
}
public static void main(String[] args) {
new NewsParsing();
}
}
The NewsBeen class is::
public class NewsBeen {
public String title;
public String description;
public String pubdate;
public String link;
public String guid;
}
I told you that surrounding with try/catch did not work, so, now it does, because i had to track the NullPointerException instead of simple Exception, like this :
try{
message.setHotelImage(property.getFirstChild().getNodeValue());
}catch(NullPointerException nEx){
marchand.setImgHtlUrl("");
}
thank you guys and sorry for this alert ;)

Categories

Resources