Getting NetworkOnMainThreadException while implementing Runnable [duplicate] - java

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();

Related

File Writer Android

I am using the following code to write an onPostExecute process to file from my FileWriter.class, it was working fine but am updating my application and I have to use the Environment.getExternalStorageDirectory().getPath(); instead of this, i tried following. I know doing something slightly wrong. Any Help or direction would be helpful.
Thanks.
public class FileWriter {
public void appendData( String text) {
try {
File myFile = new File("/sdcard/latencyOP.csv");
// myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
if (myFile.createNewFile()) {
myOutWriter.append("TimeStamp,ExecutionTime,OperationType;");
}
myOutWriter.append(text);
myOutWriter.close();
fOut.close();
/**
* Toast.makeText(getBaseContext(),
* "Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
*/
} catch (Exception e) {
/**
* Toast.makeText(getBaseContext(), e.getMessage(),
* Toast.LENGTH_SHORT).show();
*/
}
}
}
EDIT
I forgot to add that I am attempting to do some background operations and publish results on the **FILE.csv** thread without having to manipulate threads.
UPDATED CODE #Leonardo Acevedo
try {
File myFile = new File(
Environment.getExternalStorageDirectory(),
"latencyOP.csv"
);
boolean needToCreateFile = !myFile.exists();
if (needToCreateFile) {
myFile.createNewFile();
}
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
// At this point your file is guaranteed to exist
if (needToCreateFile) {
myOutWriter.append("TimeStamp,ExecutionTime,OperationType;");
}
myOutWriter.append(text);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT
).show();
} catch (Exception e) {
e.printStackTrace();
displayExceptionMessage(e.getMessage());
//Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
public void displayExceptionMessage(String msg) {
//Toast.makeText(this, "Some Error Occured", Toast.LENGTH_SHORT).show();
}
ASYNCH TASK PROCESS
protected void onPreExecute(){ startTime = Calendar.getInstance().getTime().getTime();
}
protected void onPostExecute(Long result) {
endTime = Calendar.getInstance().getTime().getTime();
long timeDiff = endTime - startTime;
FileWriter fileWriter = new FileWriter();
String data = endTime + "," + timeDiff + "," + "Authentication" + ";";
fileWriter.appendData(data);
}
Is this wrong ?
03-14 20:42:52.062 17192-17192/com.demo.common.recordwritertest W/System.err: java.io.IOException: Permission denied
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at java.io.UnixFileSystem.createFileExclusively0(Native Method)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:280)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at java.io.File.createNewFile(File.java:948)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at com.demo.common.recordwritertest.utils.FileWriter.appendData(FileWriter.java:25)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at com.demo.common.recordwritertest.com.demo.common.recordwritertest.asynctasks.AuthenticationAsyncTask.onPostExecute(AuthenticationAsyncTask.java:119)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at com.demo.common.recordwritertest.com.demo.common.recordwritertest.asynctasks.AuthenticationAsyncTask.onPostExecute(AuthenticationAsyncTask.java:27)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at android.os.AsyncTask.finish(AsyncTask.java:667)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at android.os.AsyncTask.-wrap1(AsyncTask.java)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:684)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at android.os.Looper.loop(Looper.java:154)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6119)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at java.lang.reflect.Method.invoke(Native Method)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Has been running on another Thread, but still thrown android.os.NetworkOnMainThreadException? [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 5 years ago.
public class Client extends AppCompatActivity {
public static final String TAG = Client.class.getSimpleName();
public static final int ServerPORT = 3000;
public static final String ServerIP = "10.146.166.86";
EditText message;
TextView mainView;
ClientThread clientThread;
Thread thread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
message = (EditText)findViewById(R.id.message);
mainView = (TextView)findViewById(R.id.mainView);
}
public void updateMessage(final String message) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mainView.append(message + "\n");
}
});
}
public void onClick(View view) {
if (view.getId() == R.id.connectServer) {
mainView.setText("");
clientThread = new ClientThread();
thread = new Thread(clientThread);
thread.start();
return;
}
if (view.getId() == R.id.sendMessage) {
Log.i(TAG, "Message sent from client");
clientThread.sendMessage(message.getText().toString());
}
}
class ClientThread implements Runnable {
private Socket socket;
private BufferedReader input;
#Override
public void run() {
try {
InetAddress serverAdd = InetAddress.getByName(ServerIP);
socket = new Socket(serverAdd, ServerPORT);
while (!Thread.currentThread().isInterrupted()) {
this.input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message = input.readLine();
if (null == message || "Disconnect".contentEquals(message)) {
Thread.interrupted();
message = "Server Disconnected.";
updateMessage(getTime() + " | Server : " + message);
break;
}
updateMessage(getTime() + " | Server : " + message);
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
}
void sendMessage(String message) {
try {
if (null != socket) {
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
String getTime() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
return sdf.format(new Date());
}
#Override
protected void onDestroy() {
super.onDestroy();
if (null != clientThread) {
clientThread.sendMessage("Disconnect");
clientThread = null;
}
}
}
I wrote a simple server-client TCP socket connection, and have been trying to connect between the host and the client. Although I already ran the network operations on the other Thread (not the mainThread), when I try to send a string from the client to my server, it throws
android.os.NetworkOnMainThreadException.
It seems even more weird to me because when I try switching the host and client devices, now I am able to send from the client to my server, but not from the server to the client. Then, I conclude that it should be due to one of my devices. One runs Android 8 and one runs Android 6, and it seems the problem belongs to the one running Android 8. Although I succesfully overcame this problem by adding:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
It seems really weird to me because the way it happens. Does it actually depend on the device?
Edit: Full error message. It's weird because it only happens with one of my devices. When I switch the roles between devices, it does its job successfully.
02-10 16:42:17.719 827-827/com.dev.kvuong2711.clienttcp I/Client: Message sent from client
02-10 16:42:17.720 827-827/com.dev.kvuong2711.clienttcp W/System.err: android.os.NetworkOnMainThreadException
02-10 16:42:17.721 827-827/com.dev.kvuong2711.clienttcp W/System.err: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1448)
02-10 16:42:17.721 827-827/com.dev.kvuong2711.clienttcp W/System.err: at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:108)
02-10 16:42:17.721 827-827/com.dev.kvuong2711.clienttcp W/System.err: at java.net.SocketOutputStream.write(SocketOutputStream.java:153)
02-10 16:42:17.721 827-827/com.dev.kvuong2711.clienttcp W/System.err: at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)
02-10 16:42:17.721 827-827/com.dev.kvuong2711.clienttcp W/System.err: at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:291)
02-10 16:42:17.721 827-827/com.dev.kvuong2711.clienttcp W/System.err: at sun.nio.cs.StreamEncoder.implFlush(StreamEncoder.java:295)
02-10 16:42:17.721 827-827/com.dev.kvuong2711.clienttcp W/System.err: at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:141)
02-10 16:42:17.721 827-827/com.dev.kvuong2711.clienttcp W/System.err: at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:229)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at java.io.BufferedWriter.flush(BufferedWriter.java:254)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at java.io.PrintWriter.newLine(PrintWriter.java:482)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at com.dev.kvuong2711.clienttcp.Client$ClientThread.sendMessage(Client.java:105)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at com.dev.kvuong2711.clienttcp.Client.onClick(Client.java:68)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at java.lang.reflect.Method.invoke(Native Method)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at android.view.View.performClick(View.java:6256)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at android.view.View$PerformClick.run(View.java:24779)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at android.os.Handler.handleCallback(Handler.java:789)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at android.os.Handler.dispatchMessage(Handler.java:98)
02-10 16:42:17.723 827-827/com.dev.kvuong2711.clienttcp W/System.err: at android.os.Looper.loop(Looper.java:180)
02-10 16:42:17.723 827-827/com.dev.kvuong2711.clienttcp W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6950)
02-10 16:42:17.723 827-827/com.dev.kvuong2711.clienttcp W/System.err: at java.lang.reflect.Method.invoke(Native Method)
02-10 16:42:17.723 827-827/com.dev.kvuong2711.clienttcp W/System.err: at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
02-10 16:42:17.723 827-827/com.dev.kvuong2711.clienttcp W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:835)
Your code in sendMessage is not running on another thread just because you put it in another class called "Thread". Only the run() method of a runnable is running on the other thread, when you call execute(). So you either have to call sendMessage in a new Thread() or put it in some kind of threadsafe variable or queue, that you check in your loop in the run() method and then send away.

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.

