Display Tow Array Adapter - android-arrayadapter

I want to display
ArrayAdapter<com.example.database.Sms>adapter = new SmsAdapter(this, smss);
and
ArrayAdapter<com.example.database2.part1> adapter = new DastanAdapter(this, part1);
But according to my code it shows just one of them but I want to have both of them shown
public void refreshDisplay() {
Log.i(com.example.database.DBAdapter.TAG, smss.size() + "= tedad smss");
ArrayAdapter<com.example.database.Sms>adapter = new SmsAdapter(this, smss);
setListAdapter(adapter);
}
public void refreshDisplay2() {
Log.i(DBAdapter.TAG, part1.size() + "= tedad part1");
ArrayAdapter<com.example.database2.part1> adapter = new DastanAdapter(this, part1);
setListAdapter(adapter);
}

Related

pull images from twitter API on processing 3

I am quite new to this so please bear with me. I am trying to use a keyword search to pull images from twitter using twitter4j. I want it to show the images positioned randomly on the screen in a loop.
This code I have below is a combination of different ones I have found online. Its currently finding tweets using these keywords and showing them in the console, however, it is not displaying them on the screen and I’m not sure why…
Another thing is that I think it is doing a live stream from twitter so pulling tweets immediately at the time the code is run, so I am not getting lots of results when I put in an obscure keyword, I want it to search for the last 100 tweets with images using the keyword so that I get more results
I’d really appreciate all the help I can get! thank you
///////////////////////////// Config your setup here! ////////////////////////////
// { site, parse token }
String imageService[][] = {
{
"http://twitpic.com",
"<img class=\"photo\" id=\"photo-display\" src=\""
},
{
"http://twitpic.com",
"<img class=\"photo\" id=\"photo-display\" src=\""
},
{
"http://img.ly",
"<img alt=\"\" id=\"the-image\" src=\""
},
{
"http://lockerz.com/",
"<img id=\"photo\" src=\""
},
{
"http://instagr.am/",
"<meta property=\"og:image\" content=\""
} {
"http://pic.twitter.com",
"<img id
};
// This is where you enter your Oauth info
static String OAuthConsumerKey = KEY_HERE;
static String OAuthConsumerSecret = SECRET_HERE;
static String AccessToken = TOKEN_HERE;
static String AccessTokenSecret = TOKEN_SECRET_HERE;
cb.setIncludeEntitiesEnabled(true);
Twitter twitterInstance = new TwitterFactory(cb.build()).getInstance();
// if you enter keywords here it will filter, otherwise it will sample
String keywords[] = {
"#hashtag" //sample keyword!!!!!!!!
};
///////////////////////////// End Variable Config ////////////////////////////
TwitterStream twitter = new TwitterStreamFactory().getInstance();
PImage img;
boolean imageLoaded;
void setup() {
frameRate(10);
size(800, 600);
noStroke();
imageMode(CENTER);
connectTwitter();
twitter.addListener(listener);
if (keywords.length == 0) twitter.sample();
else twitter.filter(new FilterQuery().track(keywords));
}
void draw() {
background(0);
if (imageLoaded) image(img, width / 5, height / 5);
//image(loadImage((status.getUser().getImage())), (int)random(width*.45), height-(int)random(height*.4));
}
// Initial connection
void connectTwitter() {
twitter.setOAuthConsumer(OAuthConsumerKey, OAuthConsumerSecret);
AccessToken accessToken = loadAccessToken();
twitter.setOAuthAccessToken(accessToken);
}
// Loading up the access token
private static AccessToken loadAccessToken() {
return new AccessToken(AccessToken, AccessTokenSecret);
}
// This listens for new tweet
StatusListener listener = new StatusListener() {
//#Override
public void onStatus(Status status) {
System.out.println("#" + status.getUser().getScreenName() + " - " + status.getText());
}
//#Override
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
}
//#Override
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
}
//#Override
public void onScrubGeo(long userId, long upToStatusId) {
System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
}
//#Override
public void onStallWarning(StallWarning warning) {
System.out.println("Got stall warning:" + warning);
}
//#Override
public void onException(Exception ex) {
ex.printStackTrace();
}
};
public void onStatus(Status status) {
String imgUrl = null;
String imgPage = null;
// Checks for images posted using twitter API
if (status.getMediaEntities() != null) {
imgUrl = status.getMediaEntities()[0].getMediaURL().toString();
}
// Checks for images posted using other APIs
else {
if (status.getURLEntities().length > 0) {
if (status.getURLEntities()[0].getExpandedURL() != null) {
imgPage = status.getURLEntities()[0].getExpandedURL().toString();
} else {
if (status.getURLEntities()[0].getDisplayURL() != null) {
imgPage = status.getURLEntities()[0].getDisplayURL().toString();
}
}
}
if (imgPage != null) imgUrl = parseTwitterImg(imgPage);
}
if (imgUrl != null) {
println("found image: " + imgUrl);
// hacks to make image load correctly
if (imgUrl.startsWith("//")) {
println("s3 weirdness");
imgUrl = "http:" + imgUrl;
}
if (!imgUrl.endsWith(".jpg")) {
byte[] imgBytes = loadBytes(imgUrl);
saveBytes("tempImage.jpg", imgBytes);
imgUrl = "tempImage.jpg";
}
println("loading " + imgUrl);
img = loadImage(imgUrl);
imageLoaded = true;
}
}
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
}
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
}
public void onScrubGeo(long userId, long upToStatusId) {
System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
}
public void onException(Exception ex) {
ex.printStackTrace();
}
// Twitter doesn't recognize images from other sites as media, so must be parsed manually
// You can add more services at the top if something is missing
String parseTwitterImg(String pageUrl) {
for (int i = 0; i < imageService.length; i++) {
if (pageUrl.startsWith(imageService[i][0])) {
String fullPage = ""; // container for html
String lines[] = loadStrings(pageUrl); // load html into an array, then move to container
for (int j = 0; j < lines.length; j++) {
fullPage += lines[j] + "\n";
}
String[] pieces = split(fullPage, imageService[i][1]);
pieces = split(pieces[1], "\"");
return (pieces[0]);
}
}
return (null);
}

