Android - Get attributes from CDATA section using XMLPullParser - cdata

The xml looks like this (out of a RSS feed):
<description>
<![CDATA[
<div><a href='articleURL'><img src='pic.jpg' alt='blah blah' title='blah blah'
border='0' width='100' height='56'></a></div>
]]>
gist of the article.....
</description>
I want to get the following attributes:
img src - holding the article pic
the article gist at the end of the tag but when running I get a NullPointer Ex.
All the rest (outside the CDATA section work just fine...)
the code I used:
class BackgroundParser extends AsyncTask<String, String, Integer>{
int headlineCount = 0;
String headlineTitle = "";
Bitmap pic = null;
String xmlDate = "";
String gist = "";
String articleUrl = "";
#Override
protected Integer doInBackground(String... params) {
// TODO Auto-generated method stub
try {
URL rssFeed = new URL(params[0]);
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
InputStream is = rssFeed.openStream();
parser.setInput(is, null);
boolean item = false;
boolean title = false;
boolean date = false;
boolean description = false;
boolean link = false;
String tagName;
int eventType = parser.getEventType();
while(eventType!=XmlPullParser.END_DOCUMENT){
if(eventType==XmlPullParser.START_TAG){
tagName = parser.getName();
if(item){
if(tagName.equals("title"))title = true;
if(tagName.equals("description")){
String img = parser.getAttributeValue(null, "img src");
Log.i("Info", img);
pic = getBitmapFromURL(img);
}
if(tagName.equals("pubDate"))date = true;
if(tagName.equals("description"))description = true;
if(tagName.equals("link"))link = true;
}
else{
if(tagName.equals("item"))item = true;
}
}
if(eventType==XmlPullParser.END_TAG){
tagName = parser.getName();
if(tagName.equals("item")){
item = false;
headlines.add(new Headline(headlineTitle,xmlDate,pic,gist,articleUrl));
headlineTitle = null; xmlDate = null; pic = null; gist = null; articleUrl = null;
headlineCount++;
}
}
if(eventType==XmlPullParser.TEXT){
if(title){
headlineTitle = parser.getText();
Log.i("Info", headlineTitle);
title = false;
}
if(date){
xmlDate = parser.getText();
Log.i("Info", xmlDate);
date = false;
}
if(description){
gist = parser.getText();
Log.i("info",gist);
description = false;
}
if(link){
articleUrl = parser.getText();
Log.i("info", articleUrl);
link = false;
}
}
eventType = parser.next();
}

This is what I did:
if(tagName.equals("description")){
int token = parser.nextToken();
while(token!=XmlPullParser.CDSECT){
token = parser.nextToken();
}
String cdata = parser.getText();
Log.i("Info", cdata);
String result = cdata.substring(cdata.indexOf("src='")+5, cdata.indexOf("jpg")+3);
Log.i("Info", result);
pic = getBitmapFromURL(result);
}
Is there a more elegant way of doing this???

Related

NoSuchMethodError : The Setter "movies=" was called on null

Future<YifyMovies> getData() async {
var res = await http.get("https://yts.lt/api/v2/list_movies.json");
var decodedJson = jsonDecode(res.body);
YifyMovies movie = YifyMovies();
movie.data.movies = [];
for (var json in decodedJson) {
movie.data.movies.add(Movies.fromJson(json));
}
return movie;
}
Yify Movies class:-
It's the JSON from the above API converted int0 dart.
class YifyMovies {
String status;
String statusMessage;
Data data;
YifyMovies({this.status, this.statusMessage, this.data});
YifyMovies.fromJson(Map<String, dynamic> json) {
status = json['status'];
statusMessage = json['status_message'];
data = json['data'] != null ? new Data.fromJson(json['data']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
data['status_message'] = this.statusMessage;
if (this.data != null) {
data['data'] = this.data.toJson();
}
return data;
}
}
class Data {
int movieCount;
int limit;
int pageNumber;
List<Movies> movies;
Data({this.movieCount, this.limit, this.pageNumber, this.movies});
Data.fromJson(Map<String, dynamic> json) {
movieCount = json['movie_count'];
limit = json['limit'];
pageNumber = json['page_number'];
if (json['movies'] != null) {
movies = new List<Movies>();
json['movies'].forEach((v) {
movies.add(new Movies.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['movie_count'] = this.movieCount;
data['limit'] = this.limit;
data['page_number'] = this.pageNumber;
if (this.movies != null) {
data['movies'] = this.movies.map((v) => v.toJson()).toList();
}
return data;
}
}
class Movies {
int id;
String url;
String imdbCode;
String title;
String titleEnglish;
String titleLong;
String slug;
int year;
double rating;
int runtime;
List<String> genres;
String summary;
String descriptionFull;
String synopsis;
String ytTrailerCode;
String language;
String mpaRating;
String backgroundImage;
String backgroundImageOriginal;
String smallCoverImage;
String mediumCoverImage;
String largeCoverImage;
String state;
List<Torrents> torrents;
String dateUploaded;
int dateUploadedUnix;
Movies(
{this.id,
this.url,
this.imdbCode,
this.title,
this.titleEnglish,
this.titleLong,
this.slug,
this.year,
this.rating,
this.runtime,
this.genres,
this.summary,
this.descriptionFull,
this.synopsis,
this.ytTrailerCode,
this.language,
this.mpaRating,
this.backgroundImage,
this.backgroundImageOriginal,
this.smallCoverImage,
this.mediumCoverImage,
this.largeCoverImage,
this.state,
this.torrents,
this.dateUploaded,
this.dateUploadedUnix});
Movies.fromJson(Map<String, dynamic> json) {
id = json['id'];
url = json['url'];
imdbCode = json['imdb_code'];
title = json['title'];
titleEnglish = json['title_english'];
titleLong = json['title_long'];
slug = json['slug'];
year = json['year'];
rating = json['rating'];
runtime = json['runtime'];
genres = json['genres'].cast<String>();
summary = json['summary'];
descriptionFull = json['description_full'];
synopsis = json['synopsis'];
ytTrailerCode = json['yt_trailer_code'];
language = json['language'];
mpaRating = json['mpa_rating'];
backgroundImage = json['background_image'];
backgroundImageOriginal = json['background_image_original'];
smallCoverImage = json['small_cover_image'];
mediumCoverImage = json['medium_cover_image'];
largeCoverImage = json['large_cover_image'];
state = json['state'];
if (json['torrents'] != null) {
torrents = new List<Torrents>();
json['torrents'].forEach((v) {
torrents.add(new Torrents.fromJson(v));
});
}
dateUploaded = json['date_uploaded'];
dateUploadedUnix = json['date_uploaded_unix'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['url'] = this.url;
data['imdb_code'] = this.imdbCode;
data['title'] = this.title;
data['title_english'] = this.titleEnglish;
data['title_long'] = this.titleLong;
data['slug'] = this.slug;
data['year'] = this.year;
data['rating'] = this.rating;
data['runtime'] = this.runtime;
data['genres'] = this.genres;
data['summary'] = this.summary;
data['description_full'] = this.descriptionFull;
data['synopsis'] = this.synopsis;
data['yt_trailer_code'] = this.ytTrailerCode;
data['language'] = this.language;
data['mpa_rating'] = this.mpaRating;
data['background_image'] = this.backgroundImage;
data['background_image_original'] = this.backgroundImageOriginal;
data['small_cover_image'] = this.smallCoverImage;
data['medium_cover_image'] = this.mediumCoverImage;
data['large_cover_image'] = this.largeCoverImage;
data['state'] = this.state;
if (this.torrents != null) {
data['torrents'] = this.torrents.map((v) => v.toJson()).toList();
}
data['date_uploaded'] = this.dateUploaded;
data['date_uploaded_unix'] = this.dateUploadedUnix;
return data;
}
}
class Torrents {
String url;
String hash;
String quality;
String type;
int seeds;
int peers;
String size;
int sizeBytes;
String dateUploaded;
int dateUploadedUnix;
Torrents(
{this.url,
this.hash,
this.quality,
this.type,
this.seeds,
this.peers,
this.size,
this.sizeBytes,
this.dateUploaded,
this.dateUploadedUnix});
Torrents.fromJson(Map<String, dynamic> json) {
url = json['url'];
hash = json['hash'];
quality = json['quality'];
type = json['type'];
seeds = json['seeds'];
peers = json['peers'];
size = json['size'];
sizeBytes = json['size_bytes'];
dateUploaded = json['date_uploaded'];
dateUploadedUnix = json['date_uploaded_unix'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['url'] = this.url;
data['hash'] = this.hash;
data['quality'] = this.quality;
data['type'] = this.type;
data['seeds'] = this.seeds;
data['peers'] = this.peers;
data['size'] = this.size;
data['size_bytes'] = this.sizeBytes;
data['date_uploaded'] = this.dateUploaded;
data['date_uploaded_unix'] = this.dateUploadedUnix;
return data;
}
}
Any help, please? Tell me if any more info is required?
I'm trying to list all the movies and use them for tabview in flutter which can show them in listview as well as gridview. I'm using Bloc architecture for layouts so YifyMovie class is in hom_model and the code above is in home_provider.
Your YifyMovies class is already handling the parsing for you.
So your code should change from
Future<YifyMovies> getData() async {
var res = await http.get("https://yts.lt/api/v2/list_movies.json");
var decodedJson = jsonDecode(res.body);
YifyMovies movie = YifyMovies();
movie.data.movies = [];
for (var json in decodedJson) {
movie.data.movies.add(Movies.fromJson(json));
}
return movie;
}
to
Future<YifyMovies> getData() async {
var res = await http.get("https://yts.lt/api/v2/list_movies.json");
var decodedJson = jsonDecode(res.body);
YifyMovies movie = YifyMovies.fromJson(decodedJson);
return movie;
}

How to get resource names for optional content group in a pdf?

I am trying to implement functionality to allow user to add markups to existing layers in a pdf. Here is the code that I am using to draw lines on to a layer in a pdf:
PDResources resources = page.findResources();
PDPropertyList props = resources.getProperties();
COSName resourceName = getLayerResourceName("Superimposed3", resources, props);
PDPageContentStream cs1 = new PDPageContentStream(document, page, true, false);
cs1.beginMarkedContentSequence(COSName.OC, resourceName);
cs1.setStrokingColor(0, 0, 255);
cs1.setLineWidth(0.8F);
cs1.drawLine(100,100,250,200);
cs1.endMarkedContentSequence();
cs1.close();
I am using beginMarkedContentSequence instead of beginMarkedContent as I am using pdfbox 1.8 version and 2.0.5 version is not available for .net.
Here, is my function to get resource name for a layer:
private static COSName getLayerResourceName(string layerName,PDResources resources,PDPropertyList props)
{
int index = 0;
COSName resourceName = COSName.getPDFName("MC"+ index);
PDOptionalContentGroup ocg = props.getOptionalContentGroup(resourceName);
if (ocg != null && (ocg.getName() == layerName))
{
return resourceName;
}
else if (ocg == null)
{
return null;
}
else
{
resourceName = null;
index++;
bool exitFlag = false;
while (!exitFlag)
{
resourceName = COSName.getPDFName("MC" + index);
ocg = props.getOptionalContentGroup(resourceName);
if (ocg == null)
{
exitFlag = true;
resourceName = null;
}
else if (ocg.getName() == layerName)
{
exitFlag = true;
}
else
{
index++;
}
}
}
return resourceName;
}
The above functions only works for those layers which were added using the LayerUtility.appendFormAsLayer function. But it doesn't work for those layers which were created using the following code:
PDOptionalContentProperties ocprops = document.getDocumentCatalog().getOCProperties();
PDOptionalContentGroup newGroup = new PDOptionalContentGroup("Superimposed2");
PDOptionalContentGroup newGroup1 = new PDOptionalContentGroup("Superimposed3");
ocprops.addGroup(newGroup);
ocprops.addGroup(newGroup1);
So, shall I add "MC" value in properties of page myself while, creating layer, or is there another way to get resource name for such layers.

Razor MVC return HTML

I tried to research a bit, but has not found a proper solution to this.
What I'm trying to do is to have a HTML.Action in a page like so
Html.Action("Calendar", "GlobalShared")
Inside the action "Calendar", I need to return the result of the html of the traditional calendar control
public ActionResult Calendar(
String ID,
String CssClass,
int CellSpacing,
int CellPadding,
String BorderWidth,
String ShowGridLines,
String ShowTitle,
String DayNameFormat
)
{
System.Web.UI.WebControls.Calendar cal = new System.Web.UI.WebControls.Calendar();
cal.ID = "MyCalendar";
cal.CssClass = "month-view";
cal.CellSpacing = 0;
cal.CellPadding = -1;
cal.BorderWidth = 0;
cal.ShowGridLines = false;
cal.ShowTitle = false;
cal.DayNameFormat = System.Web.UI.WebControls.DayNameFormat.Full;
}
How can I do this? Btw, I use HTML.Action is because I read that it returns a html string, is that correct or should I be doing some other ways?
Thanks
Edit. Before I attempted this in a controller, I tried the following code in a view .cshtml and it works, but I prefer to move the code into a controller
#{
System.Web.UI.WebControls.Calendar cal = new System.Web.UI.WebControls.Calendar();
cal.ID = "MyCalendar";
cal.CssClass = "month-view";
cal.CellSpacing = 0;
cal.CellPadding = -1;
cal.BorderWidth = 0;
cal.ShowGridLines = false;
cal.ShowTitle = false;
cal.DayNameFormat = System.Web.UI.WebControls.DayNameFormat.Full;
cal.RenderControl(new HtmlTextWriter(Html.ViewContext.Writer));
}
Edit #2. The reason I want to use that in a controller is because if in the future, i want to hook up an event say "DayRender", I can do it in the controller. I can not do the same in a view without polluting the view page.
Okay. Thanks guys. I figured out. Basically, I need to use #{Html.RenderAction(..)} and in the action itself, use StringBuilder/StringWriter and then return Content(...). Code below
In View
#{Html.RenderAction("Calendar", "GlobalShared");}
In Controller
[ChildActionOnly]
public ActionResult Calendar(
)
{
System.Web.UI.WebControls.Calendar cal = new System.Web.UI.WebControls.Calendar();
cal.ID = "MyCalendar";
cal.CssClass = "month-view";
cal.CellSpacing = 0;
cal.CellPadding = -1;
cal.BorderWidth = 0;
cal.ShowGridLines = false;
cal.ShowTitle = false;
cal.DayNameFormat = System.Web.UI.WebControls.DayNameFormat.Full;
cal.DayRender += new System.Web.UI.WebControls.DayRenderEventHandler(CalendarDayRender);
StringBuilder sb = new StringBuilder();
using (System.IO.StringWriter sw = new System.IO.StringWriter(sb))
{
System.Web.UI.HtmlTextWriter writer = new System.Web.UI.HtmlTextWriter(sw);
cal.RenderControl(writer);
}
String calHTML = sb.ToString();
return Content(calHTML);
}
private void CalendarDayRender(object sender, System.Web.UI.WebControls.DayRenderEventArgs e)
{
e.Cell.Text = "";
if (e.Day.Date == System.DateTime.Today)
{
e.Cell.CssClass = "today";
System.Web.UI.HtmlControls.HtmlGenericControl h3 = new System.Web.UI.HtmlControls.HtmlGenericControl("h3");
h3.InnerHtml = HttpContext.GetGlobalResourceObject("JTG_DateTime", "JTK_Today") + " " + e.Day.DayNumberText;
e.Cell.Controls.Add(h3);
}
}
Simply move your code
#{
System.Web.UI.WebControls.Calendar cal = new System.Web.UI.WebControls.Calendar();
cal.ID = "MyCalendar";
cal.CssClass = "month-view";
cal.CellSpacing = 0;
cal.CellPadding = -1;
cal.BorderWidth = 0;
cal.ShowGridLines = false;
cal.ShowTitle = false;
cal.DayNameFormat = System.Web.UI.WebControls.DayNameFormat.Full;
cal.RenderControl(new HtmlTextWriter(Html.ViewContext.Writer));
}
in a view and return that View from your Calendar Action.
public ActionResult Calendar(
String ID,
String CssClass,
int CellSpacing,
int CellPadding,
String BorderWidth,
String ShowGridLines,
String ShowTitle,
String DayNameFormat
)
{
return View("Calendar");
}
You can either create a ViewModel or use ViewBag to transfer these values from Calendar Action to your newly created View

To display an album art from media store in android

I'm not able to display album art from media store while listing albums,I'm getting
error
Bad request for field slot 0,-1. numRows = 32, numColumns = 7
01-02 02:48:16.789: D/AndroidRuntime(4963): Shutting down VM
01-02 02:48:16.789: W/dalvikvm(4963): threadid=1: thread exiting with uncaught exception (group=0x4001e578)
01-02 02:48:16.804: E/AndroidRuntime(4963): FATAL EXCEPTION: main
01-02 02:48:16.804: E/AndroidRuntime(4963): java.lang.IllegalStateException: get field slot from row 0 col -1 failed
Can anyone kindly help with this issue,Thanks in advance
public class AlbumbsListActivity extends Activity {
private ListAdapter albumListAdapter;
private HashMap<Integer, Integer> albumInfo;
private HashMap<Integer, Integer> albumListInfo;
private HashMap<Integer, String> albumListTitleInfo;
private String audioMediaId;
private static final String TAG = "AlbumsListActivity";
Boolean showAlbumList = false;
Boolean AlbumListTitle = false;
ImageView album_art ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.albums_list_layout);
Cursor cursor;
ContentResolver cr = getApplicationContext().getContentResolver();
if (getIntent().hasExtra(Util.ALBUM_ID)) {
int albumId = getIntent().getIntExtra(Util.ALBUM_ID,
Util.MINUS_ONE);
String[] projection = new String[] { Albums._ID, Albums.ALBUM, Albums.ARTIST, Albums.ALBUM_ART, Albums.NUMBER_OF_SONGS };
String selection = null;
String[] selectionArgs = null;
String sortOrder = Media.ALBUM + " ASC";
cursor = cr.query(Albums.EXTERNAL_CONTENT_URI, projection, selection, selectionArgs, sortOrder);
/* final String[] ccols = new String[] {
//MediaStore.Audio.Albums.,
MediaStore.Audio.Albums._ID,
MediaStore.Audio.Albums.ALBUM,
MediaStore.Audio.Albums.ARTIST,
MediaStore.Audio.Albums.ALBUM_ART,
MediaStore.Audio.Albums.NUMBER_OF_SONGS
};
cursor = cr.query(MediaStore.Audio.Albums.getContentUri(
"external"), ccols, null, null,
MediaStore.Audio.Albums.DEFAULT_SORT_ORDER);*/
showAlbumList = true;
}
else
{
String order = MediaStore.Audio.Albums.ALBUM + " ASC";
String where = MediaStore.Audio.Albums.ALBUM;
cursor = managedQuery(Media.EXTERNAL_CONTENT_URI,
DbUtil.projection, null, null, order);
showAlbumList = false;
}
albumInfo = new HashMap<Integer, Integer>();
albumListInfo = new HashMap<Integer, Integer>();
ListView listView = (ListView) findViewById(R.id.mylist_album);
listView.setFastScrollEnabled(true);
listView.setOnItemLongClickListener(new ItemLongClickListener());
listView.setAdapter(new AlbumCursorAdapter(this, cursor,
DbUtil.displayFields, DbUtil.displayViews,showAlbumList));
final Uri uri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
final Cursor albumListCursor = cr.query(uri, DbUtil.Albumprojection,
null, null, null);
}
private class AlbumCursorAdapter extends SimpleCursorAdapter implements SectionIndexer{
private final Context context;
private final Cursor cursorValues;
private Time musicTime;
private Boolean isAlbumList;
private MusicAlphabetIndexer mIndexer;
private int mTitleIdx;
public AlbumCursorAdapter(Context context, Cursor cursor, String[] from,
int[] to,Boolean isAlbumList) {
super(context, 0, cursor, from, to);
this.context = context;
this.cursorValues = cursor;
//musicTime = new Time();
this.isAlbumList = isAlbumList;
}
String albumName="";
String artistName = "";
String numberofsongs = "";
long albumid;
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater
.inflate(R.layout.row_album_layout, parent, false);
}
this.cursorValues.moveToPosition(position);
String title = "";
String artistName = "";
String albumName = "";
int count;
long albumid = 0;
String songDuration = "";
if (isAlbumList) {
albumInfo.put(
position,
Integer.parseInt(this.cursorValues.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Albums._ID))));
artistName = this.cursorValues
.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Albums.ARTIST));
albumName = this.cursorValues
.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Albums.ALBUM));
albumid=Integer.parseInt(this.cursorValues.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ID)));
} else {
albumInfo.put(position, Integer.parseInt(this.cursorValues
.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Media._ID))));
artistName = this.cursorValues.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Media.ARTIST));
albumName = this.cursorValues.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Media.ALBUM));
albumid=Integer.parseInt(this.cursorValues.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)));
}
//code for Alphabetical Indexer
mTitleIdx = cursorValues.getColumnIndex(MediaStore.Audio.Media.ALBUM);
mIndexer = new MusicAlphabetIndexer(cursorValues, mTitleIdx,
getResources().getString(R.string.fast_scroll_alphabet));
//end
TextView metaone = (TextView) rowView.findViewById(R.id.album_name);
TextView metatwo = (TextView) rowView.findViewById(R.id.artist_name);
ImageView metafour = (ImageView) rowView.findViewById(R.id.album_art);
TextView metathree = (TextView) rowView
.findViewById(R.id.songs_count);
metaone.setText(albumName);
metatwo.setText(artistName);
(metafour)getAlbumArt(albumid);
System.out.println("albumid----------"+albumid);
metaThree.setText(DbUtil.makeTimeString(context, secs));
getAlbumArt(albumid);
}
TextView metaone = (TextView) rowView.findViewById(R.id.album_name);
TextView metatwo = (TextView) rowView.findViewById(R.id.artist_name);
album_art = (ImageView) rowView.findViewById(R.id.album_art);
//TextView metathree = (TextView) rowView.findViewById(R.id.songs_count);
metaone.setText(albumName);
metatwo.setText(artistName);
return rowView;
}
}
String albumArtUri = "";
private void getAlbumArt(long albumid) {
Uri uri=ContentUris.withAppendedId(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, albumid);
System.out.println("hhhhhhhhhhh" + uri);
Cursor cursor = getContentResolver().query(
ContentUris.withAppendedId(
MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, albumid),
new String[] { MediaStore.Audio.AlbumColumns.ALBUM_ART },
null,
null,
null);
if (cursor.moveToFirst()) {
albumArtUri = cursor.getString(0);
}
System.out.println("kkkkkkkkkkkkkkkkkkk :" + albumArtUri);
cursor.close();
if(albumArtUri != null){
Options opts = new Options();
opts.inJustDecodeBounds = true;
Bitmap albumCoverBitmap = BitmapFactory.decodeFile(albumArtUri, opts);
opts.inJustDecodeBounds = false;
albumCoverBitmap = BitmapFactory.decodeFile(albumArtUri, opts);
if(albumCoverBitmap != null)
album_art.setImageBitmap(albumCoverBitmap);
}else {
// TODO:
Options opts = new Options();
Bitmap albumCoverBitmap = BitmapFactory.decodeResource(getApplicationContext().getResources(),
R.drawable.albumart_mp_unknown_list, opts);
if(albumCoverBitmap != null)
album_art.setImageBitmap(albumCoverBitmap);
}
}
}
}

