I am trying to get data from database using mysql-php and insert them into a ListView- android 1-There is one title in database and even if I remove the while loop in php file I got the error below 2-How to handle if I have multiple results?
Here's my code
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_polls);
ListView listView=(ListView) findViewById(R.id.list_polls);
ArrayList<String> titles=new ArrayList<>();
ArrayAdapter<String> a=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, titles );
listView.setAdapter(a);
Handler handler=new Handler(this.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
try {
titles.add(getPolls());
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
and this is my method to connect with mysql
public String getPolls() throws IOException {
URL url = new URL("http://192.168.1.8/getPolls.php");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
InputStream in = con.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(in));
String line = r.readLine();
return line;
}
Here is my php code:
<?php
$con = mysqli_connect("localhost", "root", "");
mysqli_select_db($con, "evote");
$qu="select * from polls";
if ($result=mysqli_query($con,$qu)) {
if (mysqli_num_rows($result)>0) {
while ($row=mysqli_fetch_array($result)) {
echo $row['title'];
}
}
}
?>
And here is the error I am getting:
E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.evote, PID: 21601 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.evote/com.example.evote.userPolls}: android.os.NetworkOnMainThreadException
And it also shows me an error on line of
InputStream in = con.getInputStream();