An issue with editable JFX TableView

I have a little issue with an editable TableView. I want to display data from the database and also be able to edit then which saves it back to the DB.
Now, I can edit it. I have an if statement which checks whether the value is blank (empty or white space) and it works properly, the item in DB doesn't get updated if the value is blank.
My issue is that the blank value still gets displayed. If I click to edit it again, it displays the proper value. Here is a picture of the issue.
Here is the method which creats the table in my view class.
private TableView<Teacher> createTable(){
TableView table = new TableView();
table.setEditable(true);
table.setPrefWidth(500);
table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
nameColumn = new TableColumn<>("Jméno");
surnameColumn = new TableColumn<>("Příjmení");
nickColumn = new TableColumn<>("Nick");
table.getColumns().addAll(nameColumn, surnameColumn, nickColumn);
int columnCount = table.getColumns().size();
double columnSize = Math.floor(table.getPrefWidth() / columnCount);
nameColumn.setPrefWidth(columnSize);
surnameColumn.setPrefWidth(columnSize);
nickColumn.setPrefWidth(columnSize);
nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
surnameColumn.setCellValueFactory(new PropertyValueFactory<>("surname"));
nickColumn.setCellValueFactory(new PropertyValueFactory<>("nick"));
List<Teacher> list = new TeacherDao().getAllTeachers();
ObservableList<Teacher> observableList = FXCollections.observableArrayList(list);
table.setItems(observableList);
return table;
}
Here is the part of the controller class to handle the edits.
private void onEditAction(){
view.getNameColumn().setCellFactory(TextFieldTableCell.forTableColumn());
view.getNameColumn().setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Teacher, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<Teacher, String> col) {
String newValue = col.getNewValue();
if(!(CheckString.isBlank(newValue))) {
(col.getTableView().getItems().get(
col.getTablePosition().getRow())
).setName(col.getNewValue());
Teacher teacher = view.getTeacherTableView().getSelectionModel().getSelectedItem();
int id = teacher.getUser_id();
new TeacherDao().updateTeacherNick(id, newValue);
}
}
}
);
view.getSurnameColumn().setCellFactory(TextFieldTableCell.forTableColumn());
view.getSurnameColumn().setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Teacher, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<Teacher, String> col) {
String newValue = col.getNewValue();
if(!(CheckString.isBlank(newValue))) {
(col.getTableView().getItems().get(
col.getTablePosition().getRow())
).setName(col.getNewValue());
Teacher teacher = view.getTeacherTableView().getSelectionModel().getSelectedItem();
int id = teacher.getUser_id();
new TeacherDao().updateTeacherNick(id, newValue);
}
}
}
);
view.getNickColumn().setCellFactory(TextFieldTableCell.forTableColumn());
view.getNickColumn().setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Teacher, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<Teacher, String> col) {
String newValue = col.getNewValue();
if(!(CheckString.isBlank(newValue))) {
(col.getTableView().getItems().get(
col.getTablePosition().getRow())
).setName(col.getNewValue());
Teacher teacher = view.getTeacherTableView().getSelectionModel().getSelectedItem();
int id = teacher.getUser_id();
new TeacherDao().updateTeacherNick(id, newValue);
}
}
}
);
}
I also tried adding, it didn't help though.
else
(col.getTableView().getItems().get(
col.getTablePosition().getRow())
).setName(col.getOldValue());
Well, I managed to solve it, here is how if anyone is curious
public class TeacherTableView extends TableView {
private TableColumn<Teacher, String> nameColumn, surnameColumn, nickColumn;
TeacherTableView() {
createTable();
onEditAction();
}
private void createTable(){
setEditable(true);
setPrefWidth(500);
getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
nameColumn = new TableColumn<>("Jméno");
surnameColumn = new TableColumn<>("Příjmení");
nickColumn = new TableColumn<>("Nick");
getColumns().addAll(nameColumn, surnameColumn, nickColumn);
int columnCount = getColumns().size();
double columnSize = Math.floor(getPrefWidth() / columnCount);
nameColumn.setPrefWidth(columnSize);
nameColumn.setCellValueFactory(cdf -> cdf.getValue().nameProperty());
nameColumn.setCellFactory(TextFieldTableCell.forTableColumn());
nameColumn.setEditable(true);
surnameColumn.setPrefWidth(columnSize);
surnameColumn.setCellValueFactory(cdf -> cdf.getValue().surnameProperty());
surnameColumn.setCellFactory(TextFieldTableCell.forTableColumn());
surnameColumn.setEditable(true);
nickColumn.setPrefWidth(columnSize);
nickColumn.setCellValueFactory(cdf -> cdf.getValue().nickProperty());
nickColumn.setCellFactory(TextFieldTableCell.forTableColumn());
nickColumn.setEditable(true);
List<Teacher> list = new TeacherDao().getAllTeachers();
ObservableList<Teacher> observableList = FXCollections.observableArrayList(list);
setItems(observableList);
}
private void onEditAction(){
nameColumn.setOnEditCommit(this::updateCol);
surnameColumn.setOnEditCommit(this::updateCol);
nickColumn.setOnEditCommit(this::updateCol);
}
private void updateCol(TableColumn.CellEditEvent<Teacher, String> col) {
String newValue = col.getNewValue();
if (CheckString.isNotBlank(newValue)) {
(col.getTableView().getItems().get(
col.getTablePosition().getRow())
).setName(col.getNewValue());
Teacher teacher = (Teacher) getSelectionModel().getSelectedItem();
int id = teacher.getUser_id();
new TeacherDao().updateTeacherNick(id, newValue);
} else {
col.getTableView().refresh();
}
}
}

