Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- URL url = new URL(urlToRssFeed);
- SAXParserFactory factory = SAXParserFactory.newInstance();
- SAXParser parser = factory.newSAXParser();
- XMLReader xmlreader = parser.getXMLReader();
- RssHandler theRSSHandler = new RssHandler();
- xmlreader.setContentHandler(theRSSHandler);
- InputSource is = new InputSource(url.openStream());
- xmlreader.parse(is);
- return theRSSHandler.getFeed();
- android.os.NetworkOnMainThreadException
- class RetrieveFeedTask extends AsyncTask<String, Void, RSSFeed> {
- private Exception exception;
- protected RSSFeed doInBackground(String... urls) {
- try {
- URL url = new URL(urls[0]);
- SAXParserFactory factory = SAXParserFactory.newInstance();
- SAXParser parser = factory.newSAXParser();
- XMLReader xmlreader = parser.getXMLReader();
- RssHandler theRSSHandler = new RssHandler();
- xmlreader.setContentHandler(theRSSHandler);
- InputSource is = new InputSource(url.openStream());
- xmlreader.parse(is);
- return theRSSHandler.getFeed();
- } catch (Exception e) {
- this.exception = e;
- return null;
- } finally {
- is.close();
- }
- }
- protected void onPostExecute(RSSFeed feed) {
- // TODO: check this.exception
- // TODO: do something with the feed
- }
- }
- new RetrieveFeedTask().execute(urlToRssFeed);
- <uses-permission android:name="android.permission.INTERNET"/>
- StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
- StrictMode.setThreadPolicy(policy);
- <uses-permission android:name="android.permission.INTERNET"/>
- Thread thread = new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- //Your code goes here
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- });
- thread.start();
- import android.app.IntentService;
- import android.app.PendingIntent;
- import android.content.Intent;
- import android.util.Log;
- import java.io.InputStream;
- import java.net.MalformedURLException;
- import java.net.URL;
- public class DownloadIntentService extends IntentService {
- private static final String TAG = DownloadIntentService.class.getSimpleName();
- public static final String PENDING_RESULT_EXTRA = "pending_result";
- public static final String URL_EXTRA = "url";
- public static final String RSS_RESULT_EXTRA = "url";
- public static final int RESULT_CODE = 0;
- public static final int INVALID_URL_CODE = 1;
- public static final int ERROR_CODE = 2;
- private IllustrativeRSSParser parser;
- public DownloadIntentService() {
- super(TAG);
- // make one and re-use, in the case where more than one intent is queued
- parser = new IllustrativeRSSParser();
- }
- @Override
- protected void onHandleIntent(Intent intent) {
- PendingIntent reply = intent.getParcelableExtra(PENDING_RESULT_EXTRA);
- InputStream in = null;
- try {
- try {
- URL url = new URL(intent.getStringExtra(URL_EXTRA));
- IllustrativeRSS rss = parser.parse(in = url.openStream());
- Intent result = new Intent();
- result.putExtra(RSS_RESULT_EXTRA, rss);
- reply.send(this, RESULT_CODE, result);
- } catch (MalformedURLException exc) {
- reply.send(INVALID_URL_CODE);
- } catch (Exception exc) {
- // could do better by treating the different sax/xml exceptions individually
- reply.send(ERROR_CODE);
- }
- } catch (PendingIntent.CanceledException exc) {
- Log.i(TAG, "reply cancelled", exc);
- }
- }
- }
- <service
- android:name=".DownloadIntentService"
- android:exported="false"/>
- PendingIntent pendingResult = createPendingResult(
- RSS_DOWNLOAD_REQUEST_CODE, new Intent(), 0);
- Intent intent = new Intent(getApplicationContext(), DownloadIntentService.class);
- intent.putExtra(DownloadIntentService.URL_EXTRA, URL);
- intent.putExtra(DownloadIntentService.PENDING_RESULT_EXTRA, pendingResult);
- startService(intent);
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- if (requestCode == RSS_DOWNLOAD_REQUEST_CODE) {
- switch (resultCode) {
- case DownloadIntentService.INVALID_URL_CODE:
- handleInvalidURL();
- break;
- case DownloadIntentService.ERROR_CODE:
- handleError(data);
- break;
- case DownloadIntentService.RESULT_CODE:
- handleRSS(data);
- break;
- }
- handleRSS(data);
- }
- super.onActivityResult(requestCode, resultCode, data);
- }
- new Thread(new Runnable(){
- @Override
- public void run() {
- // Do network action in this function
- }
- }).start();
- <uses-permission android:name="android.permission.INTERNET"/>
- if (android.os.Build.VERSION.SDK_INT > 9) {
- StrictMode.ThreadPolicy policy =
- new StrictMode.ThreadPolicy.Builder().permitAll().build();
- StrictMode.setThreadPolicy(policy);
- }
- new Thread(new Runnable(){
- @Override
- public void run() {
- try {
- // Your implementation goes here
- }
- catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- }).start();
- new Thread(new Runnable(){
- @Override
- public void run() {
- try {
- // Your implementation
- }
- catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- }).start();
- class DemoTask extends AsyncTask<Void, Void, Void> {
- protected Void doInBackground(Void... arg0) {
- //Your implementation
- }
- protected void onPostExecute(Void result) {
- // TODO: do something with the feed
- }
- }
- // normal method
- private void normal() {
- doSomething(); // do something in background
- }
- @Background
- protected void doSomething()
- // run your networking code here
- }
- AsyncHttpClient client = new AsyncHttpClient();
- client.get("http://www.google.com", new AsyncHttpResponseHandler() {
- @Override
- public void onStart() {
- // Called before a request is started
- }
- @Override
- public void onSuccess(int statusCode, Header[] headers, byte[] response) {
- // Called when response HTTP status is "200 OK"
- }
- @Override
- public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
- // Called when response HTTP status is "4XX" (for example, 401, 403, 404)
- }
- @Override
- public void onRetry(int retryNo) {
- // Called when request is retried
- }
- });
- RSSFeed feed = new RetreiveFeedTask().execute(urlToRssFeed).get();
- <uses-sdk
- android:minSdkVersion="8"
- android:targetSdkVersion="10" />
- <uses-permission android:name="android.permission.INTERNET"/>
- Executors.newSingleThreadExecutor().submit(new Runnable() {
- @Override
- public void run() {
- // You can perform your task here.
- }
- });
- **Use like this in Your Activity**
- btnsub.setOnClickListener(new View.OnClickListener()
- {
- @Override
- public void onClick(View v)
- {
- new Thread(new Runnable() {
- @Override
- public void run() {
- // TODO Auto-generated method stub
- //Initialize soap request + add parameters
- SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);
- //Use this to add parameters
- request.addProperty("pincode",txtpincode.getText().toString());
- request.addProperty("bg",bloodgroup.getSelectedItem().toString());
- //Declare the version of the SOAP request
- SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
- envelope.setOutputSoapObject(request);
- envelope.dotNet = true;
- try {
- HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
- //this is the actual part that will call the webservice
- androidHttpTransport.call(SOAP_ACTION1, envelope);
- // Get the SoapResult from the envelope body.
- SoapObject result = (SoapObject)envelope.getResponse();
- Log.e("result data", "data"+result);
- SoapObject root = (SoapObject) result.getProperty(0);
- // SoapObject s_deals = (SoapObject) root.getProperty(0);
- //SoapObject s_deals_1 = (SoapObject) s_deals.getProperty(0);
- //
- System.out.println("********Count : "+ root.getPropertyCount());
- value=new ArrayList<Detailinfo>();
- for (int i = 0; i < root.getPropertyCount(); i++)
- {
- SoapObject s_deals = (SoapObject) root.getProperty(i);
- Detailinfo info=new Detailinfo();
- info.setFirstName( s_deals.getProperty("Firstname").toString());
- info.setLastName( s_deals.getProperty("Lastname").toString());
- info.setDOB( s_deals.getProperty("DOB").toString());
- info.setGender( s_deals.getProperty("Gender").toString());
- info.setAddress( s_deals.getProperty("Address").toString());
- info.setCity( s_deals.getProperty("City").toString());
- info.setState( s_deals.getProperty("State").toString());
- info.setPinecode( s_deals.getProperty("Pinecode").toString());
- info.setMobile( s_deals.getProperty("Mobile").toString());
- info.setEmail( s_deals.getProperty("Email").toString());
- info.setBloodgroup( s_deals.getProperty("Bloodgroup").toString());
- info.setAdddate( s_deals.getProperty("Adddate").toString());
- info.setWaight(s_deals.getProperty("waight").toString());
- value.add(info);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- Intent inten=new Intent(getApplicationContext(),ComposeMail.class);
- //intent.putParcelableArrayListExtra("valuesList", value);
- startActivity(inten);
- }
- }).start();
- }
- });
- Ion.with(context)
- .load("http://example.com/thing.json")
- .asJsonObject()
- .setCallback(new FutureCallback<JsonObject>() {
- @Override
- public void onCompleted(Exception e, JsonObject result) {
- // do stuff with the result or error
- }
- });
- http://api.example.com/stocks //ResponseWrapper<String> object containing a list of Srings with ticker symbols
- http://api.example.com/stocks/$symbol //Stock object
- http://api.example.com/stocks/$symbol/prices //PriceHistory<Stock> object
- http://api.example.com/currencies //ResponseWrapper<String> object containing a list of currency abbreviation
- http://api.example.com/currencies/$currency //Currency object
- http://api.example.com/currencies/$id1/values/$id2 //PriceHistory<Currency> object comparing the prices of the first currency (id1) to the second (id2)
- implementation 'com.squareup.retrofit2:retrofit:2.3.0' //retrofit library, current as of September 21, 2017
- implementation 'com.squareup.retrofit2:converter-gson:2.3.0' //gson serialization and deserialization support for retrofit, version must match retrofit version
- public interface FinancesApi {
- @GET("stocks")
- Call<ResponseWrapper<String>> listStocks();
- @GET("stocks/{symbol}")
- Call<Stock> getStock(@Path("symbol")String tickerSymbol);
- @GET("stocks/{symbol}/prices")
- Call<PriceHistory<Stock>> getPriceHistory(@Path("symbol")String tickerSymbol);
- @GET("currencies")
- Call<ResponseWrapper<String>> listCurrencies();
- @GET("currencies/{symbol}")
- Call<Currency> getCurrency(@Path("symbol")String currencySymbol);
- @GET("currencies/{symbol}/values/{compare_symbol}")
- Call<PriceHistory<Currency>> getComparativeHistory(@Path("symbol")String currency, @Path("compare_symbol")String currencyToPriceAgainst);
- }
- public class FinancesApiBuilder {
- public static FinancesApi build(String baseUrl){
- return new Retrofit.Builder()
- .baseUrl(baseUrl)
- .addConverterFactory(GsonConverterFactory.create())
- .build()
- .create(FinancesApi.class);
- }
- }
- FinancesApi api = FinancesApiBuilder.build("http://api.example.com/"); //trailing '/' required for predictable behavior
- api.getStock("INTC").enqueue(new Callback<Stock>(){
- @Override
- public void onResponse(Call<Stock> stockCall, Response<Stock> stockResponse){
- Stock stock = stockCall.body();
- //do something with the stock
- }
- @Override
- public void onResponse(Call<Stock> stockCall, Throwable t){
- //something bad happened
- }
- }
- implementation 'com.android.volley:volley:1.0.0'
- public class ImageFetch {
- private static ImageLoader imageLoader = null;
- private static RequestQueue imageQueue = null;
- public static ImageLoader getImageLoader(Context ctx){
- if(imageLoader == null){
- if(imageQueue == null){
- imageQueue = Volley.newRequestQueue(ctx.getApplicationContext());
- }
- imageLoader = new ImageLoader(imageQueue, new ImageLoader.ImageCache() {
- Map<String, Bitmap> cache = new HashMap<String, Bitmap>();
- @Override
- public Bitmap getBitmap(String url) {
- return cache.get(url);
- }
- @Override
- public void putBitmap(String url, Bitmap bitmap) {
- cache.put(url, bitmap);
- }
- });
- }
- return imageLoader;
- }
- }
- <com.android.volley.toolbox.NetworkImageView
- android:id="@+id/profile_picture"
- android:layout_width="32dp"
- android:layout_height="32dp"
- android:layout_alignParentTop="true"
- android:layout_centerHorizontal="true"
- app:srcCompat="@android:drawable/spinner_background"/>
- NetworkImageView profilePicture = view.findViewById(R.id.profile_picture);
- profilePicture.setImageUrl("http://example.com/users/images/profile.jpg", ImageFetch.getImageLoader(getContext());
- HandlerThread handlerThread = new HandlerThread("URLConnection");
- handlerThread.start();
- handler mainHandler = new Handler(handlerThread.getLooper());
- Runnable myRunnable = new Runnable() {
- @Override
- public void run() {
- try {
- Log.d("Ravi", "Before IO call");
- URL page = new URL("http://www.google.com");
- StringBuffer text = new StringBuffer();
- HttpURLConnection conn = (HttpURLConnection) page.openConnection();
- conn.connect();
- InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
- BufferedReader buff = new BufferedReader(in);
- String line;
- while ( (line = buff.readLine()) != null) {
- text.append(line + "n");
- }
- Log.d("Ravi", "After IO call");
- Log.d("Ravi",text.toString());
- }catch( Exception err){
- err.printStackTrace();
- }
- }
- };
- mainHandler.post(myRunnable);
- new Thread() {
- @Override
- public void run() {
- try {
- //Your code goes here
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }.start();
- String getUrl() {
- return "SomeUrl";
- }
- private Object makeCallParseResponse(String url) {
- return null;
- //
- }
- private void processResponse(Object o) {
- }
- rx.Observable.defer(new Func0<rx.Observable<String>>() {
- @Override
- public rx.Observable<String> call() {
- return rx.Observable.just(getUrl());
- }
- })
- .subscribeOn(Schedulers.io())
- .observeOn(Schedulers.io())
- .map(new Func1<String, Object>() {
- @Override
- public Object call(final String s) {
- return makeCallParseResponse(s);
- }
- })
- .observeOn(AndroidSchedulers.mainThread())
- .subscribe(new Action1<Object>() {
- @Override
- public void call(Object o) {
- processResponse(o);
- }
- },
- new Action1<Throwable>() {
- @Override
- public void call(Throwable throwable) {
- // Process error here, it will be posted on
- // the main thread
- }
- });
- compile 'io.reactivex:rxjava:1.1.5'
- compile 'io.reactivex:rxandroid:1.2.0'
- Observable<List<String>> musicShowsObservable = Observable.fromCallable(new Callable<List<String>>() {
- @Override
- public List<String> call() {
- return mRestClient.getFavoriteMusicShows();
- }
- });
- mMusicShowSubscription = musicShowsObservable
- .subscribeOn(Schedulers.io())
- .observeOn(AndroidSchedulers.mainThread())
- .subscribe(new Observer<List<String>>() {
- @Override
- public void onCompleted() { }
- @Override
- public void onError(Throwable e) { }
- @Override
- public void onNext(List<String> musicShows){
- listMusicShows(musicShows);
- }
- });
- public class MyDownloader extends AsyncTask<String,Void,Bitmap>
- {
- @Override
- protected void onPreExecute() {
- // Show progress dialog
- super.onPreExecute();
- }
- @Override
- protected void onPostExecute(Bitmap bitmap) {
- //Populate Ui
- super.onPostExecute(bitmap);
- }
- @Override
- protected Bitmap doInBackground(String... params) {
- // Open URL connection read bitmaps and return form here
- return result;
- }
- @Override
- protected void onProgressUpdate(Void... values) {
- // Show progress update
- super.onProgressUpdate(values);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement