Advertisement
Guest User

Untitled

a guest
Jan 18th, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.71 KB | None | 0 0
  1. URL url = new URL(urlToRssFeed);
  2. SAXParserFactory factory = SAXParserFactory.newInstance();
  3. SAXParser parser = factory.newSAXParser();
  4. XMLReader xmlreader = parser.getXMLReader();
  5. RssHandler theRSSHandler = new RssHandler();
  6. xmlreader.setContentHandler(theRSSHandler);
  7. InputSource is = new InputSource(url.openStream());
  8. xmlreader.parse(is);
  9. return theRSSHandler.getFeed();
  10.  
  11. android.os.NetworkOnMainThreadException
  12.  
  13. class RetrieveFeedTask extends AsyncTask<String, Void, RSSFeed> {
  14.  
  15. private Exception exception;
  16.  
  17. protected RSSFeed doInBackground(String... urls) {
  18. try {
  19. URL url = new URL(urls[0]);
  20. SAXParserFactory factory = SAXParserFactory.newInstance();
  21. SAXParser parser = factory.newSAXParser();
  22. XMLReader xmlreader = parser.getXMLReader();
  23. RssHandler theRSSHandler = new RssHandler();
  24. xmlreader.setContentHandler(theRSSHandler);
  25. InputSource is = new InputSource(url.openStream());
  26. xmlreader.parse(is);
  27.  
  28. return theRSSHandler.getFeed();
  29. } catch (Exception e) {
  30. this.exception = e;
  31.  
  32. return null;
  33. } finally {
  34. is.close();
  35. }
  36. }
  37.  
  38. protected void onPostExecute(RSSFeed feed) {
  39. // TODO: check this.exception
  40. // TODO: do something with the feed
  41. }
  42. }
  43.  
  44. new RetrieveFeedTask().execute(urlToRssFeed);
  45.  
  46. <uses-permission android:name="android.permission.INTERNET"/>
  47.  
  48. StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
  49.  
  50. StrictMode.setThreadPolicy(policy);
  51.  
  52. <uses-permission android:name="android.permission.INTERNET"/>
  53.  
  54. Thread thread = new Thread(new Runnable() {
  55.  
  56. @Override
  57. public void run() {
  58. try {
  59. //Your code goes here
  60. } catch (Exception e) {
  61. e.printStackTrace();
  62. }
  63. }
  64. });
  65.  
  66. thread.start();
  67.  
  68. import android.app.IntentService;
  69. import android.app.PendingIntent;
  70. import android.content.Intent;
  71. import android.util.Log;
  72.  
  73. import java.io.InputStream;
  74. import java.net.MalformedURLException;
  75. import java.net.URL;
  76.  
  77. public class DownloadIntentService extends IntentService {
  78.  
  79. private static final String TAG = DownloadIntentService.class.getSimpleName();
  80.  
  81. public static final String PENDING_RESULT_EXTRA = "pending_result";
  82. public static final String URL_EXTRA = "url";
  83. public static final String RSS_RESULT_EXTRA = "url";
  84.  
  85. public static final int RESULT_CODE = 0;
  86. public static final int INVALID_URL_CODE = 1;
  87. public static final int ERROR_CODE = 2;
  88.  
  89. private IllustrativeRSSParser parser;
  90.  
  91. public DownloadIntentService() {
  92. super(TAG);
  93.  
  94. // make one and re-use, in the case where more than one intent is queued
  95. parser = new IllustrativeRSSParser();
  96. }
  97.  
  98. @Override
  99. protected void onHandleIntent(Intent intent) {
  100. PendingIntent reply = intent.getParcelableExtra(PENDING_RESULT_EXTRA);
  101. InputStream in = null;
  102. try {
  103. try {
  104. URL url = new URL(intent.getStringExtra(URL_EXTRA));
  105. IllustrativeRSS rss = parser.parse(in = url.openStream());
  106.  
  107. Intent result = new Intent();
  108. result.putExtra(RSS_RESULT_EXTRA, rss);
  109.  
  110. reply.send(this, RESULT_CODE, result);
  111. } catch (MalformedURLException exc) {
  112. reply.send(INVALID_URL_CODE);
  113. } catch (Exception exc) {
  114. // could do better by treating the different sax/xml exceptions individually
  115. reply.send(ERROR_CODE);
  116. }
  117. } catch (PendingIntent.CanceledException exc) {
  118. Log.i(TAG, "reply cancelled", exc);
  119. }
  120. }
  121. }
  122.  
  123. <service
  124. android:name=".DownloadIntentService"
  125. android:exported="false"/>
  126.  
  127. PendingIntent pendingResult = createPendingResult(
  128. RSS_DOWNLOAD_REQUEST_CODE, new Intent(), 0);
  129. Intent intent = new Intent(getApplicationContext(), DownloadIntentService.class);
  130. intent.putExtra(DownloadIntentService.URL_EXTRA, URL);
  131. intent.putExtra(DownloadIntentService.PENDING_RESULT_EXTRA, pendingResult);
  132. startService(intent);
  133.  
  134. @Override
  135. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  136. if (requestCode == RSS_DOWNLOAD_REQUEST_CODE) {
  137. switch (resultCode) {
  138. case DownloadIntentService.INVALID_URL_CODE:
  139. handleInvalidURL();
  140. break;
  141. case DownloadIntentService.ERROR_CODE:
  142. handleError(data);
  143. break;
  144. case DownloadIntentService.RESULT_CODE:
  145. handleRSS(data);
  146. break;
  147. }
  148. handleRSS(data);
  149. }
  150. super.onActivityResult(requestCode, resultCode, data);
  151. }
  152.  
  153. new Thread(new Runnable(){
  154. @Override
  155. public void run() {
  156. // Do network action in this function
  157. }
  158. }).start();
  159.  
  160. <uses-permission android:name="android.permission.INTERNET"/>
  161.  
  162. if (android.os.Build.VERSION.SDK_INT > 9) {
  163. StrictMode.ThreadPolicy policy =
  164. new StrictMode.ThreadPolicy.Builder().permitAll().build();
  165. StrictMode.setThreadPolicy(policy);
  166. }
  167.  
  168. new Thread(new Runnable(){
  169. @Override
  170. public void run() {
  171. try {
  172. // Your implementation goes here
  173. }
  174. catch (Exception ex) {
  175. ex.printStackTrace();
  176. }
  177. }
  178. }).start();
  179.  
  180. new Thread(new Runnable(){
  181. @Override
  182. public void run() {
  183. try {
  184. // Your implementation
  185. }
  186. catch (Exception ex) {
  187. ex.printStackTrace();
  188. }
  189. }
  190. }).start();
  191.  
  192. class DemoTask extends AsyncTask<Void, Void, Void> {
  193.  
  194. protected Void doInBackground(Void... arg0) {
  195. //Your implementation
  196. }
  197.  
  198. protected void onPostExecute(Void result) {
  199. // TODO: do something with the feed
  200. }
  201. }
  202.  
  203. // normal method
  204. private void normal() {
  205. doSomething(); // do something in background
  206. }
  207.  
  208. @Background
  209. protected void doSomething()
  210. // run your networking code here
  211. }
  212.  
  213. AsyncHttpClient client = new AsyncHttpClient();
  214. client.get("http://www.google.com", new AsyncHttpResponseHandler() {
  215.  
  216. @Override
  217. public void onStart() {
  218. // Called before a request is started
  219. }
  220.  
  221. @Override
  222. public void onSuccess(int statusCode, Header[] headers, byte[] response) {
  223. // Called when response HTTP status is "200 OK"
  224. }
  225.  
  226. @Override
  227. public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
  228. // Called when response HTTP status is "4XX" (for example, 401, 403, 404)
  229. }
  230.  
  231. @Override
  232. public void onRetry(int retryNo) {
  233. // Called when request is retried
  234. }
  235. });
  236.  
  237. RSSFeed feed = new RetreiveFeedTask().execute(urlToRssFeed).get();
  238.  
  239. <uses-sdk
  240. android:minSdkVersion="8"
  241. android:targetSdkVersion="10" />
  242.  
  243. <uses-permission android:name="android.permission.INTERNET"/>
  244.  
  245. Executors.newSingleThreadExecutor().submit(new Runnable() {
  246. @Override
  247. public void run() {
  248. // You can perform your task here.
  249. }
  250. });
  251.  
  252. **Use like this in Your Activity**
  253.  
  254. btnsub.setOnClickListener(new View.OnClickListener()
  255. {
  256. @Override
  257. public void onClick(View v)
  258. {
  259. new Thread(new Runnable() {
  260.  
  261. @Override
  262. public void run() {
  263. // TODO Auto-generated method stub
  264.  
  265. //Initialize soap request + add parameters
  266. SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);
  267.  
  268. //Use this to add parameters
  269.  
  270.  
  271. request.addProperty("pincode",txtpincode.getText().toString());
  272. request.addProperty("bg",bloodgroup.getSelectedItem().toString());
  273.  
  274. //Declare the version of the SOAP request
  275. SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
  276.  
  277. envelope.setOutputSoapObject(request);
  278. envelope.dotNet = true;
  279.  
  280. try {
  281.  
  282. HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
  283.  
  284. //this is the actual part that will call the webservice
  285. androidHttpTransport.call(SOAP_ACTION1, envelope);
  286.  
  287. // Get the SoapResult from the envelope body.
  288. SoapObject result = (SoapObject)envelope.getResponse();
  289. Log.e("result data", "data"+result);
  290. SoapObject root = (SoapObject) result.getProperty(0);
  291. // SoapObject s_deals = (SoapObject) root.getProperty(0);
  292. //SoapObject s_deals_1 = (SoapObject) s_deals.getProperty(0);
  293. //
  294.  
  295.  
  296. System.out.println("********Count : "+ root.getPropertyCount());
  297.  
  298. value=new ArrayList<Detailinfo>();
  299.  
  300. for (int i = 0; i < root.getPropertyCount(); i++)
  301. {
  302. SoapObject s_deals = (SoapObject) root.getProperty(i);
  303. Detailinfo info=new Detailinfo();
  304.  
  305. info.setFirstName( s_deals.getProperty("Firstname").toString());
  306. info.setLastName( s_deals.getProperty("Lastname").toString());
  307. info.setDOB( s_deals.getProperty("DOB").toString());
  308. info.setGender( s_deals.getProperty("Gender").toString());
  309. info.setAddress( s_deals.getProperty("Address").toString());
  310. info.setCity( s_deals.getProperty("City").toString());
  311. info.setState( s_deals.getProperty("State").toString());
  312. info.setPinecode( s_deals.getProperty("Pinecode").toString());
  313. info.setMobile( s_deals.getProperty("Mobile").toString());
  314. info.setEmail( s_deals.getProperty("Email").toString());
  315. info.setBloodgroup( s_deals.getProperty("Bloodgroup").toString());
  316. info.setAdddate( s_deals.getProperty("Adddate").toString());
  317. info.setWaight(s_deals.getProperty("waight").toString());
  318. value.add(info);
  319.  
  320. }
  321.  
  322.  
  323. } catch (Exception e) {
  324. e.printStackTrace();
  325. }
  326. Intent inten=new Intent(getApplicationContext(),ComposeMail.class);
  327. //intent.putParcelableArrayListExtra("valuesList", value);
  328.  
  329. startActivity(inten);
  330.  
  331.  
  332.  
  333. }
  334. }).start();
  335. }
  336. });
  337.  
  338. Ion.with(context)
  339. .load("http://example.com/thing.json")
  340. .asJsonObject()
  341. .setCallback(new FutureCallback<JsonObject>() {
  342. @Override
  343. public void onCompleted(Exception e, JsonObject result) {
  344. // do stuff with the result or error
  345. }
  346. });
  347.  
  348. http://api.example.com/stocks //ResponseWrapper<String> object containing a list of Srings with ticker symbols
  349. http://api.example.com/stocks/$symbol //Stock object
  350. http://api.example.com/stocks/$symbol/prices //PriceHistory<Stock> object
  351. http://api.example.com/currencies //ResponseWrapper<String> object containing a list of currency abbreviation
  352. http://api.example.com/currencies/$currency //Currency object
  353. http://api.example.com/currencies/$id1/values/$id2 //PriceHistory<Currency> object comparing the prices of the first currency (id1) to the second (id2)
  354.  
  355. implementation 'com.squareup.retrofit2:retrofit:2.3.0' //retrofit library, current as of September 21, 2017
  356. implementation 'com.squareup.retrofit2:converter-gson:2.3.0' //gson serialization and deserialization support for retrofit, version must match retrofit version
  357.  
  358. public interface FinancesApi {
  359. @GET("stocks")
  360. Call<ResponseWrapper<String>> listStocks();
  361. @GET("stocks/{symbol}")
  362. Call<Stock> getStock(@Path("symbol")String tickerSymbol);
  363. @GET("stocks/{symbol}/prices")
  364. Call<PriceHistory<Stock>> getPriceHistory(@Path("symbol")String tickerSymbol);
  365.  
  366. @GET("currencies")
  367. Call<ResponseWrapper<String>> listCurrencies();
  368. @GET("currencies/{symbol}")
  369. Call<Currency> getCurrency(@Path("symbol")String currencySymbol);
  370. @GET("currencies/{symbol}/values/{compare_symbol}")
  371. Call<PriceHistory<Currency>> getComparativeHistory(@Path("symbol")String currency, @Path("compare_symbol")String currencyToPriceAgainst);
  372. }
  373.  
  374. public class FinancesApiBuilder {
  375. public static FinancesApi build(String baseUrl){
  376. return new Retrofit.Builder()
  377. .baseUrl(baseUrl)
  378. .addConverterFactory(GsonConverterFactory.create())
  379. .build()
  380. .create(FinancesApi.class);
  381. }
  382. }
  383.  
  384. FinancesApi api = FinancesApiBuilder.build("http://api.example.com/"); //trailing '/' required for predictable behavior
  385. api.getStock("INTC").enqueue(new Callback<Stock>(){
  386. @Override
  387. public void onResponse(Call<Stock> stockCall, Response<Stock> stockResponse){
  388. Stock stock = stockCall.body();
  389. //do something with the stock
  390. }
  391. @Override
  392. public void onResponse(Call<Stock> stockCall, Throwable t){
  393. //something bad happened
  394. }
  395. }
  396.  
  397. implementation 'com.android.volley:volley:1.0.0'
  398.  
  399. public class ImageFetch {
  400. private static ImageLoader imageLoader = null;
  401. private static RequestQueue imageQueue = null;
  402.  
  403. public static ImageLoader getImageLoader(Context ctx){
  404. if(imageLoader == null){
  405. if(imageQueue == null){
  406. imageQueue = Volley.newRequestQueue(ctx.getApplicationContext());
  407. }
  408. imageLoader = new ImageLoader(imageQueue, new ImageLoader.ImageCache() {
  409. Map<String, Bitmap> cache = new HashMap<String, Bitmap>();
  410. @Override
  411. public Bitmap getBitmap(String url) {
  412. return cache.get(url);
  413. }
  414. @Override
  415. public void putBitmap(String url, Bitmap bitmap) {
  416. cache.put(url, bitmap);
  417. }
  418. });
  419. }
  420. return imageLoader;
  421. }
  422. }
  423.  
  424. <com.android.volley.toolbox.NetworkImageView
  425. android:id="@+id/profile_picture"
  426. android:layout_width="32dp"
  427. android:layout_height="32dp"
  428. android:layout_alignParentTop="true"
  429. android:layout_centerHorizontal="true"
  430. app:srcCompat="@android:drawable/spinner_background"/>
  431.  
  432. NetworkImageView profilePicture = view.findViewById(R.id.profile_picture);
  433. profilePicture.setImageUrl("http://example.com/users/images/profile.jpg", ImageFetch.getImageLoader(getContext());
  434.  
  435. HandlerThread handlerThread = new HandlerThread("URLConnection");
  436. handlerThread.start();
  437. handler mainHandler = new Handler(handlerThread.getLooper());
  438.  
  439. Runnable myRunnable = new Runnable() {
  440. @Override
  441. public void run() {
  442. try {
  443. Log.d("Ravi", "Before IO call");
  444. URL page = new URL("http://www.google.com");
  445. StringBuffer text = new StringBuffer();
  446. HttpURLConnection conn = (HttpURLConnection) page.openConnection();
  447. conn.connect();
  448. InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
  449. BufferedReader buff = new BufferedReader(in);
  450. String line;
  451. while ( (line = buff.readLine()) != null) {
  452. text.append(line + "n");
  453. }
  454. Log.d("Ravi", "After IO call");
  455. Log.d("Ravi",text.toString());
  456.  
  457. }catch( Exception err){
  458. err.printStackTrace();
  459. }
  460. }
  461. };
  462. mainHandler.post(myRunnable);
  463.  
  464. new Thread() {
  465. @Override
  466. public void run() {
  467. try {
  468. //Your code goes here
  469. } catch (Exception e) {
  470. e.printStackTrace();
  471. }
  472. }
  473. }.start();
  474.  
  475. String getUrl() {
  476. return "SomeUrl";
  477. }
  478.  
  479. private Object makeCallParseResponse(String url) {
  480. return null;
  481. //
  482. }
  483.  
  484. private void processResponse(Object o) {
  485.  
  486. }
  487.  
  488. rx.Observable.defer(new Func0<rx.Observable<String>>() {
  489. @Override
  490. public rx.Observable<String> call() {
  491. return rx.Observable.just(getUrl());
  492. }
  493. })
  494. .subscribeOn(Schedulers.io())
  495. .observeOn(Schedulers.io())
  496. .map(new Func1<String, Object>() {
  497. @Override
  498. public Object call(final String s) {
  499. return makeCallParseResponse(s);
  500. }
  501. })
  502. .observeOn(AndroidSchedulers.mainThread())
  503. .subscribe(new Action1<Object>() {
  504. @Override
  505. public void call(Object o) {
  506. processResponse(o);
  507. }
  508. },
  509. new Action1<Throwable>() {
  510. @Override
  511. public void call(Throwable throwable) {
  512. // Process error here, it will be posted on
  513. // the main thread
  514. }
  515. });
  516.  
  517. compile 'io.reactivex:rxjava:1.1.5'
  518. compile 'io.reactivex:rxandroid:1.2.0'
  519.  
  520. Observable<List<String>> musicShowsObservable = Observable.fromCallable(new Callable<List<String>>() {
  521.  
  522. @Override
  523. public List<String> call() {
  524. return mRestClient.getFavoriteMusicShows();
  525. }
  526. });
  527.  
  528. mMusicShowSubscription = musicShowsObservable
  529. .subscribeOn(Schedulers.io())
  530. .observeOn(AndroidSchedulers.mainThread())
  531. .subscribe(new Observer<List<String>>() {
  532.  
  533. @Override
  534. public void onCompleted() { }
  535.  
  536. @Override
  537. public void onError(Throwable e) { }
  538.  
  539. @Override
  540. public void onNext(List<String> musicShows){
  541. listMusicShows(musicShows);
  542. }
  543. });
  544.  
  545. public class MyDownloader extends AsyncTask<String,Void,Bitmap>
  546. {
  547. @Override
  548. protected void onPreExecute() {
  549. // Show progress dialog
  550. super.onPreExecute();
  551. }
  552.  
  553. @Override
  554. protected void onPostExecute(Bitmap bitmap) {
  555. //Populate Ui
  556. super.onPostExecute(bitmap);
  557. }
  558.  
  559. @Override
  560. protected Bitmap doInBackground(String... params) {
  561. // Open URL connection read bitmaps and return form here
  562. return result;
  563. }
  564.  
  565. @Override
  566. protected void onProgressUpdate(Void... values) {
  567. // Show progress update
  568. super.onProgressUpdate(values);
  569. }
  570.  
  571.  
  572. }
  573. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement