Stream video from android to RTSP server - java

I need to stream video from an android phone to RTSP server and then receive this video on another android phone. I googled a lot but I didn't find a good solution for it. Everything I found was libstreaming but I couldn't run it in my app.
Here is my sample code:
private SurfaceView mSurfaceView;
private Session mSession;
private static RtspClient mClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSurfaceView = (SurfaceView) findViewById(R.id.surface);
mSurfaceView.getHolder().addCallback(this);
initRtspClient();
}
#Override
public void onDestroy() {
mClient.release();
mSession.release();
mSurfaceView.getHolder().removeCallback(this);
super.onDestroy();
}
#Override
protected void onResume() {
super.onResume();
toggleStreaming();
}
#Override
protected void onPause(){
super.onPause();
toggleStreaming();
}
private void initRtspClient() {
mSession = SessionBuilder.getInstance()
.setContext(getApplicationContext())
.setAudioEncoder(SessionBuilder.AUDIO_NONE)
.setAudioQuality(new AudioQuality(8000, 16000))
.setVideoEncoder(SessionBuilder.VIDEO_H264)
.setSurfaceView(mSurfaceView).setPreviewOrientation(0)
.setCallback(this).build();
mClient = new RtspClient();
mClient.setSession(mSession);
mClient.setCallback(this);
mSurfaceView.setAspectRatioMode(SurfaceView.ASPECT_RATIO_PREVIEW);
mClient.setServerAddress("176.120.25.62", 1235);
}
private void toggleStreaming() {
if (!mClient.isStreaming()) {
mSession.startPreview();
mClient.startStream();
} else {
mSession.stopPreview();
mClient.stopStream();
}
}
#Override
public void onSessionError(int reason, int streamType, Exception e) {
switch (reason) {
case Session.ERROR_CAMERA_ALREADY_IN_USE:
break;
case Session.ERROR_CAMERA_HAS_NO_FLASH:
break;
case Session.ERROR_INVALID_SURFACE:
break;
case Session.ERROR_STORAGE_NOT_READY:
break;
case Session.ERROR_CONFIGURATION_NOT_SUPPORTED:
break;
case Session.ERROR_OTHER:
break;
}
if (e != null) {
e.printStackTrace();
}
}
#Override
public void onRtspUpdate(int message, Exception exception) {
switch (message) {
case RtspClient.ERROR_CONNECTION_FAILED:
exception.printStackTrace();
break;
case RtspClient.ERROR_WRONG_CREDENTIALS:
exception.printStackTrace();
break;
}
}
#Override
public void onPreviewStarted() {
}
#Override
public void onSessionConfigured() {
}
#Override
public void onSessionStarted() {
}
#Override
public void onSessionStopped() {
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
#Override
public void onBitrateUpdate(long bitrate) {
}
LOGCAT:
09-28 21:05:23.357 16654-16654/shkatovl.btandroid I/Timeline: Timeline: Activity_launch_request time:6595904
09-28 21:05:23.507 16654-16664/shkatovl.btandroid W/art: Suspending all threads took: 5.493ms
09-28 21:05:23.618 16654-16654/shkatovl.btandroid I/MediaStream: Phone supports the MediaCoded API
09-28 21:05:23.678 16654-16937/shkatovl.btandroid D/RtspClient: Connecting to RTSP server...
09-28 21:05:23.778 16654-16654/shkatovl.btandroid D/VideoStream: Surface Changed !
09-28 21:05:23.908 16654-16935/shkatovl.btandroid V/VideoQuality: Supported resolutions: 1920x1080, 1280x720, 1280x960, 800x480, 768x432, 720x480, 640x480, 576x432, 480x320, 384x288, 352x288, 320x240, 240x160, 192x112, 176x144
09-28 21:05:23.908 16654-16935/shkatovl.btandroid V/VideoQuality: Supported frame rates: 15-15fps, 12-24fps
09-28 21:05:23.978 16654-16654/shkatovl.btandroid D/VideoStream: Surface Changed !
09-28 21:05:23.998 16654-16654/shkatovl.btandroid I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#3254450a time:6596541
09-28 21:05:24.118 16654-16654/shkatovl.btandroid W/System.err: java.net.ConnectException: failed to connect to /176.120.25.62 (port 1235): connect failed: ECONNREFUSED (Connection refused)
09-28 21:05:24.118 16654-16937/shkatovl.btandroid I/RtspClient: TEARDOWN rtsp://176.120.25.62:1235/ RTSP/1.0
09-28 21:05:24.118 16654-16654/shkatovl.btandroid W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:124)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:163)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at java.net.Socket.startupSocket(Socket.java:590)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at java.net.Socket.tryAllAddresses(Socket.java:128)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at java.net.Socket.<init>(Socket.java:178)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at java.net.Socket.<init>(Socket.java:150)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at net.majorkernelpanic.streaming.rtsp.RtspClient.tryConnection(RtspClient.java:309)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at net.majorkernelpanic.streaming.rtsp.RtspClient.access$500(RtspClient.java:53)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at net.majorkernelpanic.streaming.rtsp.RtspClient$2.run(RtspClient.java:250)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at android.os.Looper.loop(Looper.java:135)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at android.os.HandlerThread.run(HandlerThread.java:61)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: Caused by: android.system.ErrnoException: connect failed: ECONNREFUSED (Connection refused)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at libcore.io.Posix.connect(Native Method)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:111)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:122)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: ... 13 more
So my question is where is my mistake(I added compile to gradle and permissions to manifest) or if you know ways to solve my problem, say me about it.
Thanks!

