Search Results

Search found 1382 results on 56 pages for 'async await'.

Page 8/56 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • Silverlight async calls and anonymous methods....

    - by JLewis
    I know there are a couple of debates on this kind of thing.... At any rate, I have several cases where I need to populate combobox items based on enumerations returned from the WCF service. In an effort to keep code clean, I started this approach. After looking into it more, I don't think the this works as well is initially thought... I am throwing this out to get recommendations/advice/code snippets on how you would do this or how you currently do this. I may be forced to have a seperate, non anonymous method, procedure. I hate doing this for something like this but at the moment, don't see it working another way... EventHandler<GetEnumerationsForTypeCompletedEventArgs> ev = null; ev = delegate(object eventSender, GetEnumerationsForTypeCompletedEventArgs eventArgs) { if (eventArgs.Error == null) { //comboBox.ItemsSource = eventArgs.Result; // populate combox for display purposes (for now) foreach (Enumeration e in eventArgs.Result) { ComboBoxItem cbi = new ComboBoxItem(); cbi.Content = e.EnumerationValueDisplayed; comboBox.Items.Add(cbi); } // remove event so we don't keep adding new events each time we need an enumeration proxy.GetEnumerationsForTypeCompleted -= ev; } }; proxy.GetEnumerationsForTypeCompleted += ev; proxy.GetEnumerationsForTypeAsync(sEnumerationType); Basically in this example we use ev to hold the anonymous method so we can then use ev from within the method to remove it from the events once called. This prevents this method from getting called more than one time. I suspect that the comboBox local var declared before this call, but within the same method, is not always the combobox originally intended but can't really verify that yet. I may add a tag to it to do some tests and populating to verify. Sorry if this is not clear. I can elaborate more if needed. Thanks Jeff

    Read the article

  • C++ Winsock non-blocking/async UDP socket

    - by Ragnagard
    Hi all! I'm developping a little data processor in c++ over UDP sockets, and have a thread (just one, and apart the sockets) that process the info received from them. My problem happens when i need to receive info from multiple clients in the socket at the same time. How could i do something like: Socket foo; /* init socket vars and attribs */ while (serving){ thread_processing(foo_info); } for multiple clients (many concurrent access) in c++? I'm using winsocks atm on win32, but just get standard blocking udp sockets working. No gui, it's a console app. I'll appreciate so much an example or pointer to one ;). Thanks in advance.

    Read the article

  • Calculate time of method execution and send to WCF service async

    - by Tim
    I need to implement time calculation for repository methods in my asp .net mvc project classes. The problem is that i need to send time calculation data to WCF Service which is time consuming. I think about threads which can help to cal WCF service asynchronously. But I have very little experience with it. Do I need to create new thread each time or I can create a global thread, if so then how? I have something like that: StopWatch class public class StopWatch { private DateTime _startTime; private DateTime _endTime; public void Start() { _startTime = DateTime.Now; } protected void StopTimerAndWriteStatistics() { _endTime = DateTime.Now; TimeSpan timeResult = _endTime - _startTime; //WCF proxy object var reporting = AppServerUtility.GetProxy<IReporting>(); //Send data to server reporting.WriteStatistics(_startTime, _endTime, timeResult, "some information"); } public void Stop() { //Here is the thread I have question with var thread = new Thread(StopTimerAndWriteStatistics); thread.Start(); } } Using of StopWatch class in Repository public class SomeRepository { public List<ObjectInfo> List() { StopWatch sw = new StopWatch(); sw.Start(); //performing long time operation sw.Stop(); } } What am I doing wrong with threads?

    Read the article

  • Async file uploads in Firefox reset on any DOM change

    - by Vibhu
    I'm pretty sure this is a Firefox or flash-related bug, but I just want to check if anyone has ran into this problem or knows how to fix it. Basically, we have a multi-file upload widget for our highly dynamic web app (think Gmail). We've tried both uploadify for jQuery, and YUI uploader. We've also tried taking those out of our app interface and putting them in an iFrame. What happens is that in the event of any DOM manipulation, even if the uploader is in an iFrame, be it a tab change (in our web app) that covers the iframe temporarily, or a block, etc., the uploader will stop its current upload. In the case of YUI uploader, it fires the "contentReady" event again. This ONLY happens in Firefox. IE and Chrome are fine. In case you are wondering, we really don't have any custom needs here. Just need to have multi-upload file support, and we need to give people free reign to tab around in our interface while an upload is in progress. It seems like Yahoo! and Gmail have both solved this problem. How? What are we doing wrong?

    Read the article

  • Raise event from http listener (Async listener handler)

    - by Sean
    Hello, I have created an simple web server, leveraging .NET HttpListener class. I am using ThreadPool.QueueUserWorkItem() to spawn a thread to listen to incoming requests. Threaded method uses HttpListener.BeginGetContext(callback, listener), and in callback method I resume with HttpListener.EndGetContext() as well as raise an even to notify UI that listener received data. This is the question - how to raise that event? Initially I used ThreadPool: ThreadPool.QueueUserWorkItem(state => ReceivedRequest(httpListenerContext, receivedRequestArgs)); But then started to doubt, maybe it should be a dedicated thread (as appose to waiting for a thread from pool): new Thread(() => ReceivedRequest(httpListenerContext, receivedRequestArgs)).Start(); Thoughts? 10X

    Read the article

  • Asp.Net MVC and ajax async callback execution order

    - by lrb
    I have been sorting through this issue all day and hope someone can help pinpoint my problem. I have created a "asynchronous progress callback" type functionality in my app using ajax. When I strip the functionality out into a test application I get the desired results. See image below: Desired Functionality When I tie the functionality into my single page application using the same code I get a sort of blocking issue where all requests are responded to only after the last task has completed. In the test app above all request are responded to in order. The server reports a ("pending") state for all requests until the controller method has completed. Can anyone give me a hint as to what could cause the change in behavior? Not Desired Desired Fiddler Request/Response GET http://localhost:12028/task/status?_=1383333945335 HTTP/1.1 X-ProgressBar-TaskId: 892183768 Accept: */* X-Requested-With: XMLHttpRequest Referer: http://localhost:12028/ Accept-Language: en-US Accept-Encoding: gzip, deflate User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0) Connection: Keep-Alive DNT: 1 Host: localhost:12028 HTTP/1.1 200 OK Cache-Control: private Content-Type: text/html; charset=utf-8 Vary: Accept-Encoding Server: Microsoft-IIS/8.0 X-AspNetMvc-Version: 3.0 X-AspNet-Version: 4.0.30319 X-SourceFiles: =?UTF-8?B?QzpcUHJvamVjdHNcVEVNUFxQcm9ncmVzc0Jhclx0YXNrXHN0YXR1cw==?= X-Powered-By: ASP.NET Date: Fri, 01 Nov 2013 21:39:08 GMT Content-Length: 25 Iteration completed... Not Desired Fiddler Request/Response GET http://localhost:60171/_Test/status?_=1383341766884 HTTP/1.1 X-ProgressBar-TaskId: 838217998 Accept: */* X-Requested-With: XMLHttpRequest Referer: http://localhost:60171/Report/Index Accept-Language: en-US Accept-Encoding: gzip, deflate User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0) Connection: Keep-Alive DNT: 1 Host: localhost:60171 Pragma: no-cache Cookie: ASP.NET_SessionId=rjli2jb0wyjrgxjqjsicdhdi; AspxAutoDetectCookieSupport=1; TTREPORTS_1_0=CC2A501EF499F9F...; __RequestVerificationToken=6klOoK6lSXR51zCVaDNhuaF6Blual0l8_JH1QTW9W6L-3LroNbyi6WvN6qiqv-PjqpCy7oEmNnAd9s0UONASmBQhUu8aechFYq7EXKzu7WSybObivq46djrE1lvkm6hNXgeLNLYmV0ORmGJeLWDyvA2 HTTP/1.1 200 OK Cache-Control: private Content-Type: text/html; charset=utf-8 Vary: Accept-Encoding Server: Microsoft-IIS/8.0 X-AspNetMvc-Version: 4.0 X-AspNet-Version: 4.0.30319 X-SourceFiles: =?UTF-8?B?QzpcUHJvamVjdHNcSUxlYXJuLlJlcG9ydHMuV2ViXHRydW5rXElMZWFybi5SZXBvcnRzLldlYlxfVGVzdFxzdGF0dXM=?= X-Powered-By: ASP.NET Date: Fri, 01 Nov 2013 21:37:48 GMT Content-Length: 25 Iteration completed... The only difference in the two requests headers besides the auth tokens is "Pragma: no-cache" in the request and the asp.net version in the response. Thanks Update - Code posted (I probably need to indicate this code originated from an article by Dino Esposito ) var ilProgressWorker = function () { var that = {}; that._xhr = null; that._taskId = 0; that._timerId = 0; that._progressUrl = ""; that._abortUrl = ""; that._interval = 500; that._userDefinedProgressCallback = null; that._taskCompletedCallback = null; that._taskAbortedCallback = null; that.createTaskId = function () { var _minNumber = 100, _maxNumber = 1000000000; return _minNumber + Math.floor(Math.random() * _maxNumber); }; // Set progress callback that.callback = function (userCallback, completedCallback, abortedCallback) { that._userDefinedProgressCallback = userCallback; that._taskCompletedCallback = completedCallback; that._taskAbortedCallback = abortedCallback; return this; }; // Set frequency of refresh that.setInterval = function (interval) { that._interval = interval; return this; }; // Abort the operation that.abort = function () { // if (_xhr !== null) // _xhr.abort(); if (that._abortUrl != null && that._abortUrl != "") { $.ajax({ url: that._abortUrl, cache: false, headers: { 'X-ProgressBar-TaskId': that._taskId } }); } }; // INTERNAL FUNCTION that._internalProgressCallback = function () { that._timerId = window.setTimeout(that._internalProgressCallback, that._interval); $.ajax({ url: that._progressUrl, cache: false, headers: { 'X-ProgressBar-TaskId': that._taskId }, success: function (status) { if (that._userDefinedProgressCallback != null) that._userDefinedProgressCallback(status); }, complete: function (data) { var i=0; }, }); }; // Invoke the URL and monitor its progress that.start = function (url, progressUrl, abortUrl) { that._taskId = that.createTaskId(); that._progressUrl = progressUrl; that._abortUrl = abortUrl; // Place the Ajax call _xhr = $.ajax({ url: url, cache: false, headers: { 'X-ProgressBar-TaskId': that._taskId }, complete: function () { if (_xhr.status != 0) return; if (that._taskAbortedCallback != null) that._taskAbortedCallback(); that.end(); }, success: function (data) { if (that._taskCompletedCallback != null) that._taskCompletedCallback(data); that.end(); } }); // Start the progress callback (if any) if (that._userDefinedProgressCallback == null || that._progressUrl === "") return this; that._timerId = window.setTimeout(that._internalProgressCallback, that._interval); }; // Finalize the task that.end = function () { that._taskId = 0; window.clearTimeout(that._timerId); } return that; };

    Read the article

  • WCF Service method syncronous/async

    - by Rafal
    Hi I have a problem withi calling WCF Service methods vs Silverlight 3. ` private bool usr_OK = false; clientService.CheckUserMailAsync(this.mailTF.Text); if (usr_OK == true) { isValidationOK = true; } else { isValidationOK = false; MessageBox.Show("User already exists.", "User registered succes!", MessageBoxButton.OK); } ` CheckUserMail should change usr_OK parameter. However it runs in other thread and it does not change the usr_OK param before IF block begins. I've tried thread.join byt the application freezed and i do not know what to do else. Please help me...how can i wait for WCF method to return param usr_OK.

    Read the article

  • WCF Service method synchronous/async

    - by Rafal
    Hi I have a problem with calling WCF Service methods with Silverlight 3. private bool usr_OK = false; clientService.CheckUserMailAsync(this.mailTF.Text); if (usr_OK == true) { isValidationOK = true; } else { isValidationOK = false; MessageBox.Show("User already exists.", "User registered succes!", MessageBoxButton.OK); } CheckUserMail should change usr_OK parameter. However it runs in other thread and it does not change the usr_OK param before IF block begins. I've tried thread.join byt the application freezed and i do not know what to do else. Please help me...how can i wait for WCF method to return param usr_OK.

    Read the article

  • Why my async call does not work?

    - by Petr
    Hi, I am trying to understand what is IAsyncresult good and therefore I wrote this code. The problem is it behaves as I called "MetodaAsync" normal way. While debugging, the program stops here until the method completed. Any help appreciated, thank you. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ConsoleApplication1 { class Program { delegate int Delegat(); static void Main(string[] args) { Program p=new Program(); Delegat d = new Delegat(p.MetodaAsync); IAsyncResult a = d.BeginInvoke(null, null); //I have removed callback int returned=d.EndInvoke(a); Console.WriteLine("AAA"); } private int MetodaAsync() { int AC=0; for (int I = 0; I < 600000; I++) { for (int A = 0; A < 6000000; A++) { } Console.Write("B"); } return AC; } } }

    Read the article

  • Async call Objective C iphone

    - by Sam
    Hi guys, I'm trying to get data from a website- xml. Everything works fine. But the UIButton remains pressed until the xml data is returned and thus if theres a problem with the internet service, it cant be corrected and the app is virtually unusable. here are the calls: { AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; if(!appDelegate.XMLdataArray.count > 0){ [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; [appDelegate GetApps]; //function that retrieves data from Website and puts into the array - XMLdataArray. } XMLViewController *controller = [[XMLViewController alloc] initWithNibName:@"MedGearsApps" bundle:nil]; [self.navigationController pushViewController:controller animated:YES]; [controller release]; } It works fine, but how can I make the view buttons functional with getting stuck. In other words, I just want the UIButton and other UIButtons to be functional whiles the thing works in the background. I heard about performSelectorInMainThread but i cant put it to practice correctly any help is appreciated :)

    Read the article

  • Lightweight messaging (async invocations) in Java

    - by Sergey Mikhanov
    I am looking for lightweight messaging framework in Java. My task is to process events in a SEDA’s manner: I know that some stages of the processing could be completed quickly, and others not, and would like to decouple these stages of processing. Let’s say I have components A and B and processing engine (be this container or whatever else) invokes component A, which in turn invokes component B. I do not care if execution time of component B will be 2s, but I do care if execution time of component A is below 50ms, for example. Therefore, it seems most reasonable for component A to submit a message to B, which B will process at the desired time. I am aware of different JMS implementations and Apache ActiveMQ: they are too heavyweight for this. I searched for some lightweight messaging (with really basic features like messages serialization and simplest routing) to no avail. Do you have anything to recommend in this issue?

    Read the article

  • multi-thread in MS Access, async processing

    - by LanguaFlash
    I know that title sounds crazy but here is my situation. After a certain user event I need to update a couple tables that are "unrelated" to what the user is currently doing. Currently this takes a couple seconds to execute and causes the user a certain amount of frustration. Is there a way to perform my update in a second process or in a manner that doesn't "freeze" the UI of my app while it is processing? Thanks

    Read the article

  • Problem Executing Async Web Request

    - by davidhayes
    Hi Can anyone tell me what I've done wrong with this simple code? When I run it it hangs on using (Stream postStream = request.EndGetRequestStream(asynchronousResult)) If I comment out the requestState.Wait.WaitOne(); line the code executes correctly but obviously doesn't wait for the response. I'm guessing the the call to EndGetRequestStream is somehow returning me to the context of the main thread?? I'm pretty sure my code is essentially the same as the sample though (MSDN Documentation) using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.IO; using System.Text; namespace SBRemoteClient { public class JSONClient { public string ExecuteJSONQuery(string url, string query) { System.Uri uri = new Uri(url); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.Method = "POST"; request.Accept = "application/json"; byte[] requestBytes = Encoding.UTF8.GetBytes(query); RequestState requestState = new RequestState(request, requestBytes); IAsyncResult resultRequest = request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), requestState); requestState.Wait.WaitOne(); IAsyncResult resultResponse = (IAsyncResult)request.BeginGetResponse(new AsyncCallback(GetResponseStreamCallback), requestState); requestState.Wait.WaitOne(); return requestState.Response; } private static void GetRequestStreamCallback(IAsyncResult asynchronousResult) { try { RequestState requestState = (RequestState)asynchronousResult.AsyncState; HttpWebRequest request = requestState.Request; using (Stream postStream = request.EndGetRequestStream(asynchronousResult)) { postStream.Write(requestState.RequestBytes, 0, requestState.RequestBytes.Length); } requestState.Wait.Set(); } catch (Exception e) { Console.Out.WriteLine(e); } } private static void GetResponseStreamCallback(IAsyncResult asynchronousResult) { RequestState requestState = (RequestState)asynchronousResult.AsyncState; HttpWebRequest request = requestState.Request; using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult)) { using (Stream responseStream = response.GetResponseStream()) { using (StreamReader streamRead = new StreamReader(responseStream)) { requestState.Response = streamRead.ReadToEnd(); requestState.Wait.Set(); } } } } } }

    Read the article

  • WCF Async callback setup for polled device

    - by Mark Pim
    I have a WCF service setup to control a USB fingerprint reader from our .Net applications. This works fine and I can ask it to enroll users and so on. The reader allows identification (it tells you that a particular user has presented their finger, as opposed to asking it to verify that a particular user's finger is present), but the device must be constantly polled while in identification mode for its status - when a user is detected the status changes. What I want is for an interested application to notify the service that it wants to know when a user is identified, and provide a callback that gets triggered when this happens. The WCF service will return immediately and spawn a thread in the background to continuously poll the device. This polling could go on for hours at a time if no one tries to log in. What's the best way to acheive this? My service contract is currently defined as follows: [ServiceContract (CallbackContract=typeof(IBiometricCallback))] public interface IBiometricWcfService { ... [OperationContract (IsOneWay = true)] void BeginIdentification(); ... } public interface IBiometricCallback { ... [OperationContract(IsOneWay = true)] void IdentificationFinished(int aUserId, string aMessage, bool aSuccess); ... } In my BeginIdentification() method can I easily spawn a worker thread to poll the device, or is it easier to make the WCF service asynchronous?

    Read the article

  • Async networking + threading problem

    - by randallmeadows
    I kick off a network request, assuming no login credentials are required to talk to the destination server. If they are required, then I get an authentication challenge, at which point I display a view requesting said credentials from the user. When they are supplied, I restart the network request, using those credentials. That's all fine and dandy, as long as I only do one request at a time. But I'm not, typically. When both requests are kicked off, I get the first challenge, and present the prompt (using -presentModalViewController:). Then the 2nd challenge comes in. And I crash when it tries to display the 2nd prompt. I have the bulk of this wrapped in an @synchronized() block, but this has no effect because these delegate methods are all being called on the same (main) thread. The docs say the delegate methods are called on the same thread in which the connection was started. OK, no problem; I'll just write a method that I run on a background thread using -performSelectorInBackground: NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO]; [connections addObject:connection]; [self performSelectorInBackground:@selector(startConnection:) withObject:connection]; [connection release]; - (void)startConnection:(NSURLConnection *)connection { NSAutoreleasePool *pool = [NSAutoreleasePool new]; [connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [connection start]; [pool drain]; } which should put every network request, and its callbacks, on its own thread, and then my @synchronized() blocks will take effect. The docs for -initWithRequest:... state "Messages to the delegate will be sent on the thread that calls this method. By default, for the connection to work correctly the calling thread’s run loop must be operating in the default run loop mode." Ok, I'm doing that. They also state "If you pass NO [for startImmediately], you must schedule the connection in a run loop before starting it." OK, I'm doing that, too. Furthermore, the docs for NSRunLoop state "Each NSThread object, including the application’s main thread, has an NSRunLoop object automatically created for it as needed. If you need to access the current thread’s run loop, you do so with the class method currentRunLoop." I'm assuming this applies to the background thread created by the call -performSelectorInBackground... (which does appear to be the case, when I execute 'po [NSClassFromString(@"NSRunLoop") currentRunLoop]' in the -startConnection: method). The -startConnection: method is indeed being called. But after kicking off the connection, I now never get any callbacks on it. None of the -connectionDid… delegate methods. (I even tried explicitly starting the thread's run loop, but that made no difference; I've used threads like this before, and I've never had to start the run loop manually before--but I'm now grasping at straws...) I think I've come up with a workaround such that I only handle one request at a time, but it's kludgy and I'd like to do this the Right Way. But, what am I missing here? Thanks! randy

    Read the article

  • On screen orientation loads again data with Async Task

    - by Zookey
    I make Android application with master/detail pattern. So I have ListActivity class which is FragmentActivity and ListFragment class which is Fragment It all works perfect, but when I change screen orientation it calls again AsyncTask and reload all data. Here is the code for ListActivity class where I handle all logic: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list); getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); getActionBar().setTitle("Dnevni horoskop"); if(findViewById(R.id.details_container) != null){ //Tablet mTwoPane = true; //Fragment stuff FragmentManager fm = getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); DetailsFragment df = new DetailsFragment(); ft.add(R.id.details_container, df); ft.commit(); } pb = (ProgressBar) findViewById(R.id.pb_list); tvNoConnection = (TextView) findViewById(R.id.tv_no_internet); ivNoConnection = (ImageView) findViewById(R.id.iv_no_connection); list = (GridView) findViewById(R.id.gv_list); if(mTwoPane == true){ list.setNumColumns(1); //list.setPadding(16,16,16,16); } adapter = new CustomListAdapter(); list.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { pos = position; if(mTwoPane == false){ Bundle bundle = new Bundle(); bundle.putSerializable("zodiac", zodiacFeed); Intent i = new Intent(getApplicationContext(), DetailsActivity.class); i.putExtra("position", position); i.putExtras(bundle); startActivity(i); overridePendingTransition(R.anim.right_in, R.anim.right_out); } else if(mTwoPane == true){ DetailsFragment fragment = (DetailsFragment) getSupportFragmentManager().findFragmentById(R.id.details_container); fragment.setHoroscopeText(zodiacFeed.getItem(position).getText()); fragment.setLargeImage(zodiacFeed.getItem(position).getLargeImage()); fragment.setSign("Dnevni horoskop - "+zodiacFeed.getItem(position).getName()); fragment.setSignDuration(zodiacFeed.getItem(position).getDuration()); // inflate menu from xml /*if(menu != null){ MenuItem item = menu.findItem(R.id.share); Toast.makeText(getApplicationContext(), item.getTitle().toString(), Toast.LENGTH_SHORT).show(); }*/ } } }); if(!Utils.isConnected(getApplicationContext())){ pb.setVisibility(View.GONE); tvNoConnection.setVisibility(View.VISIBLE); ivNoConnection.setVisibility(View.VISIBLE); } //Calling AsyncTask to load data Log.d("TAG", "loading"); HoroscopeAsyncTask task = new HoroscopeAsyncTask(pb); task.execute(); } @Override public void onConfigurationChanged(Configuration newConfig) { // TODO Auto-generated method stub super.onConfigurationChanged(newConfig); } class CustomListAdapter extends BaseAdapter { private LayoutInflater layoutInflater; public CustomListAdapter() { layoutInflater = (LayoutInflater) getBaseContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE); } public int getCount() { // TODO Auto-generated method stub // Set the total list item count return names.length; } public Object getItem(int arg0) { // TODO Auto-generated method stub return null; } public long getItemId(int arg0) { // TODO Auto-generated method stub return 0; } public View getView(int position, View convertView, ViewGroup parent) { // Inflate the item layout and set the views View listItem = convertView; int pos = position; zodiacItem = zodiacList.get(pos); if (listItem == null && mTwoPane == false) { listItem = layoutInflater.inflate(R.layout.list_item, null); } else if(mTwoPane == true){ listItem = layoutInflater.inflate(R.layout.tablet_list_item, null); } // Initialize the views in the layout ImageView iv = (ImageView) listItem.findViewById(R.id.iv_horoscope); iv.setScaleType(ScaleType.CENTER_CROP); TextView tvName = (TextView) listItem.findViewById(R.id.tv_zodiac_name); TextView tvDuration = (TextView) listItem.findViewById(R.id.tv_duration); iv.setImageResource(zodiacItem.getImage()); tvName.setText(zodiacItem.getName()); tvDuration.setText(zodiacItem.getDuration()); Animation animation = AnimationUtils.loadAnimation(getBaseContext(), R.anim.push_up); listItem.startAnimation(animation); animation = null; return listItem; } } private void getHoroscope() { String urlString = "http://balkanandroid.com/download/horoskop/examples/dnevnihoroskop.php"; try { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(urlString); HttpResponse response = client.execute(post); resEntity = response.getEntity(); response_str = EntityUtils.toString(resEntity); if (resEntity != null) { Log.i("RESPONSE", response_str); runOnUiThread(new Runnable() { public void run() { try { Log.d("TAG", "Response from server : n " + response_str); } catch (Exception e) { e.printStackTrace(); } } }); } } catch (Exception ex) { Log.e("TAG", "error: " + ex.getMessage(), ex); } } private class HoroscopeAsyncTask extends AsyncTask<String, Void, Void> { public HoroscopeAsyncTask(ProgressBar pb1){ pb = pb1; } @Override protected void onPreExecute() { pb.setVisibility(View.VISIBLE); super.onPreExecute(); } @Override protected Void doInBackground(String... params) { getHoroscope(); try { Log.d("TAG", "test u try"); JSONObject jsonObject = new JSONObject(response_str); JSONArray jsonArray = jsonObject.getJSONArray("horoscope"); for(int i=0;i<jsonArray.length();i++){ Log.d("TAG", "test u for"); JSONObject horoscopeObj = jsonArray.getJSONObject(i); String horoscopeSign = horoscopeObj.getString("name_sign"); String horoscopeText = horoscopeObj.getString("txt_hrs"); zodiacItem = new ZodiacItem(horoscopeSign, horoscopeText, duration[i], images[i], largeImages[i]); zodiacList.add(zodiacItem); zodiacFeed.addItem(zodiacItem); //Treba u POJO klasu ubaciti sve. Log.d("TAG", "ZNAK: "+zodiacItem.getName()+" HOROSKOP: "+zodiacItem.getText()); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); Log.e("TAG", "error: " + e.getMessage(), e); } return null; } @Override protected void onPostExecute(Void result) { pb.setVisibility(View.GONE); list.setAdapter(adapter); adapter.notifyDataSetChanged(); super.onPostExecute(result); } } Here is the code for ListFragment class: public class ListFragment extends Fragment { @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub // Retain this fragment across configuration changes. setRetainInstance(true); super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub View view = inflater.inflate(R.layout.fragment_list, container, false); return view; } }

    Read the article

  • Async stream writing in a thread

    - by blez
    I have a thread in which I write to 2 streams. The problem is that the thread is blocked until the first one finishes writing (until all data is transferred on the other side of the pipe), and I don't want that. Is there a way to make it asynchronous? chunkOutput is a Dictionary filled with data from multiple threads, so the faster checking for existing keys is, the faster the pipe will write. void ConsumerMethod(object totalChunks) { while(true) { if (chunkOutput.ContainsKey(curChunk)) { if (outputStream != null && chunkOutput[curChunk].Length > 0) { outputStream.Write(chunkOutput[curChunk]); // <-- here it stops } ChunkDownloader.AppendData("outfile.dat", chunkOutput[curChunk], chunkOutput[curChunk].Length); curChunk++; if (curChunk >= (int) totalChunks) return; } Thread.Sleep(10); } }

    Read the article

  • Async data loading with WCF service with UI capabilities

    - by Jojo
    I'm working on complex user control(with Telerik components). I'm trying to implement following functionality: Typing some text in RadTextBox(let say: "Hello.txt"). Clicking on Button "Check". onClientClick for button "Check" will call WCF method with parameters. Let say that this request/response will take more that 10 seconds, meanwhile I'll see loading image near TextBox AND the most important, I can continue to work on other fields. When WCF service responses UI will be updated with the result. Thanks in advance

    Read the article

  • Async polling useable for GUI thread

    - by Tomas
    Hi, I have read that I can use asynchronous call with polling especially when the caller thread serves the GUI. I cannot see how because: while(AsyncResult_.IsCompleted==false) //this stops the GUI thread { } So how it come it should be good for this purpose? I needed to update my GUI status bar everytime deamon thread did some progress..

    Read the article

  • Why is my BeginInvoke method not async?

    - by Petr
    Hi, In order to avoid freezing of GUI, I wanted to run method connecting to DB asynchronously. Therefore I have written this: DelegatLoginu dl = ConnectDB; IAsyncResult ar=dl.BeginInvoke(null, null); bool result = (bool)dl.EndInvoke(ar); But it is still freezing and I do not understand why - I though BeginInvoke assures that method it references is run in another thread. Thank you!

    Read the article

  • AngularJS directives with async content

    - by SirDavik
    I'm generating a dynamic number of Google Charts tables after receiving the content through an ajax request and I wanted to apply an accordion effect on them. I wanted to know if I could do that with directives (since if I just code render the angular tags they won't get interpreted). I don't need a code example, just a short answer to see if I should learn directives or if I should do it in a different way (I was thinking routeParams). Thanks!

    Read the article

  • Async webmethod without timeout

    - by phenevo
    Hi, I need a console app which will calling webmethod. It must be asynchronous and without timeout (we don't know how much time takes this method to deal with task. Is it good way: [WebMethod] [SoapDocumentMethod(OneWay = true)] ??

    Read the article

  • Android app crashes on Async Task

    - by Telmo Vaz
    why is my APP crashing when I invoke the AsyncTask? public class Login extends Activity { String mail; EditText mailIn; Button btSubmit; @Override protected void onCreate(Bundle tokenArg) { super.onCreate(tokenArg); setContentView(R.layout.login); mailIn = (EditText)findViewById(R.id.usermail); btSubmit = (Button)findViewById(R.id.submit); btSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View thisView) { new LoginProc().execute(); } }); } public class LoginProc extends AsyncTask<String, Void, Void> { @Override protected void onPreExecute() { mailIn = (EditText)findViewById(R.id.usermail); mail = mailIn.getText().toString(); super.onPreExecute(); } @Override protected Void doInBackground(String... params) { Toast.makeText(getApplicationContext(), mail, Toast.LENGTH_SHORT).show(); return null; } } } I'm trying to make the String name get it's value on the preExecute method, but it happens that the app crashes on that point. Even if I take the preExecute and do that on the doInBrackground, it still crashes. What's wrong?

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >