I am trying to parse Vcard file. here is my code.
public void get_vcf_data(String file) throws VCardException, IOException{
VCardParser parser = new VCardParser();
VDataBuilder builder = new VDataBuilder();
//String file = path;
//read whole file to string
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(file), "UTF-8"));
String vcardString = "";
String line;
while ((line = reader.readLine()) != null) {
vcardString += line + "\n";
}
reader.close();
//parse the string
boolean parsed = parser.parse(vcardString, "UTF-8", builder);
if (!parsed) {
throw new VCardException("Could not parse vCard file: " + file);
}
//get all parsed contacts
List<VNode> pimContacts = builder.vNodeList;
//do something for all the contacts
for (VNode contact : pimContacts) {
ArrayList<PropertyNode> props = contact.propList;
//contact name - FN property
String name = null;
String number = null;
String tel = null;
for (PropertyNode prop : props) {
if ("FN".equals(prop.propName)) {
name = prop.propValue;
Contact_name.add(name);
Log.d("Name", name);
//we have the name now
break;
}
}
for (PropertyNode prop : props) {
if ("N".equals(prop.propName)) {
number = prop.propValue;
Contact_number.add(number);
Log.d("Name", number);
//we have the name now
break;
}
}
for (PropertyNode prop : props) {
if(" TEL".equals(prop.propName))
{
tel = prop.propValue;
Contact_tel.add(tel);
Log.d("Name", tel);
}
}
Log.d("Tag", ""+Contact_name.size()+"::"+Contact_number.size()+"::"+Contact_tel.size());
//similarly for other properties (N, ORG, TEL, etc)
//...
System.out.println("Found contact: " + name);
}
}
but facing problem in while loop
while ((line = reader.readLine()) != null) {
vcardString += line + "\n";
}
continuously looping inside a while loop and doesn't exit from loop once it is entered
Related
InputStream is = getResources().openRawResource(R.raw.babynames);
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, Charset.forName("UTF-8"))
);
String line = "";
try {
reader.readLine();
while ((line = reader.readLine()) != null) {
Log.d("MyActivity", "Line: " + line);
String[] tokens = line.split(",");
BabyName name = new BabyName();
name.setGender(tokens[1]);
name.setMeaning(tokens[2]);
name.setName(tokens[3]);
name.setOrigin(tokens[4]);
babyNames.add(name);
Log.d(TAG, "Just created: " + name);
}
} catch (IOException e) {
Log.wtf("MyActivity", "Error reading data file on line" + line, e);
e.printStackTrace();
}
i am trying this but the app crashes and I got an error of array index out of bound and in logs i am getting the data
BabyName name = new BabyName();
name.setGender(tokens[1]);
name.setMeaning(tokens[2]);
name.setName(tokens[3]);
name.setOrigin(tokens[4]);
shouldn't the index start from 0
name.setGender(tokens[0]);
i am confused why my code isn't capitalizing my first letter, i am getting the name of the user from the database with all letters lower case.
here is the code:
String email = null;
String name = null;
StringBuilder nameSB = new StringBuilder();
nameSB.append(name);
nameSB.setCharAt(0, Character.toUpperCase(nameSB.charAt(0)));
name = nameSB.toString();
try {
email = ((User) ParseUser.getCurrentUser()).getEmail();
name = ((User) ParseUser.getCurrentUser()).getFirstName() + " " + ((User) ParseUser.getCurrentUser()).getLastName();
} catch (NullPointerException npe) {
}
Just summarising as answer
String email = null;
String name = null;
StringBuilder nameSB = new StringBuilder();
try {
email = ((User) ParseUser.getCurrentUser()).getEmail();
name = ((User) ParseUser.getCurrentUser()).getFirstName() + " " + ((User) ParseUser.getCurrentUser()).getLastName();
nameSB.append(name);
nameSB.setCharAt(0, Character.toUpperCase(nameSB.charAt(0)));
name = nameSB.toString();
} catch (NullPointerException npe) {
}
I'm trying to parse some XML to a string and I'm getting an outofbounds exception. I'm fairly new to android as well as trying to get text from a website, namely the CTA Bus Tracker API . One block of the XML looks like this:
<route>
<rt>1</rt>
<rtnm>Bronzeville/Union Station</rtnm>
</route>
This is my method:
class loadRoutes extends AsyncTask<String, String, String[]> {
#Override
protected String[] doInBackground(String... strings) {
try {
URL routesURL = new URL(strings[0]);
BufferedReader in = new BufferedReader(new InputStreamReader(routesURL.openStream()));
String [] result = new String[2];
String line;
while((line = in.readLine()) != null) {
if(line.contains("<rt>")) {
int firstPos = line.indexOf("<rt>");
String tempNum = line.substring(firstPos);
tempNum = tempNum.replace("<rt>", "");
int lastPos = tempNum.indexOf("</rt>");
result[0] = tempNum.substring(0, lastPos);
in.readLine();
firstPos = line.indexOf("<rtnm>");
String tempName = line.substring(firstPos);
tempName = tempName.replace("<rtnm>", "");
lastPos = tempName.indexOf("</rtnm>");
result[1] = tempName.substring(0, lastPos);
}
}
in.close();
return result;
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
The first readline() gets to the line with an rt and grabs that line, then in the if statement, readline() should get the next line, which should contain rtnm. I keep getting indexoutofbounds on the line firstPos = line.indexOf("rtnm").
The while loop is already reading in the next line, so you don't need to in.readLine(); in the if statement. Try running it like this:
while((line = in.readLine()) != null) {
if(line.contains("<rt>")) {
int firstPos = line.indexOf("<rt>");
String tempNum = line.substring(firstPos);
tempNum = tempNum.replace("<rt>", "");
int lastPos = tempNum.indexOf("</rt>");
result[0] = tempNum.substring(0, lastPos);
} else if (line.contains("<rtnm>") {
firstPos = line.indexOf("<rtnm>");
String tempName = line.substring(firstPos);
tempName = tempName.replace("<rtnm>", "");
lastPos = tempName.indexOf("</rtnm>");
result[1] = tempName.substring(0, lastPos);
}
}
Also, it might be easier to write your own XML parser in a different class. This XML parser android documentation has an example of exactly what you are trying to do.
this is the example text int text file
title: get this string and
desc: get this string
I want to split it with "title:" and "desc:"
it is simple :
after getting file content (https://stackoverflow.com/a/14768380/1725748), do :
String mystring= "title: xxxxxx desc: yyyyy";
String[] splits = mystring.split("title:|desc:");
splits[0] // is the title
splits[1] // is the description
There are various ways to get a String how you like, here I found the index of desc and split the String where desc appears:
try{
InputStream inputStream = getResources().openRawResource(R.raw.textfile);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
String title_content, desc_content;
// Read each line
while((line = reader.readLine( )) != null)
{
// title: get this string and desc: get this string
// ^
// (desc_location)
int desc_location;
if((desc_location = line.indexOf("desc:")) > 0)
{
title_content = line.substring(0, desc_location);
desc_content = line.substring(desc_location, line.length( ));
}
}
} catch (Exception e) {
// e.printStackTrace();
}
I have an html file in assets, aaa.html.
I want to read the contents of html file and replace it from another string.
Is this way is right or is there any other option.
my code:
File f = new File("file:///android_asset/aaa.html");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
But its giving file not found, where as loading in web view loads the file.
InputStream is = getAssets().open("aaa.html");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String str = new String(buffer);
str = str.replace("old string", "new string");
If you want to load file in webview then use this
mWebView.loadUrl("file:///android_asset/myfile.html");
you want to replace content inside Html file tags so the solution class code is here..
public class CardDetail {
public static String newHtmlString = "";
// private Context context;
#SuppressWarnings("rawtypes")
public String getNewHtmlString(String htmlString, HashMap hm) {
try {
StringTokenizer st = new StringTokenizer(htmlString, "##");
CardDetail.newHtmlString = "";
while (st.hasMoreTokens()) {
String token = st.nextToken();
CardDetail.newHtmlString += token;
if (st.hasMoreTokens()) {
String token2 = st.nextToken();
if (token2.equals("NAME") || token2.equals("POSITION") || token2.equals("COMPANY") || token2.equals("PHOTOURL"))
CardDetail.newHtmlString += hm.get(token2);
if (token2.equals("SKYPE_CONTAINER1")
|| token2.equals("TWITTER_CONTAINER1")
|| token2.equals("PHONENUMBER_CONTAINER1")
|| token2.equals("EMAIL_CONTAINER1")
|| token2.equals("ADDRESS_CONTAINER1")) {
String replaceString = st.nextToken();
String tokenMiddle = (String) hm.get(st.nextToken());
if (!tokenMiddle.equals("")) {
replaceString += tokenMiddle;
CardDetail.newHtmlString += replaceString + st.nextToken();
st.nextElement();
} else {
st.nextElement();
st.nextElement();
}
}
}
}
// Log.i("convertedHTMLString", newHtmlString);
return CardDetail.newHtmlString;
// htmlString = "<img src='" + hm.get("PHOTOURL") + "' width=80 height=80>";
// return htmlString;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
#SuppressWarnings("unchecked")
public HashMap<?, ?> getProfileHashMap(JSONObject jsonObject) {
#SuppressWarnings("rawtypes")
HashMap hm = new HashMap();
jsonObject = (new JSONConverterClass()).convertJsonObjectToCardDetail(jsonObject);
try {
hm.put("EMAIL", jsonObject.getString("email"));
hm.put("NAME", jsonObject.getString("firstname") + " " + jsonObject.getString("lastname"));
hm.put("COMPANY", jsonObject.getString("company_name"));
hm.put("POSITION", jsonObject.getString("position"));
hm.put("WEBSITE", jsonObject.getString("website"));
hm.put("PHONENUMBER", jsonObject.getString("phonenumber"));
hm.put("PHOTOURL", jsonObject.getString("picture_url"));
hm.put("SKYPE", jsonObject.getString("skype_username"));
hm.put("TWITTER", jsonObject.getString("twitter_username"));
hm.put("ADDRESS", jsonObject.getString("generic_location"));
} catch (Exception e) {
e.printStackTrace();
}
return hm;
}
}
convertJsonObjectToCardDetail this class just replace string with values from Json
hope this solves your problem ....