I am trying to get the host and IP address from a URL. This URL is given by a text field, when the button is clicked a want the given text to be stored in a string, and I want to convert that string to a URL. This is my code:
String value;
String ip;
URL url;
public void btnOnClick(View v){
EditText text = (EditText)findViewById(R.id.txtWebsite);
value = "http://" + text.getText().toString();
TextView output = (TextView)findViewById(R.id.txtViewOutput);
if (value.length() < 3){
output.setText("At least 3 characters are required ");
}else{
try {
url = new URL(value);
//Here is where I get my error: (look below for the given error)
InetAddress address = InetAddress.getByName(new URL(***url***).getHost());
ip = address.getHostAddress();
}catch (MalformedURLException e){
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
The error:
http://oi60.tinypic.com/b6vpxy.jpg
So it seems to me that it doesn't convert the string to a URL, and I don't know how I can fix this. If someone could point me in the right direction and tell me what I do wrong, I would appreciate it.
The variable url is already of type URL. no need to do new URL(url), just do this instead:
InetAddress address = InetAddress.getByName(url.getHost());
you can use this to parse url from string:
ArrayList retrieveLinks(String text) {
ArrayList links = new ArrayList();
String regex = "\\(?\\b(http://|www[.])[-A-Za-z0-9+&##/%?=~_()|!:,.;]*[-A-Za-z0-9+&##/%=~_()|]";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(text);
while(m.find()) {
String urlStr = m.group();
char[] stringArray1 = urlStr.toCharArray();
if (urlStr.startsWith("(") && urlStr.endsWith(")"))
{
char[] stringArray = urlStr.toCharArray();
char[] newArray = new char[stringArray.length-2];
System.arraycopy(stringArray, 1, newArray, 0, stringArray.length-2);
urlStr = new String(newArray);
System.out.println("Finally Url ="+newArray.toString());
}
System.out.println("...Url..."+urlStr);
links.add(urlStr);
}
return links;
}
hope this helps.
Related
I want to set all my hashtags in lowercase in a string:
"Hello I'm a men #Athlete et I'm going to do sport #NeverGiveUp"
Should become:
"Hello I'm a men #athlete et I'm going to
do sport #nevergiveup"
if your problem is how to convert all to simple letters hope this helps
String myString = "HashTag";
String myNewSimpleLetterString = myString.substring(0,5).toLowerCase(); //subString will get the characters from 0 - 5
Try this code
Just pass your string to this method this method returns formatted String
public static String changeFormat(String beforeFormatStr) {
String[] arrStr = beforeFormatStr.split(" ");
String afterFormatStr = "";
int wordPos = 0;
for (String word : arrStr) {
String changeStr = word;
if (word.contains("#")) {
changeStr = word.toLowerCase();
}
if (wordPos == 0) {
afterFormatStr += changeStr;
} else {
afterFormatStr += " " + changeStr;
}
wordPos++;
}
return afterFormatStr;
}
You can use Regular expression for finding and replacing hashtags to lowercase. Like :
String line = "Hello I'm a men #Athlete et I'm going to do sport #NeverGiveUp";
String regEx = "\\S*#(?:\\[[^\\]]+\\]|\\S+)"; //Regular expression for matching hashtag
StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(line);
while (m.find())
{
// Avoids throwing a NullPointerException in the case that you
// Don't have a replacement defined in the map for the match
String repString = m.group();
if (repString != null)
repString = repString.toLowerCase();
m.appendReplacement(sb, repString);
}
m.appendTail(sb);
String replacedHashtag = sb.toString();
Hash is not a string, so you have to use Regx matcher and Pattern to achieve this.
List<String> obtained_hashwords = new ArrayList<>();
String text_data = "Hello I'm a men #Athlete et I'm going to do sport #NeverGiveUp and I want to format this string";
Pattern pattern = Pattern.compile("#\\w+");
Matcher matcher = pattern.matcher(text_data);
while (matcher.find())
{
obtained_hashwords.add(matcher.group());
Log.d("Hash word",matcher.group());
}
for (String obtained_hashword:obtained_hashwords)
{
String no_hash = obtained_hashword.replace("#","");
String lower_case_word = "#"+no_hash.toLowerCase();
text_data = text_data.replace(obtained_hashword,lower_case_word);
}
Log.d("changed line",text_data);
I have a TextView with autoLink set as
<TextView
android:id="#+id/messageDetail_privateText_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="web|phone|email" />
But when I set a text with an url like http://www.test.com?p1=v1&p2=v2 the TextView's autolink doesn't recognize the query parameters after the domain.
I can understand that this kind of URL's doesn't have too much sense, but is there any workaround to this problem?
iOS is recognizing the parameters just fine.
Answering to my own question, what finally worked for me was to check the urls of the string and adding the slash manually. Not the coolest solution in the world but worked in this case.
Below the code:
protected String normalizeURLs(String html)
{
String[] pieces = html.split(" ");
ArrayList<String> textParts = new ArrayList<>();
for(String piece : pieces) {
try {
URL isURL = new URL(piece);
String protocol = isURL.getProtocol();
String host = isURL.getHost();
String query = isURL.getQuery();
String path = isURL.getPath();
String questionMark = "?";
if (path.equals("")) {
path = "/";
}
if (query == null) {
query = "";
questionMark = "";
}
String url = protocol + "://" + host + path + questionMark + query;
textParts.add(url);
} catch (MalformedURLException exception) {
textParts.add(piece);
}
}
String resultString = "";
for (String s : textParts)
{
resultString += s + " ";
}
return resultString;
}
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();
}
}
I am learning android from Udacity's course on developing Android apps.
In that they show us how to develop weather app, but I am stuck in the code where we add the code for changing the temperature units.
My question is why can't i use getActivity() method in following code:
Its in the first line of the very first function.
class FetchWeatherTask extends AsyncTask<String ,Void,String []>
{
public String formatHighLows(double high, double low) {
SharedPreferences sharedPrefs=PreferenceManager.getDefaultSharedPreferences(getActivity());
String unitType=sharedPrefs.getString(getString(R.string.pref_units_key),getString(R.string.pref_units_metric));
if(unitType.equals(getString(R.string.pref_units_imperial)))
{
high=(high*1.8)+32;
low=(low*1.8)+32;
}
else if(!unitType.equals(getString(R.string.pref_units_metric)))
{
Toast.makeText(getActivity(),"invalid unit",Toast.LENGTH_SHORT).show();
}
long roundedHigh = Math.round(high);
long roundedLow = Math.round(low);
String str= roundedHigh+"/"+roundedLow;
return str;
}
#Override
protected String [] doInBackground(String []params)
{ HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
String format="json";
String units="metric";
int numDays=7;
try {
final String FORECAST_BASE_URL="http://api.openweathermap.org/data/2.5/forecast/daily?";
final String QUERY_PARAM="q";
final String FORMAT_PARAM="mode";
final String UNITS_PARAM="units";
final String DAYS_PARAM="cnt";
Uri builtUri=Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM,params[0])
.appendQueryParameter(FORMAT_PARAM,format)
.appendQueryParameter(UNITS_PARAM,units)
.appendQueryParameter(DAYS_PARAM,Integer.toString(numDays))
.build();
URL url = new URL(builtUri.toString());
http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
} catch (IOException e) {
Log.e("PlaceholderFragment", "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PlaceholderFragment", "Error closing stream", e);
}
}
}
try
{
return getWeatherDataFromJson(forecastJsonStr,numDays);
}
catch(JSONException e)
{
}
return null;
}
protected void onPostExecute(String[] result) {
/*RECEIVES THE STRING ARRAY FROM THE DOINBACKGROUND METHOD. THE RESULT IS BY DEFAULT RETURNED TO THE ONPOST EXECUTE
* AND WE CAN ACCESS THE ARRAYLIST OF WEATHER WHICH POPULATES THE LISTVIEW BECAUSE WE HAVE MADE THAT STATIC.*/
if (result != null) {
MainActivityFragment.weather_adapter.clear();
for(String dayForecastStr : result) {
MainActivityFragment.weather_adapter.add(dayForecastStr);
}
// New data is back from the server. Hooray!
}
}
private String getReadableDateString(long time){
// Because the API returns a unix timestamp (measured in seconds),
// it must be converted to milliseconds in order to be converted to valid date.
SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
return shortenedDateFormat.format(time);
}
/**
* Prepare the weather high/lows for presentation.
*/
/**
* Take the String representing the complete forecast in JSON Format and
* pull out the data we need to construct the Strings needed for the wireframes.
*
* Fortunately parsing is easy: constructor takes the JSON string and converts it
* into an Object hierarchy for us.
*/
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays)
throws JSONException
{
// These are the names of the JSON objects that need to be extracted.
final String OWM_LIST = "list";/*it will contain the weather data for seven days, it is an array*/
/*every element of the list has a one element long array called weather which contains weather details of corresponding
day.
*/
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "max";
final String OWM_MIN = "min";
final String OWM_DESCRIPTION = "main";/*this will contain the weather description main title like clear
/*The json object is created from the string which contains data in json format*/
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
// OWM returns daily forecasts based upon the local time of the city that is being
// asked for, which means that we need to know the GMT offset to translate this data
// properly.
// Since this data is also sent in-order and the first day is always the
// current day, we're going to take advantage of that to get a nice
// normalized UTC date for all of our weather.
// We are doing this because we have to associate date with each forecast entry.
Time dayTime = new Time();
dayTime.setToNow();
// we start at the day returned by local time. Otherwise this is a mess.
// julian day returns the number of days that have passed since the julian period.
int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);
// now we work exclusively in UTC
dayTime = new Time();
String[] resultStrs = new String[numDays];
for(int i = 0; i < weatherArray.length(); i++) {
// For now, using the format "Day, description, hi/low"
String day;
String description;
String highAndLow;
// Get the JSON object representing the day
JSONObject dayForecast = weatherArray.getJSONObject(i);
// The date/time is returned as a long. We need to convert that
// into something human-readable, since most people won't read "1400356800" as
// "this saturday".
long dateTime;
// Cheating to convert this to UTC time, which is what we want anyhow
dateTime = dayTime.setJulianDay(julianStartDay+i);
day = getReadableDateString(dateTime);
// description is in a child array called "weather", which is 1 element long.it contains the description of the
/*weather for the corresponding day in the form of string*/
/*weatherObject is the corresponding object of the ith day*/
JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
/*OWM_DESCRIPTION contains the "main" description like clear*/
description = weatherObject.getString(OWM_DESCRIPTION);
// Temperatures are in a child object called "temp".It contains the max and min temperatures
// in double format with the keys mentioned OWM_MAX and OWM_MIN Try not to name variables
// "temp" when working with temperature. It confuses everybody.
JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
double high = temperatureObject.getDouble(OWM_MAX);
double low = temperatureObject.getDouble(OWM_MIN);
resultStrs[i] = day + " - " + description + " - " +Math.round(high)+" / "+Math.round(low);
}
return resultStrs;
}
}
Get Context and save in member variable of this class :
class FetchWeatherTask extends AsyncTask<String ,Void,String []> {
private Context mContext;
public FetchWeatherTask(Context context) {
this.mContext = context;
}
// use context as this.mContext everywhere you want
}
You should call above class using :
new FetchWeatherTask(context).execute(/* String parameters */);
You are inside a AsyncTask which which does not recognize getActivity(). Try to define a context at the top level activity. in onCreate() :
context = this.
Then inside AsyncTask you can use
context.getActivity();
class FetchWeatherTask extends AsyncTask<String ,Void,String>
{
private Context mContext;
String str1, str2, str3;
String finalStr="";
public FetchWeatherTask(Context context)
{ this.mContext = context;}
#Override
protected String doInBackground(String... params)
{
str1 = params[0];
str2 = params[1];
str3 = params[2];
finalStr = str1 + str2 + str3;
return finalStr;
}
#Override
protected void onPostExecute(String result) {
Log.d("rs", result);
}
}
And in your activity:
new FetchWeatherTask(this).execute(new String[]{"a", "b","c"});
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 ....