Issue
I am new to android. I am learning android networking now. I am trying to create a connection with HttpURLConnection to track the response code as 200, but I am getting IllegalArgumentException. I am doing this with Async task but couldn't rectify. Any help would be appreciated.
Here is my code :
package com.movies.usman.moviesmesh;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new CheckConnectionStatus().execute("http://google.com");
}
class CheckConnectionStatus extends AsyncTask<String, Void, String>
{
@Override
protected String doInBackground(String... params) {
URL url = null;
try {
url = new URL(params[0]);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//Log.i("Reponse: ", String.valueOf(urlConnection.getResponseCode()));
return String.valueOf(urlConnection.getResponseCode());
} catch (IOException e) {
Log.e("Error: ", e.getMessage(), e);
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
text.setText(s);
}
}
}
Solution
You should initialize your TextView in onCreate
text = (TextView) findViewById(R.id.yourViewId);
before of
new CheckConnectionStatus().execute("http://google.com");
Answered By - Sal
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.