我想在列表视图中显示数据从mysql数据库与php,列表视图是在片段。我怎么做呢?
下面是代码,其中显示了列表视图中的数据,但不是从数据库,我想在mysql数据库中用php检索数据,
public class ServiceFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
// return inflater.inflate(R.layout.fragment_servicepay, container, false);
View view = inflater.inflate(R.layout.fragment_servicepay, container, false);
String[] ServiceItems = {"Android", "Iphone", "Java"};
final ListView listView = view.findViewById(R.id.ServiceList);
ArrayAdapter<String> listViewAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_expandable_list_item_2, ServiceItems );
listView.setAdapter(listViewAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent in = new Intent(view.getContext(), ServiceUniqueActivity.class);
startActivity(in);
}
});
return view;
}
这是我的php文件的代码
<?php
$host = "localhost"; // host of MySQL server
$user = "root"; // MySQL user
$pwd = ""; // MySQL user's password
$db = "servicedb"; // database name
$con = mysqli_connect($host, $user, $pwd, $db) or die('Unable to connect');
if(mysqli_connect_error($con)) {
echo("Failed to connect to Database: ".mysqli_connect_error());
}
$sql = "SELECT * FROM Services";
$result= mysqli_query($con, $sql);
if($result)
{
while($row=mysqli_fetch_array($result))
{
$data[]=$row;
}
print(json_encode($data));
}
mysqli_close($con);
?>
2条答案
按热度按时间y1aodyip1#
在我看来,从服务器获取数据的最佳方法是使用Retrofit库:http://square.github.io/retrofit/的值;
下面是一些从服务器检索JSON格式的数据并将其显示在ListView中的指南:
pes8fvy92#