I am new to Android Programming. This is my first app. As part of the app, when i click on a button, I am trying to connect to a URL using the HTTP URL Connect method described on the android documentation. However, my app force closes the moment I click on the button. I have added Internet access and Access Network State permissions in my manifest file as well. Following is my code :
public class GET_PNR extends Activity implements OnClickListener {
private String readStream(InputStream is) {
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int i = is.read();
while(i != -1) {
bo.write(i);
i = is.read();
}
return bo.toString();
} catch (IOException e) {
return "";
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get__pnr);
View txtview = findViewById(R.id.get_pnr);
txtview.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.get__pnr, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
TextView pnrview = (TextView) findViewById(R.id.PNR);
CharSequence input;
input = pnrview.getText();
System.out.println(input);
String result;
HttpURLConnection urlConnection = null;
try{
URL url = new URL("http://www.google.com/");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
result = readStream(in);
System.out.println(result);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
}
}
Some help in this regard will be much appreciated. Thanks!