GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — volley rx demo · liangling/RxJava-Android-Samples@ddcbefc

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • app
    • build.gradle
    • src/main
      • java/com/morihacky/android/rxjava
        • MyApp.java
        • fragments
          • MainFragment.java
          • VolleyDemoFragment.java
        • wiring
          • MyVolley.java
      • res
        • layout
          • fragment_main.xml
          • fragment_volley.xml
        • values
          • strings.xml
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎app/build.gradle‎

Copy file name to clipboardExpand all lines: app/build.gradle
+3-1Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ dependencies {
1818

1919
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3'
2020
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3'
21+
compile 'com.mcxiaoke.volley:library:1.0.19'
22+
2123
}
2224

2325
android {
@@ -37,4 +39,4 @@ android {
3739
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
3840
}
3941
}
40-
}
42+
}
Collapse file

‎app/src/main/java/com/morihacky/android/rxjava/MyApp.java‎

Copy file name to clipboardExpand all lines: app/src/main/java/com/morihacky/android/rxjava/MyApp.java
+5Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package com.morihacky.android.rxjava;
22

33
import android.app.Application;
4+
5+
import com.morihacky.android.rxjava.wiring.MyVolley;
46
import com.squareup.leakcanary.LeakCanary;
57
import com.squareup.leakcanary.RefWatcher;
68
import timber.log.Timber;
@@ -27,5 +29,8 @@ public void onCreate() {
2729
_refWatcher = LeakCanary.install(this);
2830

2931
Timber.plant(new Timber.DebugTree());
32+
33+
//volley init
34+
MyVolley.init(this);
3035
}
3136
}
Collapse file

‎app/src/main/java/com/morihacky/android/rxjava/fragments/MainFragment.java‎

Copy file name to clipboardExpand all lines: app/src/main/java/com/morihacky/android/rxjava/fragments/MainFragment.java
+9-2Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,13 @@
77
import android.view.LayoutInflater;
88
import android.view.View;
99
import android.view.ViewGroup;
10-
import butterknife.ButterKnife;
11-
import butterknife.OnClick;
10+
1211
import com.morihacky.android.rxjava.R;
1312
import com.morihacky.android.rxjava.rxbus.RxBusDemoFragment;
1413

