Error while using HttpConnection - java

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

Related

Getting this error while login: at org.json.JSONTokener.syntaxError(JSONTokener.java:449) [duplicate]

I am implementing an android app and trying to make a register and login screens. my app is connected to a server, here is the part my code that makes error:
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error)
{
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
} else
{
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show();
Log.d("Debug", errorMsg);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.toString());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
and here is my error:
org.json.JSONException: End of input at character 0 of.
actually I have seen similar questions in this site but i was not be able to solve my problem
UPDATE:
this is my logcat content, and there is nothing in front of response:
1576-1576/com.example.neshat.androidhive2 D/RegisterActivity﹕ Register Response:
12-21 09:43:08.820 1576-1576/com.example.neshat.androidhive2 W/System.err﹕ org.json.JSONException: End of input at character 0 of
12-21 09:43:08.824 1576-1576/com.example.neshat.androidhive2 W/System.err﹕ at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
12-21 09:43:08.824 1576-1576/com.example.neshat.androidhive2 W/System.err﹕ at org.json.JSONTokener.nextValue(JSONTokener.java:97)
12-21 09:43:08.824 1576-1576/com.example.neshat.androidhive2 W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:156)
12-21 09:43:08.824 1576-1576/com.example.neshat.androidhive2 W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:173)
12-21 09:43:08.824 1576-1576/com.example.neshat.androidhive2 W/System.err﹕ at com.example.neshat.androidhive2.RegisterActivity$3.onResponse(RegisterActivity.java:124)
12-21 09:43:08.824 1576-1576/com.example.neshat.androidhive2 W/System.err﹕ at com.example.neshat.androidhive2.RegisterActivity$3.onResponse(RegisterActivity.java:116)
12-21 09:43:08.824 1576-1576/com.example.neshat.androidhive2 W/System.err﹕ at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
12-21 09:43:08.824 1576-1576/com.example.neshat.androidhive2 W/System.err﹕ at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
12-21 09:43:08.824 1576-1576/com.example.neshat.androidhive2 W/System.err﹕ at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
12-21 09:43:08.824 1576-1576/com.example.neshat.androidhive2 W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:739)
12-21 09:43:08.824 1576-1576/com.example.neshat.androidhive2 W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:95)
12-21 09:43:08.824 1576-1576/com.example.neshat.androidhive2 W/System.err﹕ at android.os.Looper.loop(Looper.java:135)
12-21 09:43:08.824 1576-1576/com.example.neshat.androidhive2 W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5221)
12-21 09:43:08.824 1576-1576/com.example.neshat.androidhive2 W/System.err﹕ at java.lang.reflect.Method.invoke(Native Method)
12-21 09:43:08.824 1576-1576/com.example.neshat.androidhive2 W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:372)
12-21 09:43:08.824 1576-1576/com.example.neshat.androidhive2 W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
12-21 09:43:08.824 1576-1576/com.example.neshat.androidhive2 W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
As you have seen in your logcat 1576-1576/com.example.neshat.androidhive2 D/RegisterActivity﹕ Register Response: which is the result of Log.d(TAG, "Register Response: " + response.toString());, response is an empty string, so your app will get org.json.JSONException: End of input at character 0 of at the line JSONObject jObj = new JSONObject(response);.
You should check response is not null and not an empty string first.
If you are using php to get the response, you should check on your php file. I had the same problem as you, i forgot to write the response on my php file. Below is part of my code that i forgot
$response = new emp();
$response->success = 1;
$response->message = "Register success, please login.";
die(json_encode($response));

Stream video from android to RTSP server

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!

android http conection using json keeps crashing app

hey guys i keep getting this error in my app when i try to get data from a server and read it as json and i am stuck because it doesnt happen all the time hear is the code
private class statusUpdateTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... urls) {
if(testServe("http://www.gogodis.comxa.com/getData.php")) {
HttpURLConnection conn = null;
BufferedReader reader = null;
try {
URL url = new URL(urls[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(is));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else{
retry(0);
}
return null;
}
#Override
protected void onPostExecute(String result) {
if(isJSONValid(result)) {
try {
JSONObject results = new JSONObject(result);
JSONArray jr = results.getJSONArray("results");
JSONObject set = jr.getJSONObject(0);
JSONObject info = set.getJSONArray("info").getJSONObject(0);
if (info.getString("state").equals("ok")) {
if (info.getInt("inbox") == 1) {
inbox.setImageResource(R.drawable.camr);
} else inbox.setImageResource(R.drawable.cam);
if (info.getInt("chat") == 1) {
chat.setImageResource(R.drawable.msgr);
} else chat.setImageResource(R.drawable.msg);
if(info.getInt("match") == 1){
new newMatchUpdateTask().execute("http://www.gogodis.comxa.com/getData.php?type=new_match&&user=" + my_user_id);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}else{
retry(0);
}
}
}
and hear is the logcast
05-30 15:05:11.205 5071-5394/com.reallyChat W/System.err: java.net.SocketTimeoutException
05-30 15:05:11.676 5071-5394/com.reallyChat W/System.err: at java.net.PlainSocketImpl.read(PlainSocketImpl.java:491)
05-30 15:05:11.676 5071-5394/com.reallyChat W/System.err: at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at java.io.InputStream.read(InputStream.java:163)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at java.io.BufferedInputStream.fillbuf(BufferedInputStream.java:142)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at java.io.BufferedInputStream.read(BufferedInputStream.java:227)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at libcore.io.Streams.readAsciiLine(Streams.java:201)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at libcore.net.http.HttpEngine.readResponseHeaders(HttpEngine.java:573)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at libcore.net.http.HttpEngine.readResponse(HttpEngine.java:821)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:283)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at com.really_chat.results$statusUpdateTask.doInBackground(results.java:968)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at com.really_chat.results$statusUpdateTask.doInBackground(results.java:953)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:287)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:234)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at java.lang.Thread.run(Thread.java:856)
05-30 15:05:11.696 5071-5071/com.reallyChat D/AndroidRuntime: Shutting down VM
05-30 15:05:11.706 5071-5071/com.reallyChat W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x411cd930)
05-30 15:05:11.726 5071-5071/com.reallyChat E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:154)
at org.json.JSONObject.<init>(JSONObject.java:171)
at com.really_chat.results.isJSONValid(results.java:1158)
at com.really_chat.results$statusUpdateTask.onPostExecute(results.java:989)
at com.really_chat.results$statusUpdateTask.onPostExecute(results.java:953)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5283)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
iv'e even tried to put in code that confirms its json but still no luck
public boolean isJSONValid(String test) {
try{
new JSONObject(test);
}catch(JSONException ex){
try{
new JSONArray(test);
}catch(JSONException ex1){
return false;
}
}
return true;
}
private boolean testServe(String url) {
try{
URL myUrl = new URL(url);
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(15000);
connection.connect();
return true;
} catch (Exception e) {
// Handle your exceptions
return false;
}
}
Try to change like this
conn.setReadTimeout(0 /* milliseconds */);//Infinite timeout
conn.setConnectTimeout(25000 /* milliseconds */);

Registration form android studio to connect to server