Related

SockettimeoutException and shutting down VM

I'm creating an Android project where the Registrationadmin activity connects to a PHP file (in a local server, localhost) using HttpURLConnection;
I am having problem while running the project i am getting this D/NetworkSecurityConfig: Using Network Security Config from resource network_security_config debugBuild: true
I have already given the connection and read timeout.
Registrationadmin.java code is:
public void btnregisteradm(View v) {
if (awesomeValidation.validate()) {
admname = name.getText().toString();
admpass = password.getText().toString();
admemail = email.getText().toString();
admmob = mob.getText().toString();
//Toast.makeText(ctx, "we are here", Toast.LENGTH_SHORT).show();
String method = "register";
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.execute(method,admname,admemail,admpass,admmob);
finish();
}
}
my BackgroundTask.java is
package com.example.hp.healthcareapp;
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import static android.content.ContentValues.TAG;
/**
* Created by HP on 12/18/2017.
*/
public class BackgroundTask extends AsyncTask<String,Void,String> {
AlertDialog alertDialog;
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx =ctx;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(ctx).create();
alertDialog.setTitle("Login Information....");
}
#Override
protected String doInBackground(String... params) {
String reg_url = "http://10.14.83.2:8080/register.php";
String login_url = "http://192.168.2.4:8080/login.php";
String method = params[0];
if (method.equals("register")) {
String admname = params[1];
//Log.d(TAG,admname);
String admemail = params[2];
String admpass = params[3];
String admmob = params[4];
try {
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(15000);
//httpURLConnection.setDoInput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("admname", "UTF-8")+"="+URLEncoder.encode(admname, "UTF-8") + "&" +
URLEncoder.encode("admemail", "UTF-8")+"="+URLEncoder.encode(admemail, "UTF-8") + "&" +
URLEncoder.encode("admpass", "UTF-8")+"="+URLEncoder.encode(admpass, "UTF-8")+"&"+
URLEncoder.encode("admmob", "UTF-8")+"="+URLEncoder.encode(admmob, "UTF-8");
Log.d(TAG,data);
httpURLConnection.connect();
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
//httpURLConnection.connect();
httpURLConnection.disconnect();
return "Registration Success...";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(method.equals("login"))
{
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
if(result.equals("Registration Success..."))
{
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
else
{
alertDialog.setMessage(result);
alertDialog.show();
}
}
}
register.php is
<?php
echo "this is it";
require "init.php";
$admmane = (isset($_POST['admname']) ) ? $_POST['admname'] : '';
$admpass = (isset($_POST['admpass']) ) ? $_POST['admpass'] : '';
$admemail = (isset($_POST['admemail']) ) ? $_POST['admemail'] : '';
$admmob=(isset($_POST['admmob']) ) ? $_POST['admmob'] : '';
//$admmane = "sdf";
//$admpassword = "sdf";
//$admemail = "sdf#r54";
//$admmob="sdf";
$sql_query= "insert into admin values ('$admmane','$admemail','$admpass','$admmob');";
if(mysqli_query($con, $sql_query)){
echo '{"message":"able to save the data to the database."}';
}
?>
logcat which i am getting on running the project is:
12-19 11:24:48.803 2555-2560/com.example.hp.healthcareapp I/zygote: Increasing code cache capacity to 1024KB
12-19 11:24:55.026 2555-3178/com.example.hp.healthcareapp D/NetworkSecurityConfig: Using Network Security Config from resource network_security_config debugBuild: true
12-19 11:24:55.048 2555-3178/com.example.hp.healthcareapp D/ContentValues: admname=shaista&admemail=shaista8080%40gmail.com&admpass=Pro%401234&admmob=9593626313
12-19 11:24:55.277 2555-2618/com.example.hp.healthcareapp D/EGL_emulation: eglMakeCurrent: 0x9f1840c0: ver 2 0 (tinfo 0x9f183300)
12-19 11:24:55.393 2555-2618/com.example.hp.healthcareapp D/EGL_emulation: eglMakeCurrent: 0x9f1840c0: ver 2 0 (tinfo 0x9f183300)
12-19 11:24:55.481 2555-2618/com.example.hp.healthcareapp D/EGL_emulation: eglMakeCurrent: 0x9f1840c0: ver 2 0 (tinfo 0x9f183300)
12-19 11:24:55.495 2555-2618/com.example.hp.healthcareapp D/OpenGLRenderer: endAllActiveAnimators on 0x8bb11880 (RippleDrawable) with handle 0x9f183b50
12-19 11:25:05.057 2555-3178/com.example.hp.healthcareapp W/System.err: java.net.SocketTimeoutException: timeout
12-19 11:25:05.058 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.okio.Okio$3.newTimeoutException(Okio.java:212)
12-19 11:25:05.059 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.okio.AsyncTimeout.exit(AsyncTimeout.java:261)
12-19 11:25:05.059 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.okio.AsyncTimeout$2.read(AsyncTimeout.java:215)
12-19 11:25:05.060 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:306)
12-19 11:25:05.061 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:300)
12-19 11:25:05.063 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:196)
12-19 11:25:05.065 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.internal.http.Http1xStream.readResponse(Http1xStream.java:186)
12-19 11:25:05.065 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.internal.http.Http1xStream.readResponseHeaders(Http1xStream.java:127)
12-19 11:25:05.067 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:737)
12-19 11:25:05.067 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:609)
12-19 11:25:05.068 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:471)
12-19 11:25:05.071 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:407)
12-19 11:25:05.071 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:244)
12-19 11:25:05.072 2555-3178/com.example.hp.healthcareapp W/System.err: at com.example.hp.healthcareapp.BackgroundTask.doInBackground(BackgroundTask.java:70)
12-19 11:25:05.072 2555-3178/com.example.hp.healthcareapp W/System.err: at com.example.hp.healthcareapp.BackgroundTask.doInBackground(BackgroundTask.java:25)
12-19 11:25:05.073 2555-3178/com.example.hp.healthcareapp W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:333)
12-19 11:25:05.074 2555-3178/com.example.hp.healthcareapp W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:266)
12-19 11:25:05.076 2555-3178/com.example.hp.healthcareapp W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
12-19 11:25:05.077 2555-3178/com.example.hp.healthcareapp W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
12-19 11:25:05.077 2555-3178/com.example.hp.healthcareapp W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
12-19 11:25:05.078 2555-3178/com.example.hp.healthcareapp W/System.err: at java.lang.Thread.run(Thread.java:764)
12-19 11:25:05.079 2555-3178/com.example.hp.healthcareapp W/System.err: Caused by: java.net.SocketException: Socket closed
12-19 11:25:05.080 2555-3178/com.example.hp.healthcareapp W/System.err: at java.net.SocketInputStream.read(SocketInputStream.java:203)
12-19 11:25:05.080 2555-3178/com.example.hp.healthcareapp W/System.err: at java.net.SocketInputStream.read(SocketInputStream.java:139)
12-19 11:25:05.082 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.okio.Okio$2.read(Okio.java:136)
12-19 11:25:05.083 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.okio.AsyncTimeout$2.read(AsyncTimeout.java:211)
12-19 11:25:05.083 2555-3178/com.example.hp.healthcareapp W/System.err: ... 18 more
12-19 11:25:05.085 2555-2555/com.example.hp.healthcareapp D/AndroidRuntime: Shutting down VM
12-19 11:25:05.089 2555-2555/com.example.hp.healthcareapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.hp.healthcareapp, PID: 2555
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at com.example.hp.healthcareapp.BackgroundTask.onPostExecute(BackgroundTask.java:95)
at com.example.hp.healthcareapp.BackgroundTask.onPostExecute(BackgroundTask.java:25)
at android.os.AsyncTask.finish(AsyncTask.java:695)
at android.os.AsyncTask.-wrap1(Unknown Source:0)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
can you please check whether below 2 API endpoints are working
You can check it using postman
Run app on server (put server ip from below urls)
String reg_url = "http://10.14.83.2:8080/register.php";
String login_url = "http://192.168.2.4:8080/login.php";
Make sure if these are working.that should return 200 response.
You can then check into database if registration data is getting saved.