Opendaylight flow notification

I am writing an Opendaylight application that will extract all the flow rules as and when it is deleted, added or updated.
To get the notifications when a flow is added, removed or updated, the application should provide a listener which extends the salFlowListener interface.
However, when I create the application directory structure, it is not clear from the Opendaylight tutorials online as to where the logic is to be put.
Additionally, there are compilation errors when the notification-service is augmented using the YANG model.
Is this the right approach to getting the notifications and is any clear tutorials online that I can refer to?
Thanks.
public class ChangeListener implements DataChangeListener {
private static final Logger logger = LoggerFactory.getLogger(DhcontrollerListener.class);
private DataBroker dataBroker;
public DhcontrollerListener(DataBroker broker) {
this.dataBroker = broker;
//flow
InstanceIdentifier<Flow> flowPath = InstanceIdentifier.builder(Nodes.class)
.child(Node.class).augmentation(FlowCapableNode.class).child(Table.class)
.child(Flow.class).build();
dataBroker.registerDataChangeListener(LogicalDatastoreType.OPERATIONAL, flowPath, this,
DataChangeScope.BASE);
}
#Override
public void onDataChanged(AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> change) {
if (change == null) {
logger.info("DhcontrollerListener ===>>> onDataChanged: change is null");
return;
}
handleCreatedFlow(change);
handleUpdatedFlow(change);
handleDeletedFlow(change);
}
private void handleCreatedFlow(AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> change) {
Map<InstanceIdentifier<?>, DataObject> createdData = change.getCreatedData();
if (createdData == null) {
logger.info("handleCreatedFlow ===>>> getRemovedPaths==null");
return;
}
for (Map.Entry<InstanceIdentifier<?>, DataObject> entry : createdData.entrySet()) {
final DataObject dataObject = entry.getValue();
if (dataObject instanceof Flow) {
Flow flow = (Flow) dataObject;
logger.info("create flow : " + flow.getCookie() + " " + flow.getKey().toString());
}
}
}
private void handleUpdatedFlow(AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> change) {
Map<InstanceIdentifier<?>, DataObject> updatedData = change.getCreatedData();
if (updatedData == null) {
logger.info("handleUpdatedFlow ===>>> getRemovedPaths==null");
return;
}
for (Map.Entry<InstanceIdentifier<?>, DataObject> entry : updatedData.entrySet()) {
final DataObject dataObject = entry.getValue();
if (dataObject instanceof Flow) {
Flow flow = (Flow) dataObject;
logger.info("update flow : " + flow.getCookie() + " " + flow.getKey().toString());
}
}
}
private void handleDeletedFlow(AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> change) {
Map<InstanceIdentifier<?>, DataObject> originalData = change.getOriginalData();
Set<InstanceIdentifier<?>> removedData = change.getRemovedPaths();
if (removedData == null) {
logger.info("handleDeletedFlow ===>>> getRemovedPaths==null");
return;
}
for (InstanceIdentifier<?> instanceIdentifier : removedData) {
final DataObject dataObject = originalData.get(instanceIdentifier);
if (dataObject instanceof Flow) {
Flow flow = (Flow) dataObject;
logger.info("remove flow : " + flow.getCookie() + " " + flow.getPriority() + " "
+ flow.getMatch().getIpMatch() + " " + flow.getKey().toString());
}
}
}
}
How I do is to set the InstanceIdentifier. Setting different InstanceIdentifier, you can also listener to the change of node, table, and so on.

