【问题标题】:Display data from mysql server with php into the listview in fragment使用 php 将来自 mysql 服务器的数据显示到片段中的列表视图中
【发布时间】:2018-04-11 08:31:03
【问题描述】:

我想用 php 在 mysql 数据库中的 listview 数据中显示,listview 在片段中。我该怎么做。

这里是代码,其中显示列表视图中的数据而不是来自数据库的数据,我希望使用 php 在 mysql 数据库中检索数据,

        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);
 ?>

【问题讨论】:

    标签: java php android listview android-fragments


    【解决方案1】:

    在我看来,从服务器获取数据的最佳方式是使用 Retrofit 库:http://square.github.io/retrofit/;

    以下是一些以 JSON 格式从服务器检索数据并将其显示在 ListView 中的指南:

    【讨论】:

    • 感谢您的帮助,但我的主要活动有问题,我想在片段中显示列表视图!!!你能帮帮我吗?
    • 是的,我相信我们可以一起找到您问题的答案。可能最好的组件是 ListFragment 在片段中显示列表项:tutorialspoint.com/android/android_list_fragment.htm.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    • 2016-06-09
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多