14+
import butterknife.ButterKnife;
15+
import butterknife.OnClick;
16+
1517
public class MainFragment
1618
extends BaseFragment {
1719

@@ -80,6 +82,11 @@ void demoRotationPersist() {
8082
//clickedOn(new RotationPersist1Fragment());
8183
}
8284

85+
@OnClick(R.id.btn_demo_volley)
86+
void demoVolleyRequest() {
87+
clickedOn(new VolleyDemoFragment());
88+
}
89+
8390
private void clickedOn(@NonNull Fragment fragment) {
8491
final String tag = fragment.getClass().toString();
8592
getActivity().getSupportFragmentManager()
Collapse file

‎app/src/main/java/com/morihacky/android/rxjava/fragments/VolleyDemoFragment.java‎

Copy file name to clipboard
+189Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
package com.morihacky.android.rxjava.fragments;
2+
3+
import android.os.Bundle;
4+
import android.os.Handler;
5+
import android.os.Looper;
6+
import android.support.annotation.Nullable;
7+
import android.util.Log;
8+
import android.view.LayoutInflater;
9+
import android.view.View;
10+
import android.view.ViewGroup;
11+
import android.widget.Button;
12+
import android.widget.ListView;
13+
14+
import com.android.volley.Request;
15+
import com.android.volley.VolleyError;
16+
import com.android.volley.toolbox.JsonObjectRequest;
17+
import com.android.volley.toolbox.RequestFuture;
18+
import com.morihacky.android.rxjava.R;
19+
import com.morihacky.android.rxjava.wiring.LogAdapter;
20+
import com.morihacky.android.rxjava.wiring.MyVolley;
21+
22+
import org.json.JSONObject;
23+
24+
import java.nio.charset.Charset;
25+
import java.util.ArrayList;
26+
import java.util.List;
27+
import java.util.concurrent.ExecutionException;
28+
29+
import butterknife.Bind;
30+
import butterknife.ButterKnife;
31+
import butterknife.OnClick;
32+
import rx.Observable;
33+
import rx.Observer;
34+
import rx.android.schedulers.AndroidSchedulers;
35+
import rx.functions.Func0;
36+
import rx.schedulers.Schedulers;
37+
import rx.subscriptions.CompositeSubscription;
38+
import timber.log.Timber;
39+
40+
/**
41+
* Created by zhangxitao on 15/12/30.
42+
*/
43+
44+
public class VolleyDemoFragment
45+
extends BaseFragment {
46+
public static final String TAG = "VolleyDemoFragment";
47+
48+
@Bind(R.id.list_threading_log)
49+
ListView _logsList;
50+
@Bind(R.id.btn_start_operation)
51+
Button _tapBtn;
52+
53+
private LogAdapter _adapter;
54+
private List<String> _logs;
55+
56+
private CompositeSubscription mCompositeSubscription = new CompositeSubscription();
57+
58+
@OnClick(R.id.btn_start_operation)
59+
void startRequest() {
60+
startVolleyRequest();
61+
}
62+
63+
64+
@Override
65+
public void onStart() {
66+
super.onStart();
67+
68+
/**
69+
* @condition: RxJava future request with volley
70+
*/
71+
}
72+
73+
@Override
74+
public void onPause() {
75+
super.onPause();
76+
mCompositeSubscription.unsubscribe();
77+
}
78+
79+
@Override
80+
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
81+
super.onActivityCreated(savedInstanceState);
82+
_setupLogger();
83+
}
84+
85+
@Override
86+
public View onCreateView(LayoutInflater inflater,
87+
@Nullable ViewGroup container,
88+
@Nullable Bundle savedInstanceState) {
89+
View layout = inflater.inflate(R.layout.fragment_volley, container, false);
90+
ButterKnife.bind(this, layout);
91+
return layout;
92+
}
93+
94+
private void startVolleyRequest() {
95+
mCompositeSubscription.add(newGetRouteData()
96+
.subscribeOn(Schedulers.io())
97+
.observeOn(AndroidSchedulers.mainThread())
98+
.subscribe(new Observer<JSONObject>() {
99+
@Override
100+
public void onCompleted() {
101+
Log.e(TAG, "onCompleted");
102+
Timber.d("----- onCompleted");
103+
_log("onCompleted ");
104+
}
105+
106+
@Override
107+
public void onError(Throwable e) {
108+
VolleyError cause = (VolleyError) e.getCause();
109+
String s = new String(cause.networkResponse.data, Charset.forName("UTF-8"));
110+
Log.e(TAG, s);
111+
Log.e(TAG, cause.toString());
112+
_log("onError " + s);
113+
114+
}
115+
116+
@Override
117+
public void onNext(JSONObject jsonObject) {
118+
Log.e(TAG, "onNext " + jsonObject.toString());
119+
_log("onNext " + jsonObject.toString());
120+
121+
}
122+
}));
123+
}
124+
125+
126+
/**
127+
* @use handle response from future request, in my case JsonObject.
128+
*/
129+
private JSONObject getRouteData() throws ExecutionException, InterruptedException {
130+
RequestFuture<JSONObject> future = RequestFuture.newFuture();
131+
String url = "http://www.weather.com.cn/adat/sk/101010100.html";
132+
final Request.Priority priority = Request.Priority.IMMEDIATE;
133+
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, url, future, future);
134+
MyVolley.getRequestQueue().add(req);
135+
return future.get();
136+
}
137+
138+
/**
139+
* @use the observable, same type data Jsob Object
140+
*/
141+
public Observable<JSONObject> newGetRouteData() {
142+
return Observable.defer(new Func0<Observable<JSONObject>>() {
143+
@Override
144+
public Observable<JSONObject> call() {
145+
Exception exception;
146+
try {
147+
return Observable.just(getRouteData());
148+
} catch (InterruptedException | ExecutionException e) {
149+
Log.e("routes", e.getMessage());
150+
return Observable.error(e);
151+
}
152+
}
153+
});
154+
}
155+
156+
// -----------------------------------------------------------------------------------
157+
// Methods that help wiring up the example (irrelevant to RxJava)
158+
159+
private void _setupLogger() {
160+
_logs = new ArrayList<>();
161+
_adapter = new LogAdapter(getActivity(), new ArrayList<String>());
162+
_logsList.setAdapter(_adapter);
163+
}
164+
165+
private void _log(String logMsg) {
166+
167+
if (_isCurrentlyOnMainThread()) {
168+
_logs.add(0, logMsg + " (main thread) ");
169+
_adapter.clear();
170+
_adapter.addAll(_logs);
171+
} else {
172+
_logs.add(0, logMsg + " (NOT main thread) ");
173+
174+
// You can only do below stuff on main thread.
175+
new Handler(Looper.getMainLooper()).post(new Runnable() {
176+
177+
@Override
178+
public void run() {
179+
_adapter.clear();
180+
_adapter.addAll(_logs);
181+
}
182+
});
183+
}
184+
}
185+
186+
private boolean _isCurrentlyOnMainThread() {
187+
return Looper.myLooper() == Looper.getMainLooper();
188+
}
189+
}
Collapse file

‎app/src/main/java/com/morihacky/android/rxjava/wiring/MyVolley.java‎