Sharepoint 2010 Custom Webpart - Access Denied Error

we've created a custom webpart to display announcements from all lists a user has access to, removing a few. The error we are having is that the webpart works fine on the page for the administrators, but when testing with regular user accounts, they are unable to see the page at all and are given a Access Denied error which is coming from the webpart itself.
Only when a user is added as a Site Collection Administrator they can see the page and have access to the webpart. What I'd like some advice on is how to be able to apply full read permissions to a select group within the code itself.
Below is the backend code
using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
namespace Test.TestWebPart
{
public partial class TestWebPartUserControl : UserControl
{
//Global variable call
private SPSite thisSite = SPContext.Current.Site;
private SPWebCollection thisWeb;
private DataTable dt;
private SPListCollection siteLists;
private DataTableWrapper myDataTable;
//Occurs when the page loads
protected void Page_Load(object sender, EventArgs e)
{
//Pulls all the websites in the site into a webcollection
thisWeb = thisSite.AllWebs;
//If the page is not postback call BindToGrid()
if (!Page.IsPostBack)
{
BindToGrid();
}
}
private void BindToGrid()
{
//Create a new DataTable along with the columns and headers
dt = new DataTable();
dt.Columns.Add("Title");
dt.Columns.Add("Created");
dt.Columns.Add("List");
//Call to populate the DataTable
dt = SelectData();
//Populate DataTableWrapper class and get the type
myDataTable = new DataTableWrapper(dt);
Type t = myDataTable.GetType();
//Create a ObjectDataSource to hold data and bind to spgridview
ObjectDataSource ds = new ObjectDataSource();
ds.ID = "myDataSource";
ds.TypeName = t.AssemblyQualifiedName;
ds.SelectMethod = "GetTable";
ds.ObjectCreating += new ObjectDataSourceObjectEventHandler(ds_ObjectCreating);
this.Controls.Add(ds);
grid.ID = "gridID";
BoundField column = new BoundField();
column.DataField = "Title";
column.HtmlEncode = false;
//column.SortExpression = "Title";
column.HeaderText = "Title";
grid.Columns.Add(column);
BoundField column1 = new BoundField();
column1.DataField = "Created";
column1.HtmlEncode = true;
//column1.SortExpression = "Created";
column1.HeaderText = "Created";
grid.Columns.Add(column1);
BoundField column2 = new BoundField();
column2.DataField = "List";
column2.HtmlEncode = false;
//column2.SortExpression = "List";
column2.HeaderText = "List";
grid.Columns.Add(column2);
//Provide the SPGridview with the DataSource
grid.DataSourceID = "myDataSource";
this.Controls.Add(grid);
//grid.PageSize =10;
//grid.AllowPaging = true;
//Default Pagination - commented out due to not working
//grid.PageIndexChanging += new GridViewPageEventHandler(grid_PageIndexChanging);
//grid.PagerTemplate = null;
//Bind the data to the grid
grid.DataBind();
}
//private void GenerateColumns()
//{
//}
//Used to deal with the PageIndexChange event
void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grid.PageIndex = e.NewPageIndex;
grid.DataBind();
}
//Used to deal with the ObjectCreated event
void ds_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
{
myDataTable = new DataTableWrapper(dt);
e.ObjectInstance = myDataTable;
}
//Pulls the data from lists which will be displayed
public DataTable SelectData()
{
try
{
//Create a new instance of type DataRow
DataRow row;
//Loop through each website in the webcollection
foreach (SPWeb web in thisWeb)
{
//Pull the lists from the site into a list collection
siteLists = web.Lists;
//Display only lists the current user has access to
siteLists.ListsForCurrentUser = true;
//Loop through each list within the list collection
foreach (SPList list in siteLists)
{
//If the list is an announcement list continue otherwise skip
if (list.BaseTemplate.ToString() == "Announcements")
{
//Exclude the lists stated from those whose data will be collected
if (list.Title.ToString() == "Bulletins" || list.Title.ToString() == "The Buzz - Curriculum" || list.Title.ToString() == "The Buzz - Personal" || list.Title.ToString() == "The Buzz - Support" || list.Title.ToString() == "Critical Annoucements")
{
}
else
{
//Create a item collection for each item within the current list
SPListItemCollection listItem = list.Items;
//Loop through each item within the item collection
foreach (SPListItem item in listItem)
{
//Get the url of the current website
string weburl = web.Url;
//Gets the URL of the current item
string dispurl = item.ContentType.DisplayFormUrl;
dispurl = list.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url;
//Joins together the full URL for the current item into a single variable
dispurl = string.Format("{0}/{1}?ID={2}", weburl, dispurl, item.ID);
//Create a new in the datatable as an instance of row
row = dt.Rows.Add();
//Put the correct information and links into the correct column
row["Title"] = "<a target=_blank href=\"" + dispurl + "\">" + item["Title"].ToString() + "</a>";
row["Created"] = item["Created"].ToString();
row["List"] = "<a target=_blank href=\"" + list.DefaultViewUrl + "\">" + list.Title + "</a>";
}
}
}
}
}
//Return the completed DataTable
return dt;
}
//Exception to catch any errors
catch (Exception s)
{
return dt;
}
}
}
}
Thanks
thisWeb = thisSite.AllWebs;
This code requires Administrator previliges. Run it under Elevated Previleges:
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsecurity.runwithelevatedprivileges.aspx
Based on the above comments and edited changes, here is the full working code, encase anyone was wondering:-
using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
namespace Test.TestWebPart
{
public partial class TestWebPartUserControl : UserControl
{
//Global variable call
private SPSite thisSite = SPContext.Current.Site;
//private SPWebCollection thisWeb;//
private SPWeb thisWeb = SPContext.Current.Web;
private DataTable dt;
private SPListCollection siteLists;
private DataTableWrapper myDataTable;
//Occurs when the page loads
protected void Page_Load(object sender, EventArgs e)
{
//Pulls all the websites in the site into a webcollection
//thisWeb = thisSite.AllWebs.;//
//If the page is not postback call BindToGrid()
if (!Page.IsPostBack)
{
BindToGrid();
}
}
private void BindToGrid()
{
//Create a new DataTable along with the columns and headers
dt = new DataTable();
dt.Columns.Add("Title");
dt.Columns.Add("Created");
dt.Columns.Add("List");
//Call to populate the DataTable
dt = SelectData();
//Populate DataTableWrapper class and get the type
myDataTable = new DataTableWrapper(dt);
Type t = myDataTable.GetType();
//Create a ObjectDataSource to hold data and bind to spgridview
ObjectDataSource ds = new ObjectDataSource();
ds.ID = "myDataSource";
ds.TypeName = t.AssemblyQualifiedName;
ds.SelectMethod = "GetTable";
ds.ObjectCreating += new ObjectDataSourceObjectEventHandler(ds_ObjectCreating);
this.Controls.Add(ds);
grid.ID = "gridID";
//Sorting, Filtering & paging does not work so has been commented out for now
//this.grid.AllowSorting = true;
//Bind the three columns to the SPGridView
//HtmlEncode must be false for the links to appear as true html
BoundField column = new BoundField();
column.DataField = "Title";
column.HtmlEncode = false;
//column.SortExpression = "Title";
column.HeaderText = "Title";
grid.Columns.Add(column);
BoundField column1 = new BoundField();
column1.DataField = "Created";
column1.HtmlEncode = true;
//column1.SortExpression = "Created";
column1.HeaderText = "Created";
grid.Columns.Add(column1);
BoundField column2 = new BoundField();
column2.DataField = "List";
column2.HtmlEncode = false;
//column2.SortExpression = "List";
column2.HeaderText = "List";
grid.Columns.Add(column2);
//Has been commented out due to these sections not working
//grid.AllowFiltering = true;
//grid.FilterDataFields = "Title";
//grid.FilteredDataSourcePropertyName = "FilterExpression";
//grid.FilteredDataSourcePropertyFormat = "{1} like '{0}'";
//grid.FilterDataFields = "Created";
//grid.FilteredDataSourcePropertyName = "FilterExpression";
//grid.FilteredDataSourcePropertyFormat = "{1} like '{0}'";
//grid.FilterDataFields = "ListName";
//grid.FilteredDataSourcePropertyName = "FilterExpression";
//grid.FilteredDataSourcePropertyFormat = "{1} like '{0}'";
//Provide the SPGridview with the DataSource
grid.DataSourceID = "myDataSource";
this.Controls.Add(grid);
//grid.PageSize =10;
//grid.AllowPaging = true;
//Default Pagination - commented out due to not working
//grid.PageIndexChanging += new GridViewPageEventHandler(grid_PageIndexChanging);
//grid.PagerTemplate = null;
//Bind the data to the grid
grid.DataBind();
}
//private void GenerateColumns()
//{
//}
//Used to deal with the PageIndexChange event
void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grid.PageIndex = e.NewPageIndex;
grid.DataBind();
}
//Used to deal with the ObjectCreated event
void ds_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
{
myDataTable = new DataTableWrapper(dt);
e.ObjectInstance = myDataTable;
}
//Pulls the data from lists which will be displayed
public DataTable SelectData()
{
try
{
//Create a new instance of type DataRow
DataRow row;
//Loop through each website in the webcollection
{
//Pull the lists from the site into a list collection
siteLists = thisWeb.Lists;
//Display only lists the current user has access to
siteLists.ListsForCurrentUser = true;
SPBasePermissions perms = SPBasePermissions.ViewListItems;
//Loop through each list within the list collection
foreach (SPList list in siteLists)
{
if (list.DoesUserHavePermissions(perms))
{
//If the list is an announcement list continue otherwise skip
if (list.BaseTemplate.ToString() == "Announcements")
{
//Exclude the lists stated from those whose data will be collected
if (list.Title.ToString() == "The Buzz" || list.Title.ToString() == "Test 2 list")
{
}
else
{
//Create a item collection for each item within the current list
SPListItemCollection listItem = list.Items;
//Loop through each item within the item collection
foreach (SPListItem item in listItem)
{
//Get the url of the current website
string weburl = thisWeb.Url;
//Gets the URL of the current item
string dispurl = item.ContentType.DisplayFormUrl;
dispurl = list.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url;
//Joins together the full URL for the current item into a single variable
dispurl = string.Format("{0}/{1}?ID={2}", weburl, dispurl, item.ID);
//Create a new in the datatable as an instance of row
row = dt.Rows.Add();
//Put the correct information and links into the correct column
row["Title"] = "<a target=_blank href=\"" + dispurl + "\">" + item["Title"].ToString() + "</a>";
row["Created"] = item["Created"].ToString();
row["List"] = "<a target=_blank href=\"" + list.DefaultViewUrl + "\">" + list.Title + "</a>";
}
}
}
}
}
}
//Return the completed DataTable
return dt;
}
//Exception to catch any errors
catch (Exception s)
{
return dt;
}
}
}
}
SPWeb.GetSubwebsForCurrentUser() should be used. It gets SubWebs that current user has access to. Avoid using ElevatedPriveleges until you absolutely need it.

SWT application crashes in Windows 7

I have a java SWT application that works OK with Windows XP and Windows Vista. But when I run it on Windows 7, weird errors occure, and it crashes.
For example, in a method where I call Table.removeAll() I get a java.lang.ArrayIndexOutOfBoundsException: 0. The table has SWT.VIRTUAL in style.
Another problem is when I write something in a text box (there's a ModifyListener which filters something) - after 2 characters, the cursor moves at the beginning (before first character).
The SWT version is 3.5, but I tried with the latest from the eclipse website(3.6M3) and the result is the same.
Are there any known issues? Has anybody encountered this?
Here is a snippet that doesn't work in Windows 7:
import java.util.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
public class TableCheck {
Shell shell;
Button button1, button2, button3;
UltraTable ut;
public TableCheck() {
Display display = new Display();
shell = new Shell(display);
shell.setLayout(new GridLayout(4, false));
Text text = new Text(shell, SWT.SINGLE | SWT.LEAD | SWT.READ_ONLY | SWT.BORDER);
text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
text.setText("SWT " + SWT.getPlatform() + " " + SWT.getVersion() + "; "
+ System.getProperty("os.name") + " " + System.getProperty("os.version") + " "
+ System.getProperty("os.arch"));
SelectionAdapter listener = new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (e.widget == button1) {
ut.setContent(Arrays.asList("01", "34", "test", "test2", "123", "1test", "test2"));
} else if (e.widget == button2) {
ut.setContent(Arrays.asList("Str1", "Str2", "Str3"));
} else {
ut.setContent(Collections.emptyList());
}
}
};
button1 = new Button(shell, SWT.PUSH);
button1.setText("Data 1");
button1.addSelectionListener(listener);
button2 = new Button(shell, SWT.PUSH);
button2.setText("Data 2");
button2.addSelectionListener(listener);
button3 = new Button(shell, SWT.PUSH);
button3.setText("Data 3");
button3.addSelectionListener(listener);
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true, 4, 1);
gd.widthHint = gd.heightHint = 320;
ut = new UltraTable(shell, SWT.MULTI | SWT.BORDER | SWT.VIRTUAL | SWT.FULL_SELECTION);
ut.table.setLayoutData(gd);
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
class UltraTable {
private Table table;
private static final String DATA_COLLECTION = "<<CC>>", DATA_LISTENER = "<<VL>>";
public UltraTable(Composite parent, int style) {
table = new Table(parent, style);
table.setLinesVisible(true);
table.setHeaderVisible(true);
TableColumn tableColumn = new TableColumn(table, SWT.NONE);
tableColumn.setText("Column");
tableColumn.setWidth(64);
}
void setContent(Collection<?> collection) {
if ((table.getStyle() & SWT.VIRTUAL) != 0) {
table.setData(DATA_COLLECTION, collection);
table.clearAll();
table.setItemCount(collection.size());
if (table.getData(DATA_LISTENER) == null) {
Listener listenerSD = new Listener() {
public void handleEvent(Event event) {
Collection<?> collectionW = (Collection<?>) event.widget.getData(DATA_COLLECTION);
Object object = collectionW.toArray(new Object[collectionW.size()])[event.index];
((TableItem) event.item).setText(0, object.toString());
}
};
table.setData(DATA_LISTENER, listenerSD);
table.addListener(SWT.SetData, listenerSD);
}
}
}
}
public static void main(String[] args) {
new TableCheck();
}
}
The SWT versions I checked is (as shown in the text in the shell):
SWT win32 3550; Windows 7 6.1 x86
SWT win32 3617; Windows 7 6.1 x86
I have resolved this problem after asking the same question.
You must either remove SWT.VIRTUAL or update to the SVN build of SWT. I've posted a bug report on the SWT bug page.
Edit: your code snippet has a bug in it that is causing the ArrayIndexOutOfBoundsException. You can resolve it by changing lines containing listenerSD:
public void handleEvent(Event event) {
Collection<?> collectionW = (Collection<?>) event.widget
.getData(DATA_COLLECTION);
if (collectionW.size() > event.index) {
Object object = collectionW
.toArray(new Object[collectionW.size()])[event.index];
((TableItem) event.item).setText(0, object
.toString());
}
}
On Windows 7, the table updates the visible items immediately when clearAll() is called. So
table.clearAll();
must be after the line
table.setItemCount(collection.size());

Resources