service discovery failed, except on first connect

I'm connecting my Android phone to a HC-05 bluetooth module. It kinda works, I can get some I/O done, but I also get some errors. First error I want to deal with is that I get a "Service Discovery Failed" IO Exception every time I connect to my Bluetooth device, except the first time. Only after a reboot of the phone will it cleanly connect. So, I'd expect something left open, but the only thing I can think of is the socket, and I close that.
09-16 13:55:16.463 8085-8085/ltd.arctura.laro_can_bus I/BluetoothSocket_MTK: [JSR82] Bluetooth Socket Constructor
09-16 13:55:16.463 8085-8085/ltd.arctura.laro_can_bus I/BluetoothSocket_MTK: [JSR82] type=1 fd=-1 auth=false encrypt=false port=-1
09-16 13:55:16.466 8085-8085/ltd.arctura.laro_can_bus I/BluetoothSocket_MTK: [JSR82] connect: do SDP
09-16 13:55:16.738 8085-8098/ltd.arctura.laro_can_bus I/BluetoothSocket_MTK: [JSR82] SdpHelper::onRfcommChannelFound: channel=-1
09-16 13:55:16.757 8085-8085/ltd.arctura.laro_can_bus W/System.err: java.io.IOException: Service discovery failed
09-16 13:55:16.757 8085-8085/ltd.arctura.laro_can_bus W/System.err: at android.bluetooth.BluetoothSocket$SdpHelper.doSdp(BluetoothSocket.java:813)
09-16 13:55:16.758 8085-8085/ltd.arctura.laro_can_bus W/System.err: at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:382)
09-16 13:55:16.758 8085-8085/ltd.arctura.laro_can_bus W/System.err: at ltd.arctura.laro_can_bus.bluetooth$1.onItemClick(bluetooth.java:173)
09-16 13:55:16.758 8085-8085/ltd.arctura.laro_can_bus W/System.err: at android.widget.AdapterView.performItemClick(AdapterView.java:298)
09-16 13:55:16.758 8085-8085/ltd.arctura.laro_can_bus W/System.err: at android.widget.AbsListView.performItemClick(AbsListView.java:1128)
09-16 13:55:16.759 8085-8085/ltd.arctura.laro_can_bus W/System.err: at android.widget.AbsListView$PerformClick.run(AbsListView.java:2812)
09-16 13:55:16.759 8085-8085/ltd.arctura.laro_can_bus W/System.err: at android.widget.AbsListView$1.run(AbsListView.java:3571)
09-16 13:55:16.759 8085-8085/ltd.arctura.laro_can_bus W/System.err: at android.os.Handler.handleCallback(Handler.java:725)
09-16 13:55:16.759 8085-8085/ltd.arctura.laro_can_bus W/System.err: at android.os.Handler.dispatchMessage(Handler.java:92)
09-16 13:55:16.759 8085-8085/ltd.arctura.laro_can_bus W/System.err: at android.os.Looper.loop(Looper.java:153)
09-16 13:55:16.759 8085-8085/ltd.arctura.laro_can_bus W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5341)
09-16 13:55:16.760 8085-8085/ltd.arctura.laro_can_bus W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
09-16 13:55:16.760 8085-8085/ltd.arctura.laro_can_bus W/System.err: at java.lang.reflect.Method.invoke(Method.java:511)
09-16 13:55:16.760 8085-8085/ltd.arctura.laro_can_bus W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:929)
09-16 13:55:16.761 8085-8085/ltd.arctura.laro_can_bus W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
09-16 13:55:16.765 8085-8085/ltd.arctura.laro_can_bus W/System.err: at dalvik.system.NativeStart.main(Native Method)
Restarting the HC-05 or the bluetooth on the phone both are not enough.
I have verified the UUID is correct by doing:
ParcelUuid[] uuids=btHC05.getUuids();
if (uuids != null) {
msg(uuids[0].toString());
} else {
msg("No UUID!?");
}
This yields the same UUID as I had configured.
I tried to do a .close on the socket, but that's not helping. I have no input or output streams to close.
The device is already paired and proved to work. I generally don't understand how the Connect() can throw a service discovery failed.. I wouldn't expect the connect() to do any discovery..
private BluetoothAdapter myBluetooth = null;
myBluetooth = BluetoothAdapter.getDefaultAdapter();
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
String address = null;
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
and
try {
if (btSocket == null) {
BluetoothDevice btHC05 = myBluetooth.getRemoteDevice(address);
btSocket = btHC05.createInsecureRfcommSocketToServiceRecord(myUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();
}
}
catch (IOException e){
Toast.makeText(getApplicationContext(), "Error: " + e.toString(), Toast.LENGTH_LONG).show();
ConnectSuccess = false;
}
if (!ConnectSuccess)
{
finish();
}
else {
msg("Connected.");
Intent returnIntent = new Intent();
returnIntent.putExtra("address",address);
setResult(MainActivity.RESULT_OK,returnIntent);
finish();
}
}
There is some more, but this is what is relevant.. It's a bit messy because I've been trialling-erroring a lot ;-)
Also, and this might be relevant. All this happens in a separate activity that gives the user a list of BT-devices to choose from, and then goes back to the Main_Activity.