Copy file name to clipboard
+63Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package com.morihacky.android.rxjava.wiring;
2+
3+
/**
4+
* Created by zhangxitao on 15/9/7.
5+
*/
6+
7+
import android.app.ActivityManager;
8+
import android.content.Context;
9+
10+
import com.android.volley.RequestQueue;
11+
import com.android.volley.toolbox.ImageLoader;
12+
import com.android.volley.toolbox.Volley;
13+
14+
/**
15+
* Helper class that is used to provide references to initialized RequestQueue(s) and ImageLoader(s)
16+
*
17+
* @author Ognyan Bankov
18+
*/
19+
public class MyVolley {
20+
private static RequestQueue mRequestQueue;
21+
private static ImageLoader mImageLoader;
22+
23+
24+
private MyVolley() {
25+
// no instances
26+
}
27+
28+
29+
public static void init(Context context) {
30+
mRequestQueue = Volley.newRequestQueue(context);
31+
32+
int memClass = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE))
33+
.getMemoryClass();
34+
// Use 1/8th of the available memory for this memory cache.
35+
int cacheSize = 1024 * 1024 * memClass / 8;
36+
// mImageLoader = new ImageLoader(mRequestQueue, new BitmapLruCache(cacheSize));
37+
}
38+
39+
40+
public static RequestQueue getRequestQueue() {
41+
if (mRequestQueue != null) {
42+
return mRequestQueue;
43+
} else {
44+
throw new IllegalStateException("RequestQueue not initialized");
45+
}
46+
}
47+
48+
49+
/**
50+
* Returns instance of ImageLoader initialized with {@see FakeImageCache} which effectively means
51+
* that no memory caching is used. This is useful for images that you know that will be show
52+
* only once.
53+
*
54+
* @return
55+
*/
56+
public static ImageLoader getImageLoader() {
57+
if (mImageLoader != null) {
58+
return mImageLoader;
59+
} else {
60+
throw new IllegalStateException("ImageLoader not initialized");
61+
}
62+
}
63+
}
Collapse file

‎app/src/main/res/layout/fragment_main.xml‎

Copy file name to clipboardExpand all lines: app/src/main/res/layout/fragment_main.xml
+6Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,5 +100,11 @@
100100
android:layout_width="match_parent"
101101
android:text="@string/btn_demo_rotation_persist"
102102
/>
103+
<Button
104+
android:id="@+id/btn_demo_volley"
105+
android:layout_height="wrap_content"
106+
android:layout_width="match_parent"
107+
android:text="@string/btn_demo_volley"
108+
/>
103109
</LinearLayout>
104110
</ScrollView>
Collapse file

‎app/src/main/res/layout/fragment_volley.xml‎

Copy file name to clipboard
+34Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
3+
<LinearLayout
4+
android:orientation="vertical"
5+
android:layout_height="match_parent"
6+
android:layout_width="match_parent"
7+
xmlns:android="http://schemas.android.com/apk/res/android"
8+
>
9+
10+
<TextView
11+
android:layout_height="wrap_content"
12+
android:layout_width="match_parent"
13+
android:padding="10dp"
14+
android:gravity="center"
15+
android:text="@string/msg_demo_volley"
16+
/>
17+
18+
<Button
19+
android:id="@+id/btn_start_operation"
20+
android:layout_height="wrap_content"
21+
android:layout_width="match_parent"
22+
android:layout_marginLeft="90dp"
23+
android:layout_marginRight="90dp"
24+
android:textSize="16dp"
25+
android:text="tap me"
26+
/>
27+
28+
<ListView
29+
android:id="@+id/list_threading_log"
30+
android:layout_height="match_parent"
31+
android:layout_width="match_parent"
32+
/>
33+
34+
</LinearLayout>
Collapse file

‎app/src/main/res/values/strings.xml‎

Copy file name to clipboardExpand all lines: app/src/main/res/values/strings.xml
+2-1Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@
1919
<string name="btn_demo_timing">Variations of timing/intervals/delays</string>
2020
<string name="btn_demo_exponential_backoff">Exponential backoff</string>
2121
<string name="btn_demo_rotation_persist">Rotation persist</string>
22-
22+
<string name="btn_demo_volley">Volley request demo</string>
23+
<string name="msg_demo_volley">This is a Volley request demo</string>
2324
<string name="msg_demo_concurrency_schedulers">This is a demo of how long running operations can be offloaded to a background thread. After the operation is done, we resume back on the main thread. All using RxJava! \n\n To really see this shine. Hit the button multiple times and see how the button click which is a ui operation is never blocked because the long operation only runs in the background</string>
2425
<string name="msg_demo_buffer">This is a demo of how events can be accumulated using the "buffer" operation. Tap the button below repetitively and you will notice in the logs that button taps are collected over a span of 2s and printed below.</string>
2526
<string name="msg_demo_debounce">As you type in the input box, it will not shoot out log messages at every single input character change, but rather only pick the last one.</string>

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.