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.
I want to take currency from specific Url but AsyncTask is giving me runtime error: I couldn't find what I have to do.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebServisXML xmlRead = new WebServisXML(this);
xmlRead.execute("http://www.tcmb.gov.tr/kurlar/today.xml");
}
public class WebServisXML extends AsyncTask<String, String, List<String>> {
private Context context;
private ListView listView;
private ProgressDialog dialogBar;
List<String> dovizListe = new ArrayList<String>();
HttpURLConnection baglanti = null;
public WebServisXML(Context context) {
this.context = context;
listView = (ListView) ((AppCompatActivity) context).findViewById(R.id.listView);}
protected void onPreExecute() {
super.onPreExecute();
dialogBar = ProgressDialog.show(context, "Lütfen bekleyiniz...", "İşlem yükleniyor...", true);
}
#Override
protected List<String> doInBackground(String... params) {
try {
URL adressOfLink = new URL(params[0]);
baglanti = (HttpURLConnection) adressOfLink.openConnection();
int responceCode = baglanti.getResponseCode();
if (responceCode == HttpURLConnection.HTTP_OK) {
BufferedInputStream stream = new BufferedInputStream(baglanti.getInputStream());
publishProgress("Döviz kurları okunuyor...");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(stream);
NodeList dovizNodeList = document.getElementsByTagName("Currency");
for (int i = 0; i < dovizNodeList.getLength(); i++) {
Element element = (Element) dovizNodeList.item(i);
NodeList nodeBirim = element.getElementsByTagName("Unit");
NodeList nodeIsim = element.getElementsByTagName("Isim");
NodeList nodeAlis = element.getElementsByTagName("ForexBuying");
NodeList nodeSatis = element.getElementsByTagName("ForexSelling");
String birim = nodeBirim.item(0).getFirstChild().getNodeValue();
String isim = nodeIsim.item(0).getFirstChild().getNodeValue();
String alis = nodeAlis.item(0).getFirstChild().getNodeValue();
String satis = nodeSatis.item(0).getFirstChild().getNodeValue();
dovizListe.add(birim + " " + isim + " Alış:" + alis + " Satış:" + satis);
}
publishProgress("Liste güncelleniyor...");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}finally {
if(baglanti!=null)
baglanti.disconnect();
}
return dovizListe;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
dialogBar.setMessage(values[0]);
}
#Override
protected void onPostExecute(List<String> strings) {
super.onPostExecute(strings);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(context,android.R.layout.simple_expandable_list_item_1,strings);
listView.setAdapter(arrayAdapter);
dialogBar.cancel();
}
}}
This is my error screen:
One of the nodes first child's is null. (Node has no children)
Without proper line numbers I cannot tell you which one. (Line 98 of MainActivity.java)
I suggest adding a check:
String birim = nodeBirim.item(0).getLength() > 0 ? nodeBirim.item(0).getFirstChild().getNodeValue() : "";
String isim = nodeIsim.item(0).getLength() > 0 ? nodeIsim.item(0).getFirstChild().getNodeValue() : "";
String alis = nodeAlis.item(0).getLength() > 0 ? nodeAlis.item(0).getFirstChild().getNodeValue() : "";
String satis = nodeSatis.item(0).getLength() > 0 ? nodeSatis.item(0).getFirstChild().getNodeValue() : "";
I have an xml parser class which crashes if I'm not connected to the internet. Is there anyway that I can get the class to go to a layout that says, "no connection" or something similar when a connection is not present. thanks
Xml Parser
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
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;
}
/**
* Getting XML DOM element
* #param XML string
* */
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;
}
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));
}
}
Activity that uses parser
public class CustomizedListView extends Fragment { // All static variables
static final String URL = "http://graffiti.hostoi.com/00Graffiti00/lists/00main00.xml";
// XML node keys
static final String KEY_SONG = "song"; // parent node
static final String KEY_ID = "id";
static final String KEY_ARTIST = "artist";
static final String KEY_DURATION = "duration";
static final String KEY_THUMB_URL = "thumb_url";
static final String KEY_LINK = "key";
ListView list;
LazyAdapter adapter;
ArrayList<HashMap<String, String>> songsList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.news, container, false);
songsList = new ArrayList<HashMap<String, String>>();
list=(ListView) rootView.findViewById(R.id.list);
new RetrieveXML().execute(URL);
XMLParser parser = new XMLParser();
// Getting adapter by passing xml data ArrayList
// Click event for single list row
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(getActivity(), Article.class);
new Bundle();
intent.putExtra( "b", songsList.get(position).get(KEY_LINK));
startActivity(intent);
}
});
return rootView;
}
class RetrieveXML extends AsyncTask<String, Void, String> {
private Exception exception;
XMLParser parser = new XMLParser();
protected String doInBackground(String... urls) {
try {
return parser.getXmlFromUrl(urls[0]);
} catch (Exception e) {
this.exception = e;
return null;
}
}
protected void onPostExecute(String xml) {
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_SONG);
// looping through all song nodes <song>
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_ID, parser.getValue(e, KEY_ID));
map.put(KEY_LINK, parser.getValue(e, KEY_LINK));
map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_ID));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
// adding HashList to ArrayList
songsList.add(map);
}
adapter=new LazyAdapter(getActivity(), songsList);
list.setAdapter(adapter);
}
}
Try this..
Add the below class in your package
Utils.java
import android.content.Context;
import android.net.ConnectivityManager;
import android.util.Log;
public class Utils {
public static boolean connectivity(Context c) {
if(c != null)
{
ConnectivityManager connec = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isConnected()||mobile.isConnected())
return true;
else if (wifi.isConnected() && mobile.isConnected())
return true;
else
return false;
} catch (NullPointerException e) {
Log.d("ConStatus", "No Active Connection");
return false;
}
}
else
{
Log.v("utils--", "null");
return false;
}
}
}
And before calling that RetrieveXML AsyncTask use like below code.
if(Utils.connectivity(getActivity()))
{
new RetrieveXML().execute(URL);
XMLParser parser = new XMLParser();
}
else
{
Toast.makeText(getActivity(), "Please connect to working internet connection.", Toast.LENGTH_SHORT).show();
}
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.
I'm trying to figure out why my inputstream isn't working correctly. I am trying to connect to a server and get a JSON string and save it into the variable inputJSON. However inputJOSN is empty because my inputstream isn't working correctly. This line of code:
inputJSON = ConvertByteArrayToString(getBytesFromInputStream(inputStr));
doesn't seem to be working properly and I'm not sure why?
public class AndroidClient extends ProfileActivity {
private TextView textIn;
public Thread rt;
public Socket socket = null;
public PrintWriter outputstrwr;
public OutputStream out = null;
public DataOutputStream dataOutputStream = null;
public DataInputStream dataInputStream = null;
public InputStream inputStr = null;
private final static String LOG_TAG = AndroidClient.class.getSimpleName();
private final Handler handler = new Handler();
private List<Profile> serviceInfoList = new ArrayList<Profile>();
// Map between list position and profile
private Map<Integer, Profile> posMap = new HashMap<Integer, Profile>();
private Map<String, Integer> addressMap = new HashMap<String, Integer>();
private static String profilePicBase64Str="";
private String inputJSON = "";
private String outputJSON = "";
private String outputJSONserv = "";
private Profile p;
//String urlInputStream = "";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.e(LOG_TAG, "Before OnCreate() Try");
try {
Log.e(LOG_TAG, "In OnCreate() Try");
socket = new Socket("23.23.175.213", 9000); //Port 1337
Log.e(LOG_TAG, "Created Socket");
dataOutputStream = new DataOutputStream(socket.getOutputStream());
Log.e(LOG_TAG, "Created DataOutputStream");
dataInputStream = new DataInputStream(socket.getInputStream());
Log.e(LOG_TAG, "Created DataInputStream");
//out = new OutputStream();
out = socket.getOutputStream();
inputStr = socket.getInputStream();
//Thread readjsonthrd = new Thread(new ReadJSONThread());
//inputstrrd = new InputStreamReader(socket.getInputStream());
p = new Profile();
Log.e(LOG_TAG, "Created Profile Instance");
//Gets the local profile via JSON and converts into Profile type
Gson gson = new Gson();
Log.e(LOG_TAG, "Created Gson Instance" + "GetProfileJSONStr:" + p.getProfileJSONStr());
p = gson.fromJson(p.getProfileJSONStr(), Profile.class);
setProfile(p);
Log.e(LOG_TAG, "Converted Profile to JSON");
//Gson gson = new Gson();
Log.e(LOG_TAG, "Before: outputJSON = gson.toJson(p);");
outputJSON = gson.toJson(p).toString();
outputJSON = removeExcessStr(outputJSON);
Log.e(LOG_TAG, "ProfilePicStr Base64:"+p.getProfilePicStr());
outputJSON = outputJSON.replace("Name","name");
outputJSON = outputJSON.replace("TagLine","message");
outputJSON = outputJSON.replace("Title","title");
outputJSON = outputJSON.replace("Company", "company");
outputJSON = outputJSON.replace("Industry","industry");
outputJSON = outputJSON.replace("WhatIDo","whatido");
outputJSON = outputJSON.replace("WhoDoIWantToMeet","meetwho");
outputJSON = outputJSON.replace("WHOOZNEAR_PROFILEPIC","photo");
outputJSON = outputJSON.replaceAll("[c][o][n][t][e][n][t][:][/][/][a-zA-Z0-9]+[/][a-zA-Z0-9]+[/][a-zA-Z0-9]+[/][a-zA-Z0-9]+[/][a-zA-Z0-9]+", getPicBase64Str()); /*"helloworld2"*/
if (!outputJSON.contains(",\"photo\":")) {
outputJSON = outputJSON.replace("}",",\"photo\":"+"\"IconnexUs\"}");
outputJSON = outputJSON.replace("}",",\"photo\":"+"\""+getPicBase64Str()+"\"}");
outputJSON = outputJSON.replace("}",",\"status\":\"enabled\"}");
}
else {
outputJSON = outputJSON.replace("}",",\"status\":\"enabled\"");
}
outputJSONserv = "{\"to\":\"broadcast\",\"type\":\"1\",\"payload\":"+outputJSON+"}";
Log.e(LOG_TAG, "Created outputJSON:" + outputJSON);
Log.e(LOG_TAG, "Created outputJSON Server:" + outputJSONserv);
JSONObject outObject = new JSONObject();
try {
outObject.put("photo", "hello");
outObject.put("type", "50");
outObject.put("payload", outputJSON);
outputJSON = gson.toJson(outObject).toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e(LOG_TAG, "Value of PROFILEPIC STRING FROM PROFILEMAP: "+profileMap.get("WHOOZNEAR_PROFILEPIC"));
p.setProfilePicStr(ConvertandSetImagetoBase64(profileMap.get("WHOOZNEAR_PROFILEPIC")));
//String headerJSON = gson.toJson(outObject).toString();
outputJSON = outputJSON.substring(nthOccurrence(outputJSON, '{', 2)-1, nthOccurrence(outputJSON, '}', 1)-1);
String input = "["+"Ryan"+"[";
//"[foo".replaceAll(Pattern.quote("["), "\"");
String result = input.replaceAll(Pattern.quote("["), "\"");
Log.e(LOG_TAG, "REGEX REPLACEALL:"+result);
outputstrwr = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
outputstrwr.write(outputJSONserv);
Log.e(LOG_TAG, "Base64 String:"+p.getProfilePicStr());
Log.e(LOG_TAG, "Sent dataOutputStream");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e(LOG_TAG, "Before initEventHandlers");
initEventHandlers();
Log.e(LOG_TAG, "After initEventHandlers");
//refreshViewModels();
Log.e(LOG_TAG, "Start Repeat Thread");
rt = new Thread(new RepeatingThread());
rt.start();
Log.e(LOG_TAG, "Started Repeat Thread");
}
#Override
public void onDestroy() {
super.onDestroy();
rt.stop();
try {
socket.close();
dataOutputStream.close();
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onPause(){
super.onPause();
rt.stop();
}
#Override
public void onResume(){
super.onResume();
if (rt.isAlive() == false) {
//rt.start();
}
}
#Override
public void onStop(){
super.onStop();
rt.stop();
try {
socket.close();
dataOutputStream.close();
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String removeExcessStr(String json_excess) {
//String myString = myString.replace("=\"ppshein\"", "");
String json_excess1 = json_excess.replace("\"nameValues\":{", "");
String myString = json_excess1.replace(",\"profileId\":1,\"valid\":false}", "");
return myString;
}
public static String adddblquotattr(String attr) {
String result = attr.replaceAll(Pattern.quote("["), "\"");
return result;
}
public static String adddblquotval(String val) {
String result = val.replaceAll(Pattern.quote("["), "\"");
return result;
}
public static int nthOccurrence(String str, char c, int n) {
int pos = str.indexOf(c, 0);
while (n-- > 0 && pos != -1)
pos = str.indexOf(c, pos+1);
return pos;
}
public void setPicBase64Str(String profilePicBase64Str) {
this.profilePicBase64Str = profilePicBase64Str;
}
public String getPicBase64Str() {
return profilePicBase64Str;
}
public String ConvertandSetImagetoBase64(String imagePath) {
String base64 = null;
byte[] input = null;
try{
FileInputStream fd = new FileInputStream(imagePath);
Bitmap bmt = BitmapFactory.decodeFileDescriptor(fd.getFD());
try{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap tmp = ProfileActivity.scaleDownBitmap(bmt, 10, this);
tmp.compress(Bitmap.CompressFormat.JPEG, 10, stream);
input = stream.toByteArray();
base64 = Base64.encodeToString(input, Base64.DEFAULT);
//LocalProfileActivity.input = input;
}catch(Exception e){
Log.e(LOG_TAG,"[ONACTIVITYRESULT] Could not bind input to the bytearray: " + e.getMessage());
}
}
catch (Exception e){
Log.e("LocalProfile", "ConvertandSetImagetoBase64: Could not load selected profile image");
}
return base64;
}
public String getStringFromBuffer(InputStreamReader inputstrread){
BufferedReader bRead = new BufferedReader(inputstrread);
String line = null;
StringBuffer jsonText = new StringBuffer();
try {
while((line=bRead.readLine())!=null){
jsonText.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonText.toString();
}
public String ConvertByteArrayToString(byte[] b) {
// byte[] to string
String input = new String(b);
return input;
}
public byte[] ConvertStringToByteArray(String str) {
// string to byte[]
byte[] bytes = str.getBytes();
return bytes;
}
public static byte[] getBytesFromInputStream(InputStream is)
throws IOException {
// Get the size of the file
long length = is.available();
if (length > Integer.MAX_VALUE) {
// File is too large
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int) length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely stream ");
}
// Close the input stream and return bytes
is.close();
return bytes;
}
public static String writeFile(Bitmap finalBitmap) {
String filePath = "";
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream outFile = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, outFile);
outFile.flush();
outFile.close();
} catch (Exception e) {
e.printStackTrace();
}
filePath = root+"/saved_images/"+fname;
return filePath;
}
public class RepeatingThread implements Runnable {
private final Handler mHandler = new Handler();
private int len = 0;
private byte[] input = new byte[len];
public RepeatingThread() {
//try {
Log.e(LOG_TAG, "Before inputJSON String");
//inputJSON = dataInputStream.readUTF();
//URL url = new URL("tcp://23.23.175.213:1337");
//inputJSON = dataInputStream.readUTF();
//inputstrrd = new InputStreamReader(socket.getInputStream());
String hello = "hello world";
//String inputJSON = getStringFromBuffer(new InputStreamReader(socket.getInputStream()));
//Convert
Log.e(LOG_TAG, "After inputJSON String:" + inputJSON);
/*}
catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
//LOOK HERE FIRST
//inputJSON is what is received back from the server - Take the inputJSON
//String and use regular expressions HERE to remove all the other characters in the
//string except the payload JSON.
//refreshViewModels(inputJSON);
}
#Override
public void run() {
try {
//outputstrwr.write(outputJSONserv); //UNCOMMENT IF NEED TO SEND DATA TO GET JSON BACK
inputJSON = ConvertByteArrayToString(getBytesFromInputStream(inputStr));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e(LOG_TAG, "IN REPEATINGTHREAD-INPUTJSON:" + inputJSON);
refreshViewModels(inputJSON);
mHandler.postDelayed(this, 3000);
}
}
public void refreshViewModels(String inputJSON) {
try {
ListView servicesListView = (ListView) this
.findViewById(R.id.profilesListView);
String[] from = new String[] { "profilePic", "neighborName",
"tagLine" };
int[] to = new int[] { R.id.avatar, R.id.username, R.id.email };
// prepare the list of all records
List<HashMap<String, Object>> fillMaps = new ArrayList<HashMap<String, Object>>();
List<Profile> profiles = new ArrayList<Profile>();
// Clear the position mapping list and reset it
this.posMap.clear();
Log.i(LOG_TAG, "NEW inputJSON: " + inputJSON);
inputJSON = getPayloadStr(inputJSON);
Log.i(LOG_TAG, "NEW inputJSON2: " + inputJSON);
JSONArray profileArray = new JSONArray(inputJSON);
for (int i=0; i<profileArray.length(); i++) {
JSONObject jsonObject = profileArray.getJSONObject(i);
Gson gson = new Gson();
Profile p = gson.fromJson(gson.toJson(jsonObject).toString(), Profile.class);
profiles.add(p);
}
int pos = 0;
// Creates the fillMaps list for the listAdapter
Log.i(LOG_TAG, "Profiles size: " + profiles.size());
//showToast("Profiles size: " + profiles.size());
for (Profile p : profiles) {
// Create mapping for list adapter
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("profilePic",
p.getAttributeValue("photo")== null? "Not Set" : p
.getAttributeValue("photo"));
map.put("neighborName",
p.getAttributeValue("Name") == null? "Not Set" : p
.getAttributeValue("Name"));
map.put("tagLine",
p.getAttributeValue("TagLine") == null? "Not Set" : p
.getAttributeValue("TagLine"));
fillMaps.add(map);
// Reset the postion mapping
this.posMap.put(pos++, p);
}
ListAdapter servicesListAdapter = new myAdapter(this, fillMaps,
R.layout.listitem, from, to);
servicesListView.setAdapter(servicesListAdapter);
} catch (Exception e) {
Log.e(LOG_TAG, "Error making list adapter: " + e.getMessage());
}
}
public String getPayloadStr(String profileString) {
Log.e("LOG_TAG", "Profile Str:"+profileString);
Pattern pattern = Pattern.compile(".*?payload\":(.*)\\}");
Log.e("LOG_TAG", "I got here 1");
Matcher matcher = pattern.matcher(profileString);
Log.e("LOG_TAG", "I got here 12");
//Matcher m = responseCodePattern.matcher(firstHeader);
matcher.matches();
matcher.groupCount();
//matcher.group(0);
Log.e("LOG_TAG", "I got here 2"+matcher.group(1));
return matcher.group(1);
}
private class myAdapter extends SimpleAdapter {
public myAdapter(Context context, List<? extends Map<String, ?>> data,
int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.listitem,
null);
}
HashMap<String, Object> data = (HashMap<String, Object>) getItem(position);
((TextView) convertView.findViewById(R.id.username))
.setText((String) data.get("neighborName"));
((TextView) convertView.findViewById(R.id.email))
.setText((String) data.get("tagLine"));
// Convert a string representing an image back to an image
String base64 = ((String)data.get("profilePic"));
byte[] picBytes = Base64.decode(base64, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(picBytes, 0, picBytes.length);
//THE IF AND THE ELSE NEED TO BE SWITCHED
if (bitmap==null){
((ImageView) convertView.findViewById(R.id.avatar)).setImageResource(R.drawable.btn_whooznear);
}else{
((ImageView) convertView.findViewById(R.id.avatar)).setImageBitmap(bitmap);
}
return convertView;
}
}
public void callProfileActivity(int position)
{
// Catch the case when service info is empty
if(serviceInfoList.size()==0){
return;
}
Profile profClick = posMap.get(position);
String b64Str = profClick.getAttributeValue("photo");
Intent startViewActivity = new Intent();
startViewActivity.putExtra("TransProfile", (Profile)posMap.get(position));
startViewActivity.putExtra("PhotoBase64", b64Str);
if(serviceInfoList.size()>position){
//DO SOMETHING HERE
}else{
Log.e(LOG_TAG,"Profile doesn't exist in sevice infoList? Selecting first one");
}
startViewActivity.setClass(this, ViewProfileActivity.class);
startActivity(startViewActivity);
}
/**
* Initialize the event handlers
*/
public void initEventHandlers() {
// Service List View
ListView servicesListView = (ListView) this
.findViewById(R.id.profilesListView);
servicesListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v,
int position, long id) {
Profile clickedProfile = posMap.get(position);
//showToast("Clicked Pos: " + position);
/*Intent intent = new Intent(ConnectActivity.this, ViewProfileActivity.class);
intent.putExtra("ClickProfile", posMap.get(position));*/
callProfileActivity(position);
}
});
}
/*#Override
public void onBackPressed() { // do something on back.
super.onBackPressed();
Intent myIntent = new Intent(AndroidClient.this, ProfileActivity.class);
startActivity(myIntent);
return;
}*/
}
Your code is rather long, so I cannot be sure of what exactly is the problem, but there is definitely an issue here:
public static byte[] getBytesFromInputStream(InputStream is)
throws IOException {
// Get the size of the file
long length = is.available();
If you are calling this right after sending your URL request, the server may not have had time to send the result back, so is.available() may return zero or another value less than the actual number of bytes you would hope would be available. Try code like this for reading in the file.