Getting NetworkOnMainThreadException while implementing Runnable [duplicate]

This question already has answers here:
NetworkOnMainThreadException [duplicate]
(5 answers)
Closed 7 years ago.
I'm getting NetworkOnMainThreadException while using Runnable
Code:
public class FullscreenActivity extends AppCompatActivity {
public Socket socket;
public int SERVERPORT = 5000; /* port 5000 (for testing) */
public String SERVER_IP = "10.0.2.2"; /* local Android address of localhost */
ViewFlipper flipper;
ListView listing;
public void attemptConnect(View view) {
try {
EditText editTextAddress = (EditText) findViewById(R.id.address);
EditText editTextPort = (EditText) findViewById(R.id.port);
String SERVER_IP_loc = editTextAddress.getText().toString();
int SERVERPORT_loc = Integer.parseInt(editTextPort.getText().toString());
System.out.println("Attempt Connect: IP " + SERVER_IP_loc + " Port: " + SERVERPORT_loc);
System.out.println("SET");
ClientThread myClientTask = new ClientThread(SERVER_IP_loc, SERVERPORT_loc);
myClientTask.run();
System.out.println("CONNECTED");
flipper.setDisplayedChild(1);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
// Thinks the following is not a thread ??
class ClientThread implements Runnable {
ClientThread(String addr, int port) {
SERVER_IP = addr;
SERVERPORT = port;
}
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
// gets to this line fine
socket = new Socket(serverAddr, SERVERPORT);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
}
My permissions are set up to allow internet access:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
I'm getting the following error:
6188-6188/test W/System.err: android.os.NetworkOnMainThreadException
6188-6188/test W/System.err: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
6188-6188/test W/System.err: at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:110)
6188-6188/test W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
6188-6188/test W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:122)
6188-6188/test W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
6188-6188/test W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:163)
6188-6188/test W/System.err: at java.net.Socket.startupSocket(Socket.java:592)
6188-6188/test W/System.err: at java.net.Socket.<init>(Socket.java:226)
6188-6188/test W/System.err: at test.FullscreenActivity$ClientThread.run(FullscreenActivity.java:363)
6188-6188/test W/System.err: at test(FullscreenActivity.java:340)
6188-6188/test W/System.err: at java.lang.reflect.Method.invoke(Native Method)
6188-6188/test W/System.err: at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(test:270)
6188-6188/test W/System.err: at android.view.View.performClick(View.java:5198)
6188-6188/test W/System.err: at android.view.View$PerformClick.run(View.java:21147)
6188-6188/test W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
6188-6188/test W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
6188-6188/test W/System.err: at android.os.Looper.loop(Looper.java:148)
6188-6188/test W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5417)
6188-6188/test W/System.err: at java.lang.reflect.Method.invoke(Native Method)
6188-6188/test W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
6188-6188/test W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
As far as I can tell, this should function as expected. It seems to think the Runnable isn't a thread, but I can't figure out why.
You need a Thread to run your Runnable for you. Simply calling run on a Runnable does not run it on a different thread.
new Thread(new ClientThread(SERVER_IP_loc, SERVERPORT_loc)).start();

