Parsing images from XML <enclosure> - android

I am parsing text and images from XML file.
Everyting is ok with text.
But when I start to parse images listview becomes empty.
for (int j = 0; j < clength; j++) {
Node thisNode = nchild.item(j);
String theString = null;
String nodeName = null;
if (thisNode != null && thisNode.getFirstChild() != null) {
theString = thisNode.getFirstChild().getNodeValue();
}
nodeName = thisNode.getNodeName();
if ("title".equals(nodeName)) {
_item.setTitle(theString);
}
if ("pubDate".equals(nodeName)) {
String formatedDate = theString.replace(" +0000", "");
_item.setDate(formatedDate);
}
if (nodeName.equals("enclosure")) {
Element enclosure = (Element) thisNode;
if (enclosure.hasAttr("url")) {
String imageLink = (enclosure.attr("url"));
_item.setImage(imageLink);
}
}
}
So, as I understand, the problem is taking data from .
How can I do this in wright way?
THNX!

So, i solves this task by this way.
String body = nodeToString(thisNode);
int urlStart = body.indexOf("url=");
int urlFinish = body.indexOf("length");
String urlImage = body.substring(urlStart+5, urlFinish-2);
_item.setImage(urlImage);
And method nodeToString:
private String nodeToString(Node node) {
StringWriter sw = new StringWriter();
try {
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.transform(new DOMSource(node), new StreamResult(sw));
} catch (TransformerException te) {
System.out.println("nodeToString Transformer Exception");
}
return sw.toString();
}

Related

JSONObject cannot be converted to JSONArray but after successfully tested

I getting this error: JSONObject cannot be converted to JSONArray
caused by this part of code:
private int parse() {
try {
Log.d("Jou", "result");
JSONArray ja = new JSONArray(data);
JSONObject jo = null;
titles.clear();
skills.clear();
for (int i = 0; i < ja.length(); i++) {
jo = ja.getJSONObject(i);
String id = jo.getString("ID");
String title = jo.getString("post_title");
//String content = jo.getString("post_content");
String date = jo.getString("post_date");
Skill skill = new Skill();
skill.setId(id);
skill.setTitle(title);
//skill.setContent(content);
skill.setDate(date);
skills.add(skill);
titles.add(title);
}
return 1;
} catch (JSONException e) {
Log.d("Jou", e.getMessage());
return 0;
}
Although I tried it before and it was exactly the same, then I added another string which is the date then I got the error. What could be wrong with the code?
This is the result from the server that needs to be parsed:
s = {"result":[{"post_id":"390","post_title":"Cart","post_date":‌​"2017-02-07 12:17:29"},{"post_id":"421","post_title":"Front End Developer - Digital Arts","post_date":"2017-02-07 12:18:04"},{"post_id":"431","post_title":"Art Director","post_date":"2017-02-07 12:18:19"}]}
Here is the PHP script:
<?php
$dbhost = 'localhost';
$dbuser = '';
$dbpass = '';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die ("Unable to connect") ;
if(! $conn )
{
echo 'Could not connect: ' . mysqli_error();
}
error_reporting(-1);
ini_set('display_errors', 'On');
mysqli_set_charset($conn, 'utf8');
$search ="";
if(isset($_REQUEST['query'] )){
$search = $_REQUEST['query'];
}
if($search != ""){
$sql = "SELECT ID,post_title,post_date FROM `wp_posts` WHERE post_title LIKE '%".$search."%'";
mysqli_select_db($conn,'');
$query = mysqli_query($conn, $sql ) or die ("Error: ".mysqli_error($conn));;
$result = array();
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
array_push($result,
array('post_id'=>$row['ID'],
'post_title'=>$row['post_title'],
'post_date'=>$row['post_date']
));}
echo json_encode(array("result"=>$result));
}else{
echo 'No search field has been sent';
}
?>
Try following code :
try {
Log.d("Jou", "result");
JSONObject object = new JSONObject(data)
JSONArray ja = object.getJSONArray("result");
JSONObject jo = null;
titles.clear();
skills.clear();
for (int i = 0; i < ja.length(); i++) {
jo = ja.getJSONObject(i);
String id = jo.getString("post_id");
String title = jo.getString("post_title");
//String content = jo.getString("post_content");
String date = jo.getString("post_date");
Skill skill = new Skill();
skill.setId(id);
skill.setTitle(title);
//skill.setContent(content);
skill.setDate(date);
skills.add(skill);
titles.add(title);
}
return 1;
} catch (JSONException e) {
Log.d("Jou", e.getMessage());
return 0;
}
Check with the following code. I hope it will work
private int parse(String data) {
try {
JSONObject jsonObject = new JSONObject(data); //get a response as Json Object and then get it as array by corresponding key
JSONArray ja = jsonObject.getJSONArray("result");
JSONObject jo = null;
for (int i = 0; i < ja.length(); i++) {
jo = ja.getJSONObject(i);
String id = jo.getString("ID");
String title = jo.getString("post_title");
//String content = jo.getString("post_content");
String date = jo.getString("post_date");
Skill skill = new Skill();
skill.setId(id);
skill.setTitle(title);
//skill.setContent(content);
skill.setDate(date);
skills.add(skill);
titles.add(title);
}
return 1;
} catch (JSONException e) {
Log.d("TAG", e.getMessage());
return 0;
}
}
There is some problem in your json response it is taking extra character in post_date try to validate it in the below link.
http://www.jsoneditoronline.org/

How to print a string if data is not available on server in android using json

Thank you guys.Finally i got the solution.If we want to check whether string is empty or null we must trim() the string.
String url="http://app name/Api/GetJobDetails/GetJobDetails?COMP_REQ_ID=" + title + "&StuEmail=" + e ; // this is the url
AQuery mAQuery = new AQuery(SecondActivity.this);
mAQuery.ajax(url, String.class, new AjaxCallback<String>() {
public Object dataSource;
#Override
public void callback(String url, String data, AjaxStatus status)
{
uper.callback(url, data, status);
if (null != data && status.getCode() != -101) {
String StringData = "" + data;
try {
JSONArray rootArray = new JSONArray(StringData);
int len = rootArray.length();
for (int i = 0; i < len; ++i) {
JSONObject json = rootArray.optJSONObject(i);
String Salary = json.optString("Req_From_Sal");
if (Salary == null || Salary.trim().equals("null") || Salary.trim().length() <= 0) {
b14.setText("Not Mentioned");
}
else
{
b14.setText(""+Salary);
}
}
}
}
});
Check you string if it is null or blank then print message what you want. For example:
if(StringData.length()==0){
//show message
}else{
JSONArray rootArray = new JSONArray(StringData);
int len = rootArray.length();
for (int i = 0; i < len; ++i) {
JSONObject json = rootArray.optJSONObject(i);
String Salary = json.optString("Req_From_Sal");
if (Salary == null)
b14.setText("NA"+Salary);
else
b14.setText(""+Salary)
}
}
MoreOver if you want to show specific message for specific user then ask for the success parameter. If success==1 go for you logic else if success ==0 then ask for message parameter as well parse it and show it to user
1.Check whether StringData is null or empty.
2.Check if rootArray.length()==0
Try this.
if(StringData!=null) {
JSONArray rootArray = new JSONArray(StringData);
for (int i = 0; i < rootArray.length(); ++i) {
JSONObject json = rootArray.optJSONObject(i);
String Job_Title = json.optString("Req_Title", "default_value");
String Designation = json.optString("Req_Designation_Role", "default_value");
String Salary = json.optString("Req_From_Sal", "Salary Not Mentioned");
b14.setText("" + Salary);
}
}else{
Log.d(TAG, "Invalid JSON Data");
b14.setText("Salary Not Mentioned");
}
USe TextUtils.isEmpty() to check for null and empty string.
Always add null check before getting any variable from object.
Modified code below:
JSONArray rootArray = new JSONArray(StringData);
if(rootArray!=null&&rootArray.length())
{
int len = rootArray.length();
for (int i = 0; i < len; ++i)
{
JSONObject json = rootArray.optJSONObject(i);
if (json != null) {
String Job_Title = json.optString("Req_Title");
String Designation = json.optString("Req_Designation_Role");
String Job_Type = json.optString("Req_Job_Type");
String Salary;
if (json.has("Req_From_Sal") && !TextUtils.isEmpty(json.getString("Req_From_Sal")) {
Salary = json.optString("Req_From_Sal");
} else {
Salary = "Not available";
}
b14.setText(Salary);
}
}
}
Thank you guys.Finally i got the solution. Here is edit code.To check the String is null or empty we should have to trim() the string.
Android side:-
String url="http://app name/Api/GetJobDetails/GetJobDetails?COMP_REQ_ID=" + title + "&StuEmail=" + e ; // this is the url
AQuery mAQuery = new AQuery(SecondActivity.this);
mAQuery.ajax(url, String.class, new AjaxCallback<String>() {
public Object dataSource;
#Override
public void callback(String url, String data, AjaxStatus status) {
uper.callback(url, data, status);
if (null != data && status.getCode() != -101) {
String StringData = "" + data;
try {
JSONArray rootArray = new JSONArray(StringData);
int len = rootArray.length();
for (int i = 0; i < len; ++i) {
JSONObject json = rootArray.optJSONObject(i);
String Job_Title = json.optString("Req_Title");
String Designation = json.optString("Req_Designation_Role");
String Job_Type = json.optString("Req_Job_Type");
String Salary = json.optString("Req_From_Sal");
if(Job_Title == null || Job_Title .trim().equals("null") ||Job_Title .trim().length<=0){
b1.setText("Job title not set.");
}else{
b1.setText("" +Job_Title);
}
if(Designation == null || Designation.trim().equals("null") ||Designation.trim().length() <= 0){
b3.setText("Job Designation not set.");
}else{
b3.setText("" +Designation);
}
if(Job_Type == null || Job_Type.trim().equals("null") || Job_Type.trim().length() <= 0){
b13.setText("Job Type not set.");
}else{
b13.setText("" +Job_Type);
}
if(Salary == null || Salary.trim().equals("null") || Salary.trim().length() <= 0){
b14.setText("Not yet Mentioned");
}else{
b14.setText(""+Salary);
}
}
}
}
});

how to resolve error in reading json?

Below is my json, which I am trying to read (code Log.i("callinfo", callInfo + ""); onwards, but getting error. My code to read and error message are also mentioned.
{
"CallInfo":[
{
"ItemInfo":[
{
"chargeable":"True",
"itemID":"B13984350K"
},
{
"chargeable":"True",
"itemID":"B13984351A"
}
],
"numberOfCopies":2
}
],
"ISBN":[
""
],
"TitleAvailabilityInfo":null,
"author":"Chief Army Medical Officer.",
"baseCallNumber":"RC87.1 PRE",
"publisherName":"HQ Army Medical Services,",
"title":"Preventing heat injuries : the commanders' guide",
"titleID":9206,
"yearOfPublication":"2000"
}
Code:
public void readBarCode(String response, String scannedBarcode) {
final CountDownLatch latch = new CountDownLatch(1);
final String[] names = new String[4];
JSONArray mArray, mArray1, mArray2;
int totalCount = 0;
int avail = 0;
String author, title, publisherName;
try {
JSONObject obj = new JSONObject(response);
//Results
if (obj.getJSONObject("Results") != null) {
JSONObject obj1 = obj.getJSONObject("Results");
//LookupTitleInfoResponse
if (obj1.getJSONObject("LookupTitleInfoResponse") != null) {
JSONObject obj2 = obj1.getJSONObject("LookupTitleInfoResponse");
//TitleInfo
if (obj2.getJSONArray("TitleInfo") != null) {
mArray = obj2.getJSONArray("TitleInfo");
JSONObject callInfo = mArray.getJSONObject(0);
Log.i("callinfo", callInfo + "");
mArray2 = callInfo.getJSONArray("ItemInfo");
for (int i = 0; i <= mArray2.length(); i++) {
if (mArray2.getJSONObject(i).getString("chargeable").equals("False")) {
totalCount++;
}
if (mArray2.getJSONObject(i).getString("itemID").equals(scannedBarcode)) {
avail = 1;
}
}
author = mArray.getJSONObject(0).getString("author");
publisherName = mArray.getJSONObject(0).getString("publisherName");
title = mArray.getJSONObject(0).getString("title");
TitleTxt.setText(title);
PublisherTxt.setText(publisherName);
CreatorTxt.setText(author);
BookBarcode.setText(scannedBarcode);
AvailabiltyTxt.setText(totalCount);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Getting error on below line:
mArray2 = callInfo.getJSONArray("ItemInfo");
Error:
org.json.JSONException: No value for ItemInfo
03-28 16:33:09.953 17229-17229/com.androidatc.customviewindrawer W/System.err: at org.json.JSONObject.get(JSONObject.java:389)
03-28 16:33:09.953 17229-17229/com.androidatc.customviewindrawer W/System.err: at org.json.JSONObject.getJSONArray(JSONObject.java:584)
Here we can clearly see that ItemInfo got value.
Can anyone tell me - how to resolve above error?
Many thanks in advance.
Try with below code
mArray = obj2.getJSONArray("TitleInfo");
JSONObject titleInfo = mArray.getJSONObject(0);
JSONArray arr1 = titleInfo.getJSONArray("CallInfo");
JSONObject callInfo = arr1.getJSONObject(0);
JSONArray arr2 = callInfo.getJSONArray("ItemInfo");
Log.i("ItemInfo", arr2 + "");
Here is full method
public void readBarCode(String response, String scannedBarcode) {
final CountDownLatch latch = new CountDownLatch(1);
final String[] names = new String[4];
JSONArray mArray, mArray1, mArray2;
int totalCount = 0;
int avail = 0;
String author, title, publisherName;
try {
JSONObject obj = new JSONObject(response);
//Results
if (obj.getJSONObject("Results") != null) {
JSONObject obj1 = obj.getJSONObject("Results");
//LookupTitleInfoResponse
if (obj1.getJSONObject("LookupTitleInfoResponse") != null) {
JSONObject obj2 = obj1.getJSONObject("LookupTitleInfoResponse");
//TitleInfo
if (obj2.getJSONArray("TitleInfo") != null) {
mArray = obj2.getJSONArray("TitleInfo");
JSONObject titleInfo = mArray.getJSONObject(0);
JSONArray arr1 = titleInfo.getJSONArray("CallInfo");
JSONObject callInfo = arr1.getJSONObject(0);
JSONArray arr2 = callInfo.getJSONArray("ItemInfo");
Log.i("ItemInfo", arr2 + "");
for (int i = 0; i < arr2.length(); i++) {
if (arr2.getJSONObject(i).getString("chargeable").equals("False")) {
totalCount++;
}
if (arr2.getJSONObject(i).getString("itemID").equals(scannedBarcode)) {
avail = 1;
}
}
author = mArray.getJSONObject(0).getString("author");
publisherName = mArray.getJSONObject(0).getString("publisherName");
title = mArray.getJSONObject(0).getString("title");
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}

Couchbase - query is not updated

I made a filter and filtering the values from the couch-base. Only first time i am able to getting the right filter values, after that it is returing the previous filter values every time. So i have to clear the cache every time. Please help.
Here is my query code.
public Query getFilterQuery(final String titles, final String sender,
final String sysName, final String prosName, final String fromDate,
final String toDate) {
final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
com.couchbase.lite.View view = database.getView(FILTER_VIEW);
if (view.getMap() == null) {
Mapper mapper = new Mapper() {
public void map(Map<String, Object> document, Emitter emitter) {
String type = (String) document.get(AppConstants.KEY_DOC_TYPE);
if (AppConstants.DOC_TYPE_MESSAGE.equals(type)) {
String message_type = (String) document.get(AppConstants.MESSAGE_TYPE);
Log.d("message_type", message_type);
if (message_type.equals("task")) {
String msgDetails = (String) document.get(AppConstants.MESSAGE_BODY);
try {
JSONObject msgObj = new JSONObject(msgDetails);
DocumentReader documentReader = mApplication
.getDocumentReader(message_type);
documentReader.setJsonObject(msgObj);
String title = (String) documentReader.getValue("task.title");
JSONArray infoArray = (JSONArray) documentReader.getValue("task.info");
String taskDate = null;
String senderName = null;
String processName = null;
for (int i = 0; i < infoArray.length(); i++) {
JSONObject jObject = infoArray
.getJSONObject(i);
String field_label = jObject
.getString(AppConstants.LABEL);
if (field_label.equals(TASK_DATE)) {
taskDate = jObject
.getString(AppConstants.FIELD_VALUE);
Log.d("taskDate", taskDate);
}
if (field_label.equals(SENDER)) {
senderName = jObject
.getString(AppConstants.FIELD_VALUE);
}
if (field_label.equals(PROCESS_NAME)) {
processName = jObject
.getString(AppConstants.FIELD_VALUE);
}
}
Date dateFrom = null;
Date dateTo = null;
try {
date = dateFormat.parse(taskDate);
Log.d("taskDate", taskDate);
if (toDate != null && fromDate != null) {
dateTo = dateFormat.parse(toDate);
dateFrom = dateFormat.parse(fromDate);
}
} catch (ParseException e) {
e.printStackTrace();
}
/*if (titles != null && titles.contains(title)) {
emitter.emit(document.get(AppConstants.MESSAGE_ID),document);
}*/
if (senderName != null && senderName.contains(sender)) {
emitter.emit(document.get(AppConstants.MESSAGE_ID),document);
}
/*if (processName != null && processName.contains(prosName)) {
emitter.emit(document.get(AppConstants.MESSAGE_ID),document);
}*/
/*if (date.before(dateTo) && date.after(dateFrom)) {
emitter.emit(document.get(AppConstants.MESSAGE_ID),document);
}*/
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
};
view.setMap(mapper, "1");
}
Query query = view.createQuery();
return query;
}
}
A Query in Couchbase-lite is split into 2 parts.
Setting up the view (basically - the index)
Running the query against the view.
You should create you view only once (your mapper) and run queries against it with a search term under startkey and endkey.
You can also do a compound index, which is basically a string compound from several keys and search by it.
If you set the map everytime you run the query-the query will not be updated, as it look at you version argument and it's always set to a string "1".
if you will change it you will get a new index for you query - but it should be used only in dev when you change your view.
Roi.

Read HTML file from assets

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 ....

Categories

Resources