Nhibernate Throws Found shared references to a collection

I have read thru a number of other questions similar to this one - but being new to Nhibernate, none of them seem to answer my question of why is Inhibernate throwing a "Found shared references to a collection: Order.ShippingAddress.Items" to the following code:
VendorOrderNotificationAcknowledgement ICheckoutVendorService.SendOrderNotification(VendorOrderNotification request)
{
OrderRepository repo = new OrderRepository();
var order =(AbstractOrder) repo.FindByCartId(request.OrderNotification.CartOrderId);
ShippingAddress billingAddress = order.ShippingAddresses[0];
var itemsFromDb = billingAddress.Items;
order.ClearAllShippingAddresses();
wcfFactory.UpdateOrder(order); //NO ERROR THROWN HERE!
ShippingAddress shippingAddress = orderHelper.CreateShippingAddress(request.ShippingDetails);
shippingAddress.Items = itemsFromDb;
order.AddShippingAddress(shippingAddress);
order.SourceCode = _sourceCode;
order.TaxAmount = 0;
order.GiftCertificateAmount = 0;
order.Status = StatusCode.Approved;
order.CreatedAt = request.OrderNotification.OrderTime.Year >2010
? request.OrderNotification.OrderTime
: DateTime.Now;
order.PurchasedDate=
request.OrderNotification.OrderTime.Year>2010
? request.OrderNotification.OrderTime
: DateTime.Now;
order.UpdatedAt = DateTime.Now;
if (request.OrderNotification.OrderCharges != null)
{
order.ShippingAmount = request.OrderNotification.OrderCharges.Shipping;
order.TaxAmount = request.OrderNotification.OrderCharges.DutyAndTaxes;
}
else
{
order.ShippingAmount = 0;
order.TaxAmount = 0;
}
order.UseGiftWrap = false;
order.SourceCode = _sourceCode;
UpdateEshopWorldOrder(order); // THROWS FOUND SHARED REFERENCES TO A COLLECTION: ORDER.SHIPPINGADDRESS.ITEMS
var orderDto = orderHelper.CreateOrderDto(billingAddress, orderHelper, order);
var dtoShippingAddresses = orderHelper.CreateDtoShippingAddresses(order);
orderDto.ShippingAddresses = dtoShippingAddresses;
ShippingMethodDto shippingMethodDto = 0;
var mine = wcfFactory.SendOrder(orderDto);
//More Code below here ...
}
public OrderDto CreateOrderDto(ShippingAddress billingAddress, OrderHelper orderHelper, AbstractOrder order)
{
OrderDto orderDto = new OrderDto();
orderDto.AlternateOrderId = order.Id.ToString();
orderDto.ConfirmationNumber = order.ConfirmationNumber;
orderDto.Coupons = new string[0];
orderDto.DiscountAmount = order.DiscountAmount;
orderDto.GiftCardAmount = order.GiftCertificateAmount;
orderDto.PurchaseDate = order.PurchasedDate;
orderDto.ShippingAmount = order.ShippingAmount;
orderDto.SourceCode = order.SourceCode;
orderDto.TaxAmount = order.TaxAmount;
orderDto.UseGiftWrap = order.UseGiftWrap;
var customerDto = orderHelper.CreateCustomerDto(billingAddress);
orderDto.SoldTo = customerDto;
return orderDto;
}
public void UpdateEshopWorldOrder(AbstractOrder order)
{
try
{
//Session.Update(order);
// transaction.Commit();
Session.Flush();
}
catch (Exception ex)
{
_logger.Debug("order saved failed with an error of " + ex.Message);
_logger.Error(ex);
throw;
}
}
Any insights are appreciated....
thnx
I think the problem is, that your itemsFromDB collection object is referenced by shippingAddress and also by billingAddress.
Both entities need their own collection-objects. Both collections however may contain references to the same address-objects.
So I assume replacing shippingAddress.Items = itemsFromDb; with something like
shippingAddress.Items.AddRange(itemsFromDb)
or
shippingAddress.Items = new List<ShippingAddress>(itemsFromDb) should do the trick