Android将MySQL中数据用ListView显示
时间: 2024-05-13 18:19:10 浏览: 13
要在Android中将MySQL中的数据用ListView显示,您需要执行以下步骤:
1.创建一个布局文件,其中包括一个ListView。
2.创建一个Java类来连接到MySQL数据库并检索数据。
3.使用适配器将数据填充到ListView中。
以下是一个简单的示例:
1.在布局文件中添加ListView。
```
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
2.创建一个Java类来连接到MySQL数据库并检索数据。
```
public class MySQLConnector {
private String url = "jdbc:mysql://localhost:3306/mydatabase";
private String user = "myuser";
private String password = "mypassword";
public Connection getConnection() {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public ArrayList<String> getData() {
Connection connection = getConnection();
ArrayList<String> list = new ArrayList<String>();
try {
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM mytable");
while (resultSet.next()) {
String data = resultSet.getString("data");
list.add(data);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
}
```
3.使用适配器将数据填充到ListView中。
```
public class MainActivity extends AppCompatActivity {
private ListView listView;
private MySQLConnector mySQLConnector = new MySQLConnector();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
ArrayList<String> list = mySQLConnector.getData();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(adapter);
}
}
```
这个例子连接到名为“mydatabase”的MySQL数据库,并从名为“mytable”的表中检索数据。然后使用ArrayAdapter将数据填充到ListView中。您需要确保在AndroidManifest.xml文件中添加Internet权限,以便应用程序可以连接到MySQL数据库。