Caused by: android.system.ErrnoException: isConnected failed: ECONNREFUSED (Connection refused)

I'm using Android asyntask with Pycharm(python with flask) server and it will return an array. When i tried to connect with server it will show connection refused.
i need the solution why it shows the error like connection refused.
Android code:
public static String ip = "http://192.168.43.221:3000/";
private class BackTask extends AsyncTask<String, String, String> {
private String result = null,name,batch,id,dept,dob,phno,add,credits;
#Override
protected String doInBackground(String... params) {
try {
String data = URLEncoder.encode("device", "UTF-8") + "=" +
URLEncoder.encode(device, "UTF-8") + "&" +
URLEncoder.encode("ID", "UTF-8") + "=" +
URLEncoder.encode(regno1, "UTF-8") + "&" +
URLEncoder.encode("Password", "UTF-8") + "=" +
URLEncoder.encode(password1, "UTF-8");
BufferedReader reader = null;
Log.d("checking", data);
try {
URL url = new URL(ip + "login/");
URLConnection con = url.openConnection();
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(data);
writer.flush();
//getting response back
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
Toast.makeText(getBaseContext(),reader.readLine(),Toast.LENGTH_LONG).show();
StringBuilder s = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
s.append(line + "\n");
}
result = s.toString();
} catch (Exception e) {
// Toast.makeText(getBaseContext(),"Connection error",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
Toast.makeText(getBaseContext(),"Connection error",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
SharedPreferences.Editor e = sp1.edit();
if(!sp1.equals(null))
{
e.putString("uname", regno1);
e.putString("pass", password1);
e.apply();
}
// progress.dismiss();
//notification.setText(result);
if (result != null) {
Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
result = result.trim();
name= setDetails(result);
if (name.equals("success")) {
Intent intent1 = new Intent(LoginActivity.this, HrActivity.class);
//intent.putExtra("json",result);
startActivity(intent);
} else {
errormsg.setText("*Check id / password");
}
}
}
#Override
protected void onPreExecute() {
progress.show();
}
#Override
protected void onProgressUpdate(String... text) {
// progress. For example updating ProgessDialog
}
Logcat:
03-12 13:52:48.194 23394-23527/com.example.dinesh.eis W/System.err: at libcore.io.IoBridge.isConnected(IoBridge.java:267)
03-12 13:52:48.194 23394-23527/com.example.dinesh.eis W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:191)
03-12 13:52:48.194 23394-23527/com.example.dinesh.eis W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:127)
03-12 13:52:48.194 23394-23527/com.example.dinesh.eis W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:188)
03-12 13:52:48.194 23394-23527/com.example.dinesh.eis W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:461)
03-12 13:52:48.194 23394-23527/com.example.dinesh.eis W/System.err: at java.net.Socket.connect(Socket.java:918)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at com.android.okhttp.internal.Platform.connectSocket(Platform.java:174)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at com.android.okhttp.Connection.connect(Connection.java:152)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:282)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:216)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:391)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:217)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at com.example.dinesh.eis.LoginActivity$BackTask.doInBackground(LoginActivity.java:121)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at com.example.dinesh.eis.LoginActivity$BackTask.doInBackground(LoginActivity.java:101)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:292)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-12 13:52:48.197 23394-23527/com.example.dinesh.eis W/System.err: at java.lang.Thread.run(Thread.java:818)
03-12 13:52:48.197 23394-23527/com.example.dinesh.eis W/System.err: Caused by: android.system.ErrnoException: isConnected failed: ECONNREFUSED (Connection refused)
03-12 13:52:48.198 23394-23527/com.example.dinesh.eis W/System.err: at libcore.io.IoBridge.isConnected(IoBridge.java:252)
03-12 13:52:48.198 23394-23527/com.example.dinesh.eis W/System.err: ... 20 more
ECONNREFUSED is to mean a connection is attempted to a remote server,However the remote host is not answering back. This is much like knocking into someone's door and no one is replying back. There is no direct answer for your scnerio as many things can cause this along the way. Please have a look in this and this threads. They might give you some insight into the core issue, and from that you can start analyzing and debugging your code.

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!

Categories

Resources