No errors occur within when emulator is run on my android phone. Not sure if that the correct http:192.168....... When I run the app i enter the data and it says connecting to server but then says unfortunately the app crashed. Any Ideas.
BackgroundTask
package com.example.om.fitnessproject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class BackgroundTask extends AsyncTask<String, Void, String > {
String register_url = "https://192.168.0.4/Fitnessplus/register.php";
Context ctx;
ProgressDialog progressDialog;
Activity activity;
AlertDialog.Builder builder;
public BackgroundTask(Context ctx){
this.ctx = ctx;
activity = (Activity)ctx;
}
#Override
protected void onPreExecute() {
builder = new AlertDialog.Builder(activity);
progressDialog = new ProgressDialog(ctx);
progressDialog.setTitle("Please wait");
progressDialog.setMessage("Connecting to server");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
String method = params [0];
if(method.equals("register"))
{
try {
URL url = new URL(register_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String name = params[1];
String email = params[2];
String password = params[3];
String data = URLEncoder.encode("name","UTF- 8")+"="+URLEncoder.encode(name,"UTF-8")+"&"+
URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(email, "UTF-8")+"&"+
URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while ((line=bufferedReader.readLine())!=null)
{
stringBuilder.append(line+"\n");
}
httpURLConnection.disconnect();
Thread.sleep(5000);
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String json) {
try {
progressDialog.dismiss();
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
JSONObject JO = jsonArray.getJSONObject(0);
String code = JO.getString("code");
String message = JO.getString("message");
if (code.equals("reg_true"))
{
showDialog("Registration Success", message,code);
}
else if(code.equals("reg_false"))
{
showDialog("Registration failed", message, code);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void showDialog(String title,String message,String code)
{
builder.setTitle(title);
if(code.equals("reg_true")||code.equals("reg_false"))
{
builder.setMessage(message);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
activity.finish();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
}
register
package com.example.om.fitnessproject;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class register extends AppCompatActivity {
EditText Name, Email, Pass, ConPass;
Button reg_button;
AlertDialog.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Name = (EditText)findViewById(R.id.reg_name);
Email = (EditText)findViewById(R.id.reg_email);
Pass = (EditText)findViewById(R.id.reg_password);
ConPass = (EditText)findViewById(R.id.reg_con_password);
reg_button = (Button)findViewById(R.id.reg_button);
reg_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Name.getText().toString().equals("") || Email.getText().toString().equals("") || Pass.getText().toString().equals("")) {
builder = new AlertDialog.Builder(register.this);
builder.setTitle("Something went wrong");
builder.setMessage("Please fill in all the field");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
} else if (!(Pass.getText().toString().equals(ConPass.getText().toString()))) {
builder = new AlertDialog.Builder(register.this);
builder.setTitle("Something went wrong");
builder.setMessage("Your passwords are not matching");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Pass.setText("");
ConPass.setText("");
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
else {
BackgroundTask backgroundTask = new BackgroundTask(register.this);
backgroundTask.execute("register",Name.getText().toString(),Email.getText().toString(),Pass.getText().toString());
}
}
});
}
}
Trace
04-18 20:42:35.360 26137-26137/? I/art: Late-enabling -Xcheck:jni
04-18 20:42:35.532 26137-26137/com.example.kieranbroom.fitnessproject W/System: ClassLoader referenced unknown path: /data/app/com.example.kieranbroom.fitnessproject-1/lib/arm64
04-18 20:42:36.458 26137-26209/com.example.kieranbroom.fitnessproject D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
04-18 20:42:36.520 26137-26209/com.example.kieranbroom.fitnessproject I/Adreno: QUALCOMM build : 63c06b2, I8366cd0437
Build Date : 10/21/15
OpenGL ES Shader Compiler Version: XE031.05.13.02
Local Branch :
Remote Branch : quic/LA.BF64.1.2.9_v2
Remote Branch : NONE
Reconstruct Branch : NOTHING
04-18 20:42:36.526 26137-26209/com.example.kieranbroom.fitnessproject I/OpenGLRenderer: Initialized EGL, version 1.4
04-18 20:42:59.950 26137-26209/com.example.kieranbroom.fitnessproject D/OpenGLRenderer: endAllStagingAnimators on 0x7f9623f800 (RippleDrawable) with handle 0x7f96234220
04-18 20:43:05.999 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
04-18 20:43:05.999 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImp l.java:328)
04-18 20:43:05.999 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.okhttp.internal.http.SocketConnector.connectTls(SocketConnector.java:103)
04-18 20:43:05.999 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.okhttp.Connection.connect(Connection.java:143)
04-18 20:43:05.999 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:185)
04-18 20:43:05.999 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:128)
04-18 20:43:06.000 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java: 341)
04-18 20:43:06.000 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
04-18 20:43:06.000 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
04-18 20:43:06.000 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:437)
04-18 20:43:06.000 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
04-18 20:43:06.000 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:245)
04-18 20:43:06.000 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218)
04-18 20:43:06.000 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java)
04-18 20:43:06.000 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.example.kieranbroom.fitnessproject.BackgroundTask.doInBackground(BackgroundTask.java:64)
04-18 20:43:06.000 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.example.kieranbroom.fitnessproject.BackgroundTask.doInBackground(BackgroundTask.java:26)
04-18 20:43:06.000 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:295)
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at java.lang.Thread.run(Thread.java:818)
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: Caused by: java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.org.conscrypt.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:318)
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.org.conscrypt.TrustManagerImpl.checkServerTrusted(TrustManagerImpl.java:219)
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.org.conscrypt.Platform.checkServerTrusted(Platform.java:115)
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.org.conscrypt.OpenSSLSocketImpl.verifyCertificateChain(OpenSSLSocketImpl.java:556)
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:324)
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: ... 20 more
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: Caused by: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
04-18 20:43:06.002 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: ... 26 more
04-18 20:43:06.010 26137-26137/com.example.kieranbroom.fitnessproject D/AndroidRuntime: Shutting down VM
04-18 20:43:06.010 26137-26137/com.example.kieranbroom.fitnessproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.kieranbroom.fitnessproject, PID: 26137
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:156)
at org.json.JSONObject.<init>(JSONObject.java:173)
at com.example.kieranbroom.fitnessproject.BackgroundTask.onPostExecute(BackgroundTask.java:115)
at com.example.kieranbroom.fitnessproject.BackgroundTask.onPostExecute(BackgroundTask.java:26)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

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