Error while using HttpConnection

QUESTION
I am trying to parse an XML file from a website. I am using an HTTP connection for getting the XML content from the website. While I am downloading the content I am facing some issues. The code is given below.
CODE
public class MainActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button= (Button) findViewById(R.id.button);
}
public void process(View view) {
Thread thread=new Thread(new Download());
thread.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class Download implements Runnable {
public void run() {
try {
URL url = new URL("http://api.androidhive.info/pizza/?format=xml");
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.getDoOutput();
InputStream stream = connection.getInputStream();
Toast.makeText(MainActivity.this, stream + "", Toast.LENGTH_LONG).show();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
} }
This is the code I am using to download the content. The error I am getting is
ERROR
10-21 01:14:21.459 25125-25181/com.example.sajithm.domparsing W/System.err﹕ java.net.UnknownHostException: Unable to resolve host "api.androidhive.info": No address associated with hostname
10-21 01:14:21.459 25125-25181/com.example.sajithm.domparsing W/System.err﹕ at java.net.InetAddress.lookupHostByName(InetAddress.java:424)
10-21 01:14:21.459 25125-25181/com.example.sajithm.domparsing W/System.err﹕ at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
10-21 01:14:21.459 25125-25181/com.example.sajithm.domparsing W/System.err﹕ at java.net.InetAddress.getAllByName(InetAddress.java:214)
10-21 01:14:21.459 25125-25181/com.example.sajithm.domparsing W/System.err﹕ at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
10-21 01:14:21.459 25125-25181/com.example.sajithm.domparsing W/System.err﹕ at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
10-21 01:14:21.459 25125-25181/com.example.sajithm.domparsing W/System.err﹕ at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
10-21 01:14:21.459 25125-25181/com.example.sajithm.domparsing W/System.err﹕ at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
10-21 01:14:21.459 25125-25181/com.example.sajithm.domparsing W/System.err﹕ at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
10-21 01:14:21.459 25125-25181/com.example.sajithm.domparsing W/System.err﹕ at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
10-21 01:14:21.459 25125-25181/com.example.sajithm.domparsing W/System.err﹕ at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
10-21 01:14:21.459 25125-25181/com.example.sajithm.domparsing W/System.err﹕ at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
10-21 01:14:21.459 25125-25181/com.example.sajithm.domparsing W/System.err﹕ at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
10-21 01:14:21.459 25125-25181/com.example.sajithm.domparsing W/System.err﹕ at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)
10-21 01:14:21.459 25125-25181/com.example.sajithm.domparsing W/System.err﹕ at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
10-21 01:14:21.459 25125-25181/com.example.sajithm.domparsing W/System.err﹕ at com.example.sajithm.domparsing.MainActivity$Download.run(MainActivity.java:65)
10-21 01:14:21.459 25125-25181/com.example.sajithm.domparsing W/System.err﹕ at java.lang.Thread.run(Thread.java:841)
10-21 01:14:21.459 25125-25181/com.example.sajithm.domparsing W/System.err﹕ Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
10-21 01:14:21.459 25125-25181/com.example.sajithm.domparsing W/System.err﹕ at libcore.io.Posix.getaddrinfo(Native Method)
10-21 01:14:21.459 25125-25181/com.example.sajithm.domparsing W/System.err﹕ at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61)
10-21 01:14:21.459 25125-25181/com.example.sajithm.domparsing W/System.err﹕ at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
10-21 01:14:21.459 25125-25181/com.example.sajithm.domparsing W/System.err﹕ ... 15 more
--------- beginning of /dev/log/system
10-21 01:19:34.259 25125-25131/com.example.sajithm.domparsing D/dalvikvm﹕ GC_FOR_ALLOC freed 306K, 4% free 9003K/9336K, paused 5ms, total 5ms
REQUEST
The web address is valid. Can anyone please suggest a solution to tackle this problem. Is there any other way to download the content?
I have tried below code and it worked :
Method to make a call :
public void makeXMLRequest() {
try {
URL url = new URL("http://api.androidhive.info/pizza/?format=xml");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.getDoOutput();
String readStream = readStream(con.getInputStream());
// Give output for the command line
System.out.println(readStream);
} catch (Exception e) {
e.printStackTrace();
}
}
Reference method to parse response :
private static String readStream(InputStream in) {
StringBuilder sb = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(in));) {
String nextLine = "";
while ((nextLine = reader.readLine()) != null) {
sb.append(nextLine);
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
How to call this method :
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
makeXMLRequest();
}
});
thread.start();
Try this if it can help.
Thanks..!
Though you can access the website by web browser of your computer. I can access the link as well.
But it doesn't mean your Android phone can resolve the domain name.
Please use adb shell to try
ping api.androidhive.info
You will most probably see a negative response.
This is a problem with emulator. In some cases emulator cannot access websites though the site is accessible through our pc browser. I reinstalled the virtual device (In my case it was Nexus 4.3) inside Genymotion,now everything works fine and the emulator is capable to access all websites.
Thank you

RXJava Android - Network exception when trying to pull RSS feed

I currently am trying to pull down an RSS Feed as an XML file and I'm trying to use RXJava instead of an AsyncTask to parse and download the file.
I'm getting a network on the main thread error though while I'm trying to pull the feed down.
Here is the relevant code with observable which is in the main activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.rv_test_items);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
final ArrayList<TestItem> testItems = new ArrayList<>();
//testItems.add(new TestItem("Title here", "Content here"));
RssReader reader = new RssReader("http://www.feedforall.com/sample.xml");
// Subscribe on a new background thread, while returning the result on the UI thread.
// Using the RSS Classes we will pull the rss items from the rss feed and then create our
// own TestItem from them.
try {
Observable
.from(reader.getItems())
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<RssItem>() {
#Override
public void call(RssItem item) {
TestItem newItem = new TestItem(item.getTitle(), item.getDescription());
testItems.add(newItem);
}
});
} catch (Exception e) {
e.printStackTrace();
Log.e("App", "Failed to download RSS Items");
}
TestItemAdapter testItemAdapter = new TestItemAdapter(testItems);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(testItemAdapter);
And here is my RSSReader class
public class RssReader {
private String rssUrl;
public RssReader(String url) {
rssUrl = url;
}
public List<RssItem> getItems() throws Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
//Creates a new RssHandler which will do all the parsing.
RssHandler handler = new RssHandler();
//Pass SaxParser the RssHandler that was created.
saxParser.parse(rssUrl, handler);
return handler.getRssItemList();
}
}
And my RSSHandler class
public class RssHandler extends DefaultHandler {
private List<RssItem> rssItemList;
private RssItem currentItem;
private boolean parsingTitle;
private boolean parsingLink;
private boolean parsingDescription;
public RssHandler() {
//Initializes a new ArrayList that will hold all the generated RSS items.
rssItemList = new ArrayList<RssItem>();
}
public List<RssItem> getRssItemList() {
return rssItemList;
}
//Called when an opening tag is reached, such as <item> or <title>
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equals("item"))
currentItem = new RssItem();
else if (qName.equals("title"))
parsingTitle = true;
else if (qName.equals("link"))
parsingLink = true;
else if (qName.equals("description"))
parsingDescription = true;
else if (qName.equals("media:thumbnail") || qName.equals("media:content") || qName.equals("image")) {
if (attributes.getValue("url") != null)
currentItem.setImageUrl(attributes.getValue("url"));
}
}
//Called when a closing tag is reached, such as </item> or </title>
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals("item")) {
//End of an item so add the currentItem to the list of items.
rssItemList.add(currentItem);
currentItem = null;
} else if (qName.equals("title"))
parsingTitle = false;
else if (qName.equals("link"))
parsingLink = false;
else if (qName.equals("description"))
parsingDescription = false;
}
//Goes through character by character when parsing whats inside of a tag.
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (currentItem != null) {
//If parsingTitle is true, then that means we are inside a <title> tag so the text is the title of an item.
if (parsingTitle)
currentItem.setTitle(new String(ch, start, length));
//If parsingLink is true, then that means we are inside a <link> tag so the text is the link of an item.
else if (parsingLink)
currentItem.setLink(new String(ch, start, length));
//If parsingDescription is true, then that means we are inside a <description> tag so the text is the description of an item.
else if (parsingDescription)
currentItem.setDescription(new String(ch, start, length));
}
}
}
Stack trace
10-07 11:39:15.040 1959-1959/? I/art: Late-enabling -Xcheck:jni
10-07 11:39:15.208 1959-1959/? W/System.err: java.io.IOException: Couldn't open http://www.feedforall.com/sample.xml
10-07 11:39:15.208 1959-1959/? W/System.err: at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:755)
10-07 11:39:15.208 1959-1959/? W/System.err: at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:292)
10-07 11:39:15.208 1959-1959/? W/System.err: at javax.xml.parsers.SAXParser.parse(SAXParser.java:390)
10-07 11:39:15.208 1959-1959/? W/System.err: at javax.xml.parsers.SAXParser.parse(SAXParser.java:266)
10-07 11:39:15.208 1959-1959/? W/System.err: at com.polymorphicinc.retrofitsample.rss.RssReader.getItems(RssReader.java:36)
10-07 11:39:15.208 1959-1959/? W/System.err: at com.polymorphicinc.retrofitsample.ui.MainActivity.onCreate(MainActivity.java:47)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.Activity.performCreate(Activity.java:5990)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.ActivityThread.access$800(ActivityThread.java:151)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.os.Looper.loop(Looper.java:135)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5254)
10-07 11:39:15.208 1959-1959/? W/System.err: at java.lang.reflect.Method.invoke(Native Method)
10-07 11:39:15.209 1959-1959/? W/System.err: at java.lang.reflect.Method.invoke(Method.java:372)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
10-07 11:39:15.209 1959-1959/? W/System.err: Caused by: android.os.NetworkOnMainThreadException
10-07 11:39:15.209 1959-1959/? W/System.err: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
10-07 11:39:15.209 1959-1959/? W/System.err: at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
10-07 11:39:15.209 1959-1959/? W/System.err: at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
10-07 11:39:15.209 1959-1959/? W/System.err: at java.net.InetAddress.getAllByName(InetAddress.java:215)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:332)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:199)
10-07 11:39:15.209 1959-1959/? W/System.err: at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:753)
10-07 11:39:15.209 1959-1959/? W/System.err: ... 18 more
10-07 11:39:15.209 1959-1959/? E/App: Failed to download RSS Items
10-07 11:39:15.215 1959-1978/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
10-07 11:39:15.216 1959-1959/? D/: HostConnection::get() New Host Connection established 0xb42d9a00, tid 1959
10-07 11:39:15.219 1959-1959/? D/Atlas: Validating map...
10-07 11:39:15.281 1959-1978/? D/libEGL: loaded /system/lib/egl/libEGL_emulation.so
10-07 11:39:15.282 1959-1978/? D/libEGL: loaded /system/lib/egl/libGLESv1_CM_emulation.so
10-07 11:39:15.286 1959-1978/? D/libEGL: loaded /system/lib/egl/libGLESv2_emulation.so
10-07 11:39:15.295 1959-1978/? D/: HostConnection::get() New Host Connection established 0xb42d9b90, tid 1978
10-07 11:39:15.311 1959-1978/? I/OpenGLRenderer: Initialized EGL, version 1.4
10-07 11:39:15.360 1959-1978/? D/OpenGLRenderer: Enabling debug mode 0
10-07 11:39:15.381 1959-1978/? W/EGL_emulation: eglSurfaceAttrib not implemented
10-07 11:39:15.381 1959-1978/? W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xb424bb40, error=EGL_SUCCESS
Take a look at this to get an idea how to do it:
public class RssReader {
private String rssUrl;
public RssReader(String url) {
rssUrl = url;
}
public Observable<List<RssItem>> getItems() {
return Observable.create(new Observable.OnSubscribe<List<RssItem>>() {
#Override
public void call(Subscriber<? super List<RssItem>> subscriber) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
//Creates a new RssHandler which will do all the parsing.
RssHandler handler = new RssHandler();
//Pass SaxParser the RssHandler that was created.
saxParser.parse(rssUrl, handler);
subscriber.onNext(handler.getRssItemList());
subscriber.onCompleted();
} catch (Exception e) {
subscriber.onError(e);
}
}
});
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.rv_test_items);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
RssReader reader = new RssReader("http://www.feedforall.com/sample.xml");
reader.getItems()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<List<RssItem>>() {
#Override
public void call(List<RssItem> items) {
final ArrayList<TestItem> testItems = new ArrayList<>(items.size());
for (int size = items.size(), i = 0; i < size; i++) {
RssItem item = items.get(i);
testItems.add(new TestItem(item.getTitle(), item.getDescription()));
}
recyclerView.setAdapter(new TestItemAdapter(testItems));
}
}, new Action1<Throwable>() {
#Override
public void call(Throwable e) {
e.printStackTrace();
Log.e("App", "Failed to download RSS Items");
}
});
}
try this
Observable.defer(() -> Observable.from(reader.getItems())
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<RssItem>() {
#Override
public void call(RssItem item) {
TestItem newItem = new TestItem(item.getTitle(), item.getDescription());
testItems.add(newItem);
}
});

Categories

Resources