I have an android Activity
which crashes on making a HTTP GET request on the URL
http://developernetwork.net78.net/readUnivs.php.
The app simply has to make an HTTP GET request to the server, which will return a list of educational universities as plain text separated by \n
character. This list is then set as list data in a android.widget.Spinner
with the help of android.widget.ArrayAdapter
.
Here ia my PHP code on the server
<?php
$conn = mysqli_connect($url, $username, $passwd, $database_name);
$result = mysqli_query($conn, "SELECT University FROM Universities");
while($row = mysqli_fetch_array())
print($row["University"]."\n");
print("END");
mysqli_close($conn);
?>
And here is my android activity:
package com.adi.test;
import android.os.Bundle;
import android.app.Activity;
import android.widget.Spinner;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import java.util.ArrayList;
import java.util.Scanner;
import java.net.URL;
import java.net.HttpURLConnection;
public class TestActivity extends Activity {
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
try {
URL url = new URL("http://developernetwork.net78.net/readUnivs.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "Mozilla/5.0");
Scanner sc = new Scanner(conn.getInputStream());
ArrayList<String> list = new ArrayList<String>();
while(sc.hasNextLine()) {
String line = sc.nextLine();
if(!line.equals("END"))
list.add(line);
}
sc.close();
} catch(IOException exception) {
}
Spinner spinner = new Spinner(this);
spinner.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
layout.addView(spinner);
setContentView(layout);
}
}
The app compiles and installs fine on my LG L90. But it crashes as soon as it opens up. Why is this happening? If I add a simple loop that increments a number from 0 to 10 in place of my loop which reads the response of the server, the app runs fine. I think there is some issue with the loop. Can someone please point out what the issue could be?