I've seen this question, it's not my case, since I don't have backslashes in my url,
I have simple URL like, https://url.com/login
My Code,
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class LoginActivity extends AppCompatActivity {
URL url = new URL("https://url.net/login/");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
FloatingActionButton btn = (FloatingActionButton) findViewById(R.id.submitbtn);
EditText edtxt = (EditText) findViewById(R.id.usernm);
EditText edtxt2 = (EditText) findViewById(R.id.usrpwd);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),HomeActivity.class);
startActivity(i);
}
});
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
}
}
Screen shot:
When I hover on new URL();
, I get error as:
Unhandled Exception: java.net.MalformedURLException
That's why I'm getting another error at line,
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
in stack Trace I'm getting error as,
Error:(48, 13) error: cannot find symbol method readStream(InputStream)
When I hover on new URL();, I get error as:
The URL()
constructor throws java.net.MalformedURLException
. You need to wrap that constructor call in a try
/catch
block.
That's why I'm getting another error at line,
That is because getInputStream()
also throws checked exceptions. You need to wrap that code in a try
/catch
block.
That's the line of error and I'm getting error as Error:(48, 13) error: cannot find symbol method readStream(InputStream)
That is because you did not implement a method named readStream()
on this class.
All of this is covered in any decent book or course on Java programming.
Eventually, once you get past these compile errors, your code will crash at runtime with a NetworkOnMainThreadException
, as you cannot perform network I/O on the main application thread. You will need to move this HTTP code to a background thread, either one that you create yourself or by using an HTTP client API that can handle it for you (e.g., OkHttp).