i have already record saved in database i want that when i click on update button, it get record from database and show that record by default selected and expanded, and also show all other records but not selected and not expanded,
Here is My Model code:
public TreeNode getSelectedEmpMarketsForUpdate(int moID) {
ConnectionHandler conHandler = ConnectionHandler.getConnectionHandler();
Connection con = conHandler.getConnection();
Statement stmt = null;
ArrayList<MarketBean> list = new ArrayList<MarketBean>();
TreeNode root = new DefaultTreeNode(new BasicBean(1, "Root"), null);
root.setExpanded(true);
try {
ResultSet rs = null;
stmt = con.createStatement();
String selectQry = " select x.*,y.market_id as selected_id from (\n"
+ "select a.name as COUNTRY_NAME,a.id as COUNTRY_ID,b.name as ZONE_NAME, b.id as ZONE_ID, c.name as REGION_NAME, \n"
+ "C.ID as REGION_ID, d.name as CITY_NAME, D.ID AS CITY_ID, e.name as AREA_NAME, E.ID AS AREA_ID,f.name as MARKET_NAME, \n"
+ "F.ID AS MARKET_ID, concat(a.name,concat(b.name,concat(c.name,concat(d.name,concat(e.name,f.name))))) as completeName \n"
+ "from country a left outer join zone b on a.id=b.country_id left outer join region c on b.id=c.zone_id \n"
+ "left outer join city d on c.id=d.region_id left outer join area e on d.id=e.city_id \n"
+ "left outer join market f on e.id=f.area_id \n"
+ "where a.name like '%%' OR b.name like '%%' OR c.name like '%%' OR d.name like '%%' OR e.name like '%%' \n"
+ "OR f.name like '%%') x\n"
+ "\n"
+ "LEFT OUTER JOIN\n"
+ "(select F.ID AS MARKET_ID\n"
+ " from country a left outer join zone b \n"
+ " on a.id=b.country_id \n"
+ " left outer join region c \n"
+ " on b.id=c.zone_id \n"
+ " left outer join city d \n"
+ " on c.id=d.region_id \n"
+ " left outer join area e \n"
+ " on d.id=e.city_id \n"
+ " left outer join market f \n"
+ " on e.id=f.area_id \n"
+ " right join mo_market_bridge mb on mb.`MARKET_ID` = f.`ID`\n"
+ " where mb.`MO_ID` = '" + moID + " ' ) y\n"
+ " ON y.market_id=x.market_id";
System.out.println(selectQry);
rs = stmt.executeQuery(selectQry);
TreeMap<String, TreeNode> tm = new TreeMap<String, TreeNode>();
TreeNode country = null;
TreeNode zone = null;
TreeNode region = null;
TreeNode city = null;
TreeNode area = null;
TreeNode market = null;
int i = 0;
while (rs.next()) {
System.out.print(rs.getString("completeName"));
if (rs.getString("COUNTRY_NAME") != null && !tm.containsKey("CN" + rs.getString("COUNTRY_ID"))) {
country = new DefaultTreeNode(new BasicBean(rs.getInt("COUNTRY_ID"), rs.getString("COUNTRY_NAME")), root);
tm.put("CN" + rs.getString("COUNTRY_ID"), country);
if (rs.getBoolean("selected_id")) {
country.setExpanded(true);
country.setSelected(true);
}
}
if (rs.getString("ZONE_NAME") != null && !tm.containsKey("ZN" + rs.getString("ZONE_ID"))) {
zone = new DefaultTreeNode(new BasicBean(rs.getInt("ZONE_ID"), rs.getString("ZONE_NAME")), country);
tm.put("ZN" + rs.getString("ZONE_ID"), zone);
if (rs.getBoolean("selected_id")) {
zone.setExpanded(true);
zone.setSelected(true);
}
}
if (rs.getString("REGION_NAME") != null && !tm.containsKey("RG" + rs.getString("REGION_ID"))) {
region = new DefaultTreeNode(new BasicBean(rs.getInt("REGION_ID"), rs.getString("REGION_NAME")), zone);
tm.put("RG" + rs.getString("REGION_ID"), region);
if (rs.getBoolean("selected_id")) {
region.setExpanded(true);
region.setSelected(true);
}
}
if (rs.getString("CITY_NAME") != null && !tm.containsKey("CT" + rs.getString("CITY_ID"))) {
city = new DefaultTreeNode(new BasicBean(rs.getInt("CITY_ID"), rs.getString("CITY_NAME")), region);
tm.put("CT" + rs.getString("CITY_ID"), city);
if (rs.getBoolean("selected_id")) {
city.setExpanded(true);
city.setSelected(true);
}
}
if (rs.getString("AREA_NAME") != null && !tm.containsKey("AR" + rs.getString("AREA_ID"))) {
area = new DefaultTreeNode(new BasicBean(rs.getInt("AREA_ID"), rs.getString("AREA_NAME")), city);
tm.put("AR" + rs.getString("AREA_ID"), area);
if (rs.getBoolean("selected_id")) {
area.setExpanded(true);
area.setSelected(true);
}
}
if (rs.getString("MARKET_NAME") != null && !tm.containsKey("MK" + rs.getString("MARKET_ID"))) {
if (!rs.getString("MARKET_NAME").contains("MARKET")) {
String marketname = rs.getString("MARKET_NAME") + " MARKET ";
market = new DefaultTreeNode(new BasicBean(rs.getInt("MARKET_ID"), marketname), area);
tm.put("MK" + rs.getString("MARKET_ID"), market);
if (rs.getBoolean("selected_id")) {
market.setExpanded(true);
market.setSelected(true);
}
} else {
market = new DefaultTreeNode(new BasicBean(rs.getInt("MARKET_ID"), rs.getString("MARKET_NAME")), area);
tm.put("MK" + rs.getString("MARKET_ID"), market);
if (rs.getBoolean("selected_id")) {
market.setExpanded(true);
market.setSelected(true);
}
}
}
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException e) {
System.out.println(e);
}
conHandler.freeConnection(con);
}
return root;
}
here is xhtml:
<p:tree value="#{marketMappinBean.allMarketsRoot}"
selectionMode="checkbox"
selection="#{marketMappinBean.selectedNode}"
dynamic="true"
var="node" id="treeNode" animate="true" highlight="true" style="width: auto "
>
<p:treeNode >
<h:outputText value="#{node.name}" />
</p:treeNode>
</p:tree>
here is bean:
MarketMappingModel db = new MarketMappingModel();
selectedMarketsroot = db.getSelectedEmployeeMarketsTree(moID);
by default selected and expanded not working, but all records are showing
Related
The below class is used in an array.
package com.example.ShivitoMGO;
public class RoomTable {
public String RoomName,UpDown,minmaxint;
}
Main Activity
static ArrayList <RoomTable> CountCheck = new ArrayList<>();
public void playerup(View vvv){
st_spinner = v1.findViewById(R.id.spinner);
st_reportLayout = v1.findViewById(R.id.reportlayout);
st_Leanervidimg = v1.findViewById(R.id.Linearvidcopy);
TextView roomname = v1.findViewById(R.id.action_Players1);
RoomTable roomtb = new RoomTable();
if (CountCheck.size() == 0){
//playerupdown = "up";
Toast.makeText(this, "Will notify when " + mRooms.get(position1) + " players increase #" + mRoomSize.get(position1), Toast.LENGTH_LONG).show();
String[] minmaxval = mRoomSize.get(position1).split("/");
CountCheckint = Integer.parseInt(minmaxval[0].trim());
//CountCheck = (String) mRooms.get(position1);
roomtb.RoomName = (String) mRooms.get(position1);
roomtb.minmaxint = minmaxval[0].trim();
roomtb.UpDown = "up";
Log.d("added: ", "it was added");
CountCheck.add(roomtb);
Log.d("RoomTableadd: ",roomtb.RoomName+ " " + roomtb.minmaxint +" " +roomtb.UpDown);
st_reportLayout.setVisibility(View.GONE);
Log.d("Longclickhere: ", mRoomSize.get(position1));
Log.d("RoomNameCount ", String.valueOf(CountCheck.get(0).RoomName));
}else {
int exist1 = 0;
int poss;
for (int i = 0; i < CountCheck.size(); i++) {
if (roomname.getText() == CountCheck.get(i).RoomName) {
Log.d("RoomNametxt: " , CountCheck.get(i).RoomName);
Log.d("RoomNametxt: ", (String) roomname.getText());
Toast.makeText(this, "Notification " + CountCheck.get(i).RoomName + " OFF!", Toast.LENGTH_LONG).show();
Log.d("Removed item: ", String.valueOf(CountCheck.size()));
CountCheck.remove(i);
Log.d("Removed item: ", String.valueOf(CountCheck.size()));
st_reportLayout.setVisibility(View.GONE);
exist1 = 1;
poss = i;
} else {
exist1 = 0;
}
}
if (exist1 == 0) {
Toast.makeText(this, "Will notify when " + mRooms.get(position1) + " players increase #" + mRoomSize.get(position1), Toast.LENGTH_LONG).show();
String[] minmaxval = mRoomSize.get(position1).split("/");
CountCheckint = Integer.parseInt(minmaxval[0].trim());
//CountCheck = (String) mRooms.get(position1);
roomtb.RoomName = (String) mRooms.get(position1);
roomtb.minmaxint = minmaxval[0].trim();
roomtb.UpDown = "up";
Log.d("added: ", "it was added");
CountCheck.add(roomtb);
Log.d("RoomTableadd: ", roomtb.RoomName + " " + roomtb.minmaxint + " " + roomtb.UpDown);
st_reportLayout.setVisibility(View.GONE);
}
Log.d("CountSize: ", String.valueOf(CountCheck.size()));
for (int xb = 0;xb<CountCheck.size();xb++) {
try {
Log.d("RoomNameCount ", String.valueOf(CountCheck.get(xb).RoomName));
} catch (Exception e) {
Log.d("Out of range ", String.valueOf(e));
}
}
}
}
Recycler-View
#Override
public boolean onLongClick(View v) {
// Launch your web intent
if (CountCheck.size() != 0){
Log.d("Longclickhere: ",mRoomSize.get(position));
Toast.makeText(mContext, mRoomSize.get(position), Toast.LENGTH_SHORT).show();
Toast.makeText(mContext, "Will notify when "+mRooms.get(position)+" players decrease", Toast.LENGTH_SHORT).show();
String[] minmaxval = mRoomSize.get(position).split("/");
MainActivity.CountCheckint = Integer.parseInt(minmaxval[0].trim());
} else{
//MainActivity.CountCheck = "";
Toast.makeText(mContext, "Player Decrease notification OFF", Toast.LENGTH_SHORT).show();
}
return true;
In this app the recycler view creates the "rooms" and if the room is selected the textview and 2 other values are put in to the RoomTable. these are stored and used in a service to check if ether of the other to values change. Everything works as intended unless i use the swip-to-refresh witch runs the recycler-view again. If i do not refresh and i select the same item in the recycler-view it will remove it from CountCheck . However if i run the refresh and select the same recycler-view item that i selected previously it will add it instead of removing it. This Makes no since to me because i use a for loop to Check the CountCheck.get(i).RoomName aka the textview and if the names are the same then my if statement will remove instead of add. is it somehow possible i'm ending up with 2 CountCheck Objects????? with the same name???? Please I'm out of ideas on this one. Thanks.
I dont remember why. Maybe someone can explain but i changed this line
if (roomname.getText() == CountCheck.get(i).RoomName)
To this
if (roomname.getText().equals(CountCheck.get(i).RoomName));
and that fixed the issue. please let me know the difference if you are reading this.
My app uses a countdown timer in the background in a class that extends Services. The background running service is designed to access the Sharedpreferences data of the app. During the countdown, a particular integer in the Sharedpreferences changes value and the updated value is expected to be accessed in the onFinish() call of the countdown timer. The problem now is that the Service don't read the updated valued from the Sharedpreferences but rather returns the initial value at the point the background service started.
I saw somewhere that the solution to the problem is to use
PreferenceManager.getDefaultSharedPreferences()
instead of getSharedPrefences to be able access the current SharedPreferences value. I implemented this recommendation but the problem persist.
Please somebody should help me out because trying to figure out this is taking too much of my time.
My code is here:
public class BroadcastService extends Service {
DatabaseHelperClass myDatabase = new DatabaseHelperClass(this);
private SharedPreferences defaultSharedPreferences, sharedPreferences, staffSignedIn;
private SharedPreferences.Editor staffEditor, defaultSharedPreferencesEditor;
int countSignIn;
private SimpleDateFormat simpleDateFormatII;
Long timeLeftInMiliseconds;
private final static String TAG = "BroadcastService";
public static final String COUNTDOWN_BR = "com.cenitscitech.www.etimebook.countdown_br";
Intent bi = new Intent(COUNTDOWN_BR);
CountDownTimer cdt = null;
#Override
public void onCreate() {
super.onCreate();
defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
defaultSharedPreferencesEditor = defaultSharedPreferences.edit();
sharedPreferences = getSharedPreferences("setTime", MODE_PRIVATE);
//staffSignedIn = getSharedPreferences("present", MODE_PRIVATE);
//countSignIn = staffSignedIn.getInt("max", 0);
//staffEditor = staffSignedIn.edit();
simpleDateFormatII = new SimpleDateFormat("MMM EEE dd, yyyy HH:mm");
Log.i(TAG, "Starting timer in broadcast receiver...");
Log.i(TAG, "max Count Obtained onBroadcastCreate: "+defaultSharedPreferences.getInt("max", 0));
}
#Override
public void onDestroy() {
//cdt.cancel();
Log.i(TAG, "Timer in broadcast receiver cancelled");
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
timeLeftInMiliseconds = intent.getLongExtra("timeLeft", 0L);
cdt = new CountDownTimer(timeLeftInMiliseconds, 1000) {
#Override
public void onTick(long millisUntilFinished) {
SharedPreferences defaultShared = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);
/*bi.putExtra("countdown", millisUntilFinished);
sendBroadcast(bi);*/
}
#Override
public void onFinish() {
SharedPreferences defaultSharedPreferences2 = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
countSignIn = defaultSharedPreferences2.getInt("max", 0);
Log.i(TAG, "Timer finished");
bi.putExtra("countdown", "Timer finished");
sendBroadcast(bi);
StringBuilder phoneBuilder = new StringBuilder();
Calendar cStart = Calendar.getInstance();
cStart.set(Calendar.HOUR_OF_DAY, 0);
cStart.set(Calendar.MINUTE, 0);
cStart.set(Calendar.SECOND, 0);
Long cStartLong = cStart.getTimeInMillis();
Calendar cEnd = Calendar.getInstance();
cEnd.set(Calendar.HOUR_OF_DAY, 23);
cEnd.set(Calendar.MINUTE, 59);
cEnd.set(Calendar.SECOND, 59);
Long cEndLong = cEnd.getTimeInMillis();
String[] conditionsElements;
Log.i(TAG + " onFinish", "MAXIMUM COUNT OBTAINED: " + defaultSharedPreferences2.getInt("max", 0));
Log.i(TAG + " onFinish", "MAXIMUM COUNT OBTAINED: " + countSignIn);
if (defaultSharedPreferences2.getInt("max", 0) > 0) {
Log.i(TAG + " onFinish", "CURRENT countSignIn Value: "+countSignIn+"\n"+" max Value: "+defaultSharedPreferences2.getInt("max", 0));
conditionsElements = new String[defaultSharedPreferences2.getInt("max", 0)];
for (int i = 1; i <= defaultSharedPreferences2.getInt("max", 0); i++) {
conditionsElements[i - 1] = defaultSharedPreferences2.getString(Integer.toString(i), "NoElement");
Log.i(TAG + " onFinish", "conditionsElement[" + (i - 1) + "] = " + defaultSharedPreferences2.getString(Integer.toString(i), "NoElement"));
if (i < defaultSharedPreferences2.getInt("max", 0)) {
phoneBuilder.append("MOBILE_NUMBER = ? OR ");
Log.i(TAG + " onFinish", "phoneBuilder[" + (i - 1) + "]: " + phoneBuilder);
//phoneBuilder.append(staffSignedIn.getString(Integer.toString(i), "NoStaff")+"_");
} else if (i == defaultSharedPreferences2.getInt("max", 0)) {
//phoneBuilder.append(staffSignedIn.getString(Integer.toString(i), "NoStaff"));
phoneBuilder.append("MOBILE_NUMBER = ?");
Log.i(TAG + " onFinish", "phoneBuilder[final]: " + phoneBuilder);
}
}
} else {
Log.i(TAG + " onFinishInsideElse", "CURRENT countSignIn Value: "+countSignIn+"\n"+" max Value: "+defaultSharedPreferences2.getInt("max", 0));
conditionsElements = new String[1];
conditionsElements[0] = "NoElement";
phoneBuilder.append("MOBILE_NUMBER = ?");
}
Cursor cursor = myDatabase.queryAbsentStaff(SURNAME_COLUMN + ", " + FIRST_NAME_COLUMN + ", " + MIDDLE_NAME_COLUMN + ", " + MOBILE_NUMBER_COLUMN + ", " + DATE_COLUMN,
SURNAME_COLUMN + ", " + FIRST_NAME_COLUMN + ", " + MIDDLE_NAME_COLUMN + ", " + MOBILE_NUMBER_COLUMN + ", " + DATE_COLUMN,
phoneBuilder.toString(),
conditionsElements);
Log.i(TAG + " onFinish", "\n" + "SET TIMES:" + "\n" + cStartLong + "\n" + cEndLong + "\n" + "RETURNED ROWS:" + "\n" + cursor.getCount());
/*staffEditor.putInt("max", 0);
staffEditor.apply();
for(int i=0; i<staffSignedIn.getInt("totalStaff", 100); i++){
staffEditor.putString(Integer.toString((i+1)), "empty").apply();
}*/
if(cursor.moveToFirst()){
for (int i = 0; i < cursor.getCount(); i++) {
if(myDatabase.insertTimeBookRecord(cursor.getString(cursor.getColumnIndex(SURNAME_COLUMN)), cursor.getString(cursor.getColumnIndex(FIRST_NAME_COLUMN)),
cursor.getString(cursor.getColumnIndex(MIDDLE_NAME_COLUMN)), cursor.getString(cursor.getColumnIndex(MOBILE_NUMBER_COLUMN)),
"ABSENT", Long.toString(System.currentTimeMillis()), 1000000L, "NO", "0000", System.currentTimeMillis(), "notSynced", "notSynced")){
cursor.moveToNext();
if(cursor.isAfterLast()){
cursor.close();
}
}else{
cursor.moveToNext();
if(cursor.isAfterLast()){
cursor.close();
}
}
}
}
Log.i(TAG +" onFinish: ", "max val reset: "+defaultSharedPreferences2.getInt("max", 0));
public double getMinCBQta(long enteCod, long artCod) throws FailureException {
logger.debug("getMinCBqta() - ENTER");
double minCBQta = 0;
final TypedQuery<Double> query = em.createQuery("select NVL(Min(c.qtaCapienza),0) " + "from CapienzaBanco c "
+ "where c.id.enteCod = :ENTECOD AND c.id.artCod = :ARTCOD "
+ "AND c.id.nrPromo = 0 AND c.id.annoPromo = 0 AND c.qtaCapienza!= 0 ", Double.class);
try {
query.setParameter(CommonConstants.ENTECOD, enteCod);
query.setParameter(CommonConstants.ARTCOD, artCod);
minCBQta = query.getSingleResult();
} catch (final NoResultException ne) {
logger.warn("getMinCBQta :No result received from CAPIENZA_BANCO with enetCod " + enteCod + "artCod: " + artCod);
} catch (final Exception e) {
logger.error("getMinCBQta : Error Retriving data from CAPIENZA_BANCO " + e.getMessage());
throw new FailureException("getMinCBQta : Error Retriving data from CAPIENZA_BANCO " + e);
}
logger.debug("getMinCBqta()" + " EXIT");
return minCBQta;
}
In Java 8, the Container class has an void add(Component comp, Object constraints) method that adds the component with a constraints information. I want to build a GUI with three panels, where pressing a button would result in switching the constraint information of the components that do not include the button object. How is it possible to switch the constraint information?
EDIT:
I tried the following:
private Map<SpecUITitlePanel, GridBagConstraints> constraints = new Hashtable<SpecUITitlePanel, GridBagConstraints>();
[…]
switchPanelsButton.setText( "Switch panels");
switchPanelsButton.addActionListener( new java.awt.event.ActionListener() {
public void actionPerformed( final java.awt.event.ActionEvent event) {
switchPanelsActionPerformed( event);
}
[…]
private void switchPanelsActionPerformed( final java.awt.event.ActionEvent event) {
boolean swapped = false;
final GridBagLayout layout = (GridBagLayout) getLayout();
final Iterator<SpecUITitlePanel> keysIter = constraints.keySet().iterator();
// summaryPanel, testPanel
while (keysIter.hasNext() && layout != null) {
final SpecUITitlePanel key = keysIter.next();
final String title = key.getTitle();
final Iterator<SpecUITitlePanel> keysIter2 = constraints.keySet().iterator();
while (keysIter2.hasNext()) {
final SpecUITitlePanel key2 = keysIter2.next();
final String title2 = key2.getTitle();
if (!title.equals( title2)) {
if (!title.contains( BUTTON_PANEL_TITLE) && !title2.contains( BUTTON_PANEL_TITLE)) {
// swap components
String message = "component = " + title + ", "
+ constraints.get( key) + "; component2 = " + title2
+ ", " + constraints.get( key2);
System.out.println( message);
final GridBagConstraints value = constraints.get( key);
final GridBagConstraints value2 = constraints.get( key2);
constraints.put(key, value2);
layout.setConstraints( key, value2);
constraints.put(key2, value);
layout.setConstraints( key2, value);
swapped = true;
message = "component = " + title + ", "
+ constraints.get( key) + "; component2 = " + title2
+ ", " + constraints.get( key2);
System.out.println( message);
}
}
}
}
if (swapped) {
repaint();
}
}
The relevant part of the output is
component = Test, java.awt.GridBagConstraints#5179288b; component2 = tna.rads.main_panel.violation_summary_panel, java.awt.GridBagConstraints#f1a7ed2
component = Test, java.awt.GridBagConstraints#f1a7ed2; component2 = tna.rads.main_panel.violation_summary_panel, java.awt.GridBagConstraints#5179288b
When I execute the code I developed to call an Async method of the linq2Twitter, I am getting a System.Aggregate Exception, the code is below:
static async Task<List<myTwitterStatus>> getRetweets(ulong tweetID, TwitterContext twitterCtx)
{
List<myTwitterStatus> reTweets = new List<myTwitterStatus>();
var publicTweets =
await
(from tweet in twitterCtx.Status
where tweet.Type == StatusType.Retweets &&
tweet.ID == tweetID
select tweet)
.ToListAsync();
if (publicTweets != null)
publicTweets.ForEach(tweet =>
{
if (tweet != null && tweet.User != null)
{
myTwitterStatus tempStatus = new myTwitterStatus();
tempStatus.Country = tweet.Place.Country;
tempStatus.createdAt = tweet.CreatedAt;
tempStatus.FavoriteCount = long.Parse(tweet.FavoriteCount.ToString());
tempStatus.ID = tweet.ID;
tempStatus.isTruncated = tweet.Truncated;
tempStatus.Lang = tweet.Lang;
tempStatus.MaxID = tweet.MaxID;
tempStatus.PlaceFullname = tweet.Place.FullName;
tempStatus.RetweetCount = tweet.RetweetCount;
tempStatus.ScreenName = tweet.ScreenName;
tempStatus.Text = tweet.Text;
tempStatus.UserFriends = tweet.User.FriendsCount;
tempStatus.UserCreated = tweet.User.CreatedAt;
tempStatus.UserFollowers = tweet.User.FollowersCount;
tempStatus.UserFavorities = tweet.User.FavoritesCount;
tempStatus.UserFriends = tweet.User.FriendsCount;
tempStatus.UserLocation = tweet.User.Location;
tempStatus.UserName = tweet.User.Name;
tempStatus.UserTweetCount = tweet.User.StatusesCount;
reTweets.Add(tempStatus);
}
});
return reTweets;
}
The issue is when I called the method
var authorizer = new SingleUserAuthorizer
{
CredentialStore = new InMemoryCredentialStore
{
ConsumerKey = SM.Default.Consumer_key2.ToString(),
ConsumerSecret = SM.Default.Consumer_secret2.ToString(),
OAuthToken = SM.Default.Access_token2.ToString(),
OAuthTokenSecret = SM.Default.Access_secret2.ToString()
}
};
TwitterContext twitterCtx = new TwitterContext(authorizer);
Task<List<myTwitterStatus>> task = Task<List<myTwitterStatus>>.Factory.StartNew(() => getRetweets(ulong.Parse(tweet.StringId), twitterCtx).Result);
task.Wait();
List<myTwitterStatus> tempList = task.Result.ToList<myTwitterStatus>();
foreach (var ret in tempList)
{
un = file.RemoveSpecialCharacters(ret.UserName);
sn = file.RemoveSpecialCharacters(ret.ScreenName);
tweets.AppendLine(account + "," + getWE(ret.createdAt) + "," + Text + "," + un + "," + sn + "," + ret.createdAt + "," +
file.RemoveSpecialCharacters(ret.UserLocation) + ",,,1,," + ret.UserTweetCount + "," +
ret.RetweetCount + "," + ret.FavoriteCount + "," + ret.UserFollowers);
I would appreciate any kind of assistance about it, I have no idea how to solve it.
Can you add a try/catch so see what the inner exception is.
try
{
//Perform your operation here
}
catch (AggregateException aex)
{
//Dive into inner exception
}
Thanks to all for the help, I activate the breakpoints for the specific exception and an additional validation was added, the issue was not in the async process, it was because it was trying to handle a null as an string, to hendle this error this line was modified sn = file.RemoveSpecialCharacters(ret.ScreenName ?? string.Empty);
The full code is below:
private void getRetweets(TwitterStatus tweet)
{
Text = file.RemoveSpecialCharacters(tweet.Text);
tweetID = tweet.StringId;
#region Get retweets
RetweetsOptions retOpt = new RetweetsOptions();
if (int.Parse(tweet.RetweetCountString.ToString()) > 1)
retOpt.Count = int.Parse(tweet.RetweetCountString.ToString()) + 1;
else
retOpt.Count = 1;
String errorText = "";
DateTime fromDate, toDate;
if (radDate.Checked == true)
{
fromDate = dtpFrom.Value;
toDate = dtpTo.Value;
}
else
{
fromDate = tweet.CreatedDate;
toDate = DateTime.Now;
}
TwitterResponse<TwitterStatusCollection> retweet = null;
if (int.Parse(tweet.RetweetCountString.ToString()) > 100)
{
var authorizer = new SingleUserAuthorizer
{
CredentialStore = new InMemoryCredentialStore
{
ConsumerKey = SM.Default.Consumer_key2.ToString(),
ConsumerSecret = SM.Default.Consumer_secret2.ToString(),
OAuthToken = SM.Default.Access_token2.ToString(),
OAuthTokenSecret = SM.Default.Access_secret2.ToString()
}
};
TwitterContext twitterCtx = new TwitterContext(authorizer);
//HELPER: https://www.youtube.com/watch?v=IONqMWGn9-w
try
{
Task<List<myTwitterStatus>> task = null;
Parallel.Invoke(
() =>
{
task = getRetweets(ulong.Parse(tweet.StringId), twitterCtx);
while (!task.IsCompleted)
{
Thread.Sleep(250);
}
});
List<myTwitterStatus> tempList = task.Result.ToList<myTwitterStatus>();
foreach (var ret in tempList)
{
un = file.RemoveSpecialCharacters(ret.UserName);
sn = file.RemoveSpecialCharacters(ret.ScreenName ?? string.Empty);
tweets.AppendLine(account + "," + getWE(ret.createdAt) + "," + Text + "," + un + "," + sn + "," + ret.createdAt + "," +
file.RemoveSpecialCharacters(ret.UserLocation) + ",,,1,," + ret.UserTweetCount + "," +
ret.RetweetCount + "," + ret.FavoriteCount + "," + ret.UserFollowers);
}
}catch(Exception ex){
Console.WriteLine("Error: " + ex.Message+ Environment.NewLine + ex.StackTrace);
}
return;
}
else
retweet= TwitterStatus.Retweets(tokensRet, Decimal.Parse(tweet.Id.ToString()), retOpt);
if (retweet.Result.ToString() == "Success" && retweet.ResponseObject.Count > 0 && retweet!=null)
{
int retPages = int.Parse(tweet.RetweetCountString.ToString()) + 1 / 20;
for (int page = 0; page <= retPages; page++)
{
try
{
//List<TwitterStatus> retList = new List<TwitterStatus>(retweet.ResponseObject.Page = page);
retweet.ResponseObject.Page = page;
List<TwitterStatus> retList = retweet.ResponseObject.ToList<TwitterStatus>();
foreach (var ret in retList)
{
try
{
if (ret.CreatedDate.CompareTo(fromDate) >= 0 && ret.CreatedDate.CompareTo(toDate) <= 0)
{
#region Get UN Sync
getUN(ret, ref un, ref sn);
#endregion
tweets.AppendLine(account + "," + getWE(ret.CreatedDate) + "," + Text + "," + un + "," + sn + "," + ret.CreatedDate + "," +
file.RemoveSpecialCharacters(ret.User.Location.ToString()) + ",,,1,," + ret.User.NumberOfStatuses.ToString() + "," +
ret.RetweetCount + "," + ret.User.NumberOfFavorites.ToString() + "," + ret.User.NumberOfFollowers.ToString());
}
else if (tweet.CreatedDate.CompareTo(toDate) <= 0)//if the tweet's created date is lower than the from's date, exits the loop
break;
}
catch (NullReferenceException ex)
{
errorText = ex.Source + Environment.NewLine + ex.StackTrace;
continue;
}
}
}
catch (Exception ex)
{
errorText = ex.Source + Environment.NewLine + ex.StackTrace;
//MessageBox.Show(ex.Message + Environment.NewLine + "Rate Limit was reached!" + Environment.NewLine +
// "Wait an hour or try a shorter date range", "Rate Limit Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
else if (error == false && retweet.Result.ToString() != "Success")
{
errorText = retweet.Result.ToString();
MessageBox.Show("Retweets: Something went wrong!" + Environment.NewLine + errorText, "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
error = true;
}
#endregion
}