Android : AsynkTask and HttpConnection errors - java

i'm new in java and android programming , and by following some tutorial i've tried to make an Android App that have to make a Http request to a php page for reading the output string. I get the following errorr in doInBackground method :
Multiple markers at this line
- Exception MalformedURLException is not compatible with throws clause in
AsyncTask<Void,String,String>.doInBackground(Void[])
- Exception IOException is not compatible with throws clause in AsyncTask<Void,String,String>.doInBackground(Void[])
- Exception IOException is not compatible with throws clause in AsyncTask<Void,String,String>.doInBackground(Void[])
- implements android.os.AsyncTask<java.lang.Void,java.lang.String,java.lang.String>.doInBackground
- Exception MalformedURLException is not compatible with throws clause in
AsyncTask<Void,String,String>.doInBackground(Void[])
Any idea ?
Thank You
That's the MainActivity.java code :
public class MainActivity extends Activity {
Button button;
TextView finalResult;
public class ConnessioneAsyncTask extends AsyncTask<Void,String,String>{
#Override
public String doInBackground(Void... v) throws IOException, MalformedURLException{
try{
URL url = new URL("http://myUrl");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = read.readLine();
String html = "";
while (line != null){
html += line;
line = read.readLine();
}
return html;
}
catch(MalformedURLException ex){
System.out.println(ex.getMessage());
}
catch(Exception ee){
System.out.println(ee.getMessage());
}
}
#Override
public void onPreExecute(){
}
#Override
public void onPostExecute(String result){
finalResult.setText(result);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.asynkButton);
finalResult = (TextView) findViewById(R.id.textView1);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
ConnessioneAsyncTask runner = new ConnessioneAsyncTask();
runner.execute();
}
});
}
}

doInBackground Method does not declare any throws clause and you are trying to add throws declaration. you need to handle all exception with in your code only instead of declaring it using throws clause. Here is javadoc for the doInBackground method. So in a nutshell you need to remove throws clause in order to make it valid.

Related

Buffer with bufferedreader.readLine () returns null unexpectedly

I have problems using BufferedReader when I use readLine () it returns null value. This is my code:
How can I discover the source of the problem?
BackgroundTask_GET.java
public class BackgroundTask_GET extends AsyncTask<Void, Void, Void> {
String duongdan = MainActivity.SERVER_NAME;
TextView tvResult;
String strName, strScore;
String str;
ProgressDialog pDialog;
Context context;
public String TAG = "GG";
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Sending...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
public BackgroundTask_GET(Context context, TextView tvResult, String
strName, String strScore) {
this.tvResult = tvResult;
this.strName = strName;
this.strScore = strScore;
this.context = context;
}
#Override
protected Void doInBackground(Void... voids) {
duongdan += "?name=" + this.strName + "&score=" + this.strScore;
try {
URL url = new URL(duongdan);
HttpURLConnection urlConnection = (HttpURLConnection)
url.openConnection();
BufferedReader bfr = new BufferedReader(new
InputStreamReader(url.openStream()));
String line = "";
StringBuffer sb = new StringBuffer();
Log.d(TAG, "bfr:" + urlConnection);
while ((line = bfr.readLine()) != null) {
sb.append(line);
Log.d(TAG, "append"+sb.append(line));
}
str = sb.toString();
urlConnection.disconnect();
Log.d(TAG, "doInBackground: " + str);
} catch (MalformedURLException e) {
e.printStackTrace();
Log.d(TAG, "exception " + e);
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG, "exception " + e);
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (pDialog.isShowing()) {
pDialog.dismiss();
}
tvResult.setText(str);
Log.d("RESULT", "khanh" + str);
}
}
`` `MainActivity
public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
public static final String SERVER_NAME =
"http://192.168.1.2/AndroidNetworking_server/student_GET.php";
private EditText edtName, edtScore;
private Button btnSend;
private TextView tvResult;
String strName, strScore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtName = findViewById(R.id.edtName);
edtScore = findViewById(R.id.edtScore);
btnSend = findViewById(R.id.btnSend);
tvResult = findViewById(R.id.tvResult);
btnSend.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch(view.getId()) {
case R.id.btnSend:
strName = edtName.getText().toString();
strScore = edtScore.getText().toString();
BackgroundTask_GET backgroundTask = new
BackgroundTask_GET(this, tvResult, strName, strScore);
backgroundTask.execute();
break;
}
}
}
Error:
~
` 1 `
2019-07-15 14:07:58.065 24764- 28936/com.example.lab2_khanhpd02377_androidnetworkingD/GG:bfr:com.android.okhttp.internal.huc.HttpURLConnectionImpl:http://192.168.1.2/AndroidNetworking_server/student_GET.php?name=4&score=5
~
` 2 `
2019-07-15 14:07:58.066 24764- 28936/com.example.lab2_khanhpd02377_androidnetworking D/GG: doInBackground:
I can see a couple of problems with your code:
The readLine() method returns the line with the line separator removed. So
while ((line = bfr.readLine()) != null) {
sb.append(line);
}
will strip line separators while reading.
You are not checking the HTTP response code. If the response code is not a 2xx code, then getInputStream() will throw an exception.
The response code can be found using getResponseCode(). The error response body can be read using getErrorStream().
As #user207421 says, you shouldn't call urlConnection.disconnect() unless you really need to disconnect. If you don't need to, it is better to let the HTTP client library deal with disconnection. (It may be able to keep the connection open, and use it for later requests to the same server.)
You should1 close the BufferedReader, and ideally you should do it using try-with-resources.
1 - I won't say must because there are scenarios where it won't matter. However, if you don't close the stream, one way or another, you will leak file descriptors which could lead to errors later on. And, it is certainly good practice to close streams ... because you never really know if your code might be used / reused in the future in some context where the resource leak does matter.
UPDATE - I think you are saying that the real real cause for the null / empty stream was on the PHP side. Notwithstanding that, you probably ought to address the four issues that I mentioned: line separators, response code, disconnect and using try-with-resource.

Cant get Json info on the app [duplicate]

This question already has answers here:
NetworkOnMainThreadException [duplicate]
(5 answers)
Closed 5 years ago.
Im just a beginner learning Json parsing and stream from the net,
well I dont get errors in this app but it doesnt display anything.
I dont know what the problem and cant see any problem in the log.
here is the code:
InputStream is;
String line;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text);
try {
URL url = new URL("https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&minlatitude=4&maxlatitude=5");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
is = new BufferedInputStream(connection.getInputStream());
if(connection.getInputStream()==null)
{
textView.setText("input stream empty");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
while((line=reader.readLine())!=null){
builder.append(line);
}
if(builder.toString().equals(""))
{
textView.setText("no work builder empty");
}
line=builder.toString();
JSONObject object = new JSONObject(line);
JSONArray fea = object.getJSONArray("features");
JSONObject QUAKE = fea.getJSONObject(0);
JSONObject pro = QUAKE.getJSONObject("properties");
int mag = pro.getInt("mag");
textView.setText(mag+"");
} catch (Exception e) {
e.printStackTrace();
}
}
Thanks!
A exception is thrown when an application attempts to perform a networking operation on its main thread. Hence the network call wouldn't take place in your case as you are making a network call on main thread and it would directly throw a NetworkOnMainThreadException instead of making a network call. Run your code in AsyncTask
well doing any network operation on main thread is crime in Android. You will be punished with network_operation_on_main_thread exception. You need take help from AsyncTask.
please try below code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text);
new LongOperation().execute("");
}
private class LongOperation extends AsyncTask<String, Void, String> {
String data = "input stream empty";
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL("https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&minlatitude=4&maxlatitude=5");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
is = new BufferedInputStream(connection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
while((line=reader.readLine())!=null){
builder.append(line);
}
if(builder.toString().equals(""))
{
data = "no work builder empty";
}
line=builder.toString();
JSONObject object = new JSONObject(line);
JSONArray fea = object.getJSONArray("features");
JSONObject QUAKE = fea.getJSONObject(0);
JSONObject pro = QUAKE.getJSONObject("properties");
int mag = pro.getInt("mag");
data = mag+"";
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
textView.setText(data);
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}

Asking the user for a URL to receive a JSON

Just as a practicing exercise i'm trying to make an app that fetches a JSON from a URL.
I found the following code in other thread here in stackoverflow and it works just fine. My problem is that the URL is hardcoded, and i need it to be an input by the user. What should i change/add?
public class MainActivity extends AppCompatActivity {
Button btnHit;
TextView txtJson;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnHit = (Button) findViewById(R.id.btnHit);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute("Url address here");
}
});
}
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
Log.d("Response: ", "> " + line); //here u ll get whole response..... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
txtJson.setText(result);
}
}
}
This is the thread where i got that code from:
Get JSON Data from URL Using Android?
Create a constructor in your async Task
private class JSONTask extends AsyncTask<String, String, String> {
String url;
public JSONTask(String url){
this.url=url;
}
use the url string in place of params[0]
And wherever you call your async task do it like this
new JSONTask(textView.getText()).execute()
This should solve it.
Else you can directly use the do in background variable params.
So the problem is that you are using a TextView. TextView does not recieve inputs.
EditText does.
Make these Changes:
TextView txtJson;
In your OnCreate change this:
txtJson = (EditText) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute(txtJson.getText());
}
});
Now in your xml file change the Button to EditText.
Hope this helps.

Android HTTP API call

I am pretty fresh with Android Studio, and I am trying to call MVC Api service with api key and app id.
However, whenever i try the one with api key and app id, it always throws "Trust anchor for certification path not found." while it works good when i try the one without api key.
Can you give me a advice? Thank you.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button)findViewById(R.id.button);
tv = (TextView)findViewById(R.id.textView);
btn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
new JSONTask().execute("");
}
});
}
public class JSONTask extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... params) {
try{
StringBuilder result = new StringBuilder();
URL url2 = new URL(url);
HttpURLConnection conn = (HttpURLConnection) url2.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Apikey",key);
conn.addRequestProperty("AppID",id);
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
catch (IOException e)
{
Log.e("MYAPP", "exception", e);
return "error";
}
}
protected void onPostExecute(String result)
{
super.onPostExecute(result);
tv.setText(result);
}
}
This kind of exceptions mostly occur because of the misconfiguration of a web service. Check out this article. It's fully described why you are getting this exception.

Android debugger and JSOUP: Source not found

I am trying to retrieve a website's html code and parse it to get the site's text. For some reason the class I have below runs fine when I comment out the jsoup library part of the code, but otherwise I get this weird error "source code not found", and the debug section does not hit any of the breakpoints. Not even those before any jsoup code. It jumps right to the error as soon as I hit the button on the emulator. I have the jsoup jar file added to my eclipse project as an external JAR in my java build path. What am I doing wrong?
BTW: I have jsoup 1.6.2
public class AndroidActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText eText = (EditText) findViewById(R.id.address);
final TextView tView = (TextView) findViewById(R.id.pagetext);
// TODO Auto-generated method stub
class TareaAsincrona extends AsyncTask<String, Void ,String>
{
#Override
protected void onPreExecute()
{
}
#Override
protected void onPostExecute(String X)
{
}
#Override
protected String doInBackground(String... urls)
{
try
{
// Perform action on click
URL url = new URL(eText.getText().toString());
URLConnection conn = url.openConnection();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
String Codigo_Fuente ="";
while ((line = rd.readLine()) != null)
{
Codigo_Fuente= Codigo_Fuente + line;
//Codigo_Fuente.add(line);//android.text.Html.fromHtml(line).toString());
}
Document doc = Jsoup.parse(Codigo_Fuente);
return doc.body().text();
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
}
final Button button = (Button) findViewById(R.id.ButtonGo);
button.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View arg0)
{
new TareaAsincrona().execute();
}
});
}
}
Did you add the library to the "libs" folder too?

Categories

Resources