listview绑定mysql_Android ListView 数据绑定

package com.example.gzznproject;

import java.util.ArrayList;

import java.util.HashMap;

import org.ksoap2.SoapEnvelope;

import org.ksoap2.serialization.SoapObject;

import org.ksoap2.serialization.SoapSerializationEnvelope;

import org.ksoap2.transport.AndroidHttpTransport;

import android.app.Activity;

import android.content.Context;

import android.content.Intent;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.net.ConnectivityManager;

import android.os.Bundle;

import android.view.ContextMenu;

import android.view.ContextMenu.ContextMenuInfo;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.view.View.OnCreateContextMenuListener;

import android.widget.AdapterView.AdapterContextMenuInfo;

import android.widget.ListView;

import android.widget.SimpleAdapter;

import android.widget.Toast;public classLogListActivity extends Activity {

SimpleAdapter adapter;

SqliteDBHelper helper;publicListView listview;public HashMaphashmap;public static ArrayList>arrayList;public static intenegerid;public static intflagid;public static intuserid;

@Overrideprotected voidonCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.loglist);

_getdataview();

listview.setOnCreateContextMenuListener(listener);

}//listview数据绑定

public void_getdataview() {

listview=(ListView) findViewById(R.id.listView);

adapter= new SimpleAdapter(LogListActivity.this, getdata(),

R.layout.item,new String[] { "ConstrName", "WorkTime"},new int[] { R.id.txt_ConstrName, R.id.txt_WorkTime });

listview.setAdapter(adapter);

}//长按菜单

OnCreateContextMenuListener listener = newOnCreateContextMenuListener() {

@Overridepublic voidonCreateContextMenu(ContextMenu menu, View v,

ContextMenuInfo menuInfo) {

menu.setHeaderTitle("操作提示");

menu.add(0, 2, 0, "文件上传");

menu.add(0, 0, 0, "编辑");

menu.add(0, 1, 0, "删除");

}

};

@Overridepublicboolean onContextItemSelected(MenuItem item) {

final AdapterContextMenuInfo info=(AdapterContextMenuInfo) item

.getMenuInfo();

hashmap= arrayList.get((int) info.id);

Object obj= hashmap.get("ID");int id =Integer.parseInt(String.valueOf(obj));if (item.getItemId() == 1) {if (id == -1) {

Toast.makeText(getApplicationContext(),"没有选中数据!",

Toast.LENGTH_SHORT).show();

}else{

helper.Delete(id);

_getdataview();

Toast.makeText(getApplicationContext(),"数据删除成功!",

Toast.LENGTH_SHORT).show();

}

}else if (item.getItemId() == 0) {if (id == -1) {

Toast.makeText(getApplicationContext(),"没有选中数据!",

Toast.LENGTH_SHORT).show();

}else{

LogManagerActivity.hashmap=hashmap;

Intent intent= newIntent();

intent.setClass(LogListActivity.this, LogManagerActivity.class);

startActivity(intent);

}

}else if (item.getItemId() == 2) {

String url= "http://117.34.91.186:8347/WebServices/InsertLog.asmx";

String nameSpace= "http://tempuri.org/";

String SOAP_ACTION= "http://tempuri.org/InserttionLog";

String method= "InserttionLog";

SoapObject request= newSoapObject(nameSpace, method);

request.addProperty("Id", userid);

request.addProperty("ConstrName", hashmap.get("ConstrName")

.toString()== null ? "" : hashmap.get("ConstrName")

.toString());

request.addProperty("Enginer",

hashmap.get("Enginer").toString() == null ? "": hashmap

.get("Enginer").toString());

request.addProperty("DepartID",

hashmap.get("ID").toString() == null ? "" : hashmap.get("ID").toString());

request.addProperty("EngineName", hashmap.get("EnginerName")

.toString()== null ? "" : hashmap.get("EnginerName")

.toString());

request.addProperty("EnginerAddress", hashmap.get("EnginerAddress")

.toString()== null ? "" : hashmap.get("EnginerAddress")

.toString());

request.addProperty("WorkContent", hashmap.get("WorkContent")

.toString()== null ? "" : hashmap.get("WorkContent")

.toString());

request.addProperty("WorkRemark", hashmap.get("WorkRemark")

.toString()== null ? "" : hashmap.get("WorkRemark")

.toString());

request.addProperty("TodayPlan", hashmap.get("TodayPlan")

.toString()== null ? "" : hashmap.get("TodayPlan")

.toString());

request.addProperty("TorrowPlan", hashmap.get("TorrowPlan")

.toString()== null ? "" : hashmap.get("TorrowPlan")

.toString());

request.addProperty("Remark",

hashmap.get("Remark").toString() == null ? "": hashmap

.get("Remark").toString());

request.addProperty("WorkTime",

hashmap.get("WorkTime").toString() == null ? "": hashmap

.get("WorkTime").toString());

SoapSerializationEnvelope envelope= newSoapSerializationEnvelope(

SoapEnvelope.VER11);

envelope.bodyOut=request;

envelope.dotNet= true;

AndroidHttpTransport transport= newAndroidHttpTransport(url);try{if(isOpenNetwork()) {

transport.call(SOAP_ACTION, envelope);if (envelope.getResponse() != null) {

Objectobject =envelope.getResponse();

boolean result=Boolean

.parseBoolean(object.toString());if (result == true) {

Toast.makeText(getApplicationContext(),"上传成功!",

Toast.LENGTH_SHORT).show();

}else{

Toast.makeText(getApplicationContext(),"上传失败!",

Toast.LENGTH_SHORT).show();

}

}

}else{

Toast.makeText(getApplicationContext(),"当前网络不可用不能上传文件!",

Toast.LENGTH_SHORT).show();

}

}catch(Exception e) {

e.printStackTrace();

}

}else{return false;

}returnsuper.onContextItemSelected(item);

}//绑定listview的数据源

public ArrayList>getdata() {

helper= new SqliteDBHelper(this);

SQLiteDatabase mdb=helper.getReadableDatabase();

Cursor c= mdb.rawQuery("select * from myLog", null);

arrayList= new ArrayList>();while(c.moveToNext()) {

hashmap= new HashMap();

hashmap.put("ID", c.getString(0));

hashmap.put("ConstrName", c.getString(1));

hashmap.put("Enginer", c.getString(2));

hashmap.put("DepartID", c.getString(3));

hashmap.put("EnginerName", c.getString(4));

hashmap.put("EnginerAddress", c.getString(5));

hashmap.put("WorkContent", c.getString(6));

hashmap.put("WorkRemark", c.getString(7));

hashmap.put("TodayPlan", c.getString(8));

hashmap.put("TorrowPlan", c.getString(9));

hashmap.put("Remark", c.getString(10));

hashmap.put("WorkTime", c.getString(11));

hashmap.put("DeletionStateCode", c.getString(12));

hashmap.put("Enabled", c.getString(13));

hashmap.put("SortCode", c.getString(14));

hashmap.put("Description", c.getString(15));

hashmap.put("CreateOn", c.getString(16));

hashmap.put("CreateUserId", c.getString(17));

hashmap.put("CreateBy", c.getString(18));

hashmap.put("ModifiedOn", c.getString(19));

hashmap.put("ModifiedUserId", c.getString(20));

hashmap.put("ModifiedBy", c.getString(21));

hashmap.put("Crsign", c.getString(22));

hashmap.put("Telphone", c.getString(23));

hashmap.put("Departname", c.getString(24));

hashmap.put("Itemid", c.getString(25));

hashmap.put("Itemname", c.getString(26));

arrayList.add(hashmap);

}returnarrayList;

}

@Overridepublicboolean onCreateOptionsMenu(Menu menu) {//getMenuInflater().inflate(R.menu.main, menu);

menu.add(0, 1, 1, "添加数据");

menu.add(0, 2, 1, "树形结构");return true;

}

@Overridepublicboolean onOptionsItemSelected(MenuItem item) {if (item.getItemId() == 1) {

Intent itent= newIntent();

itent.setClass(LogListActivity.this, LogManagerActivity.class);

startActivity(itent);

}else{

Intent itent= newIntent();

itent.setClass(LogListActivity.this, TreeStructure.class);

startActivity(itent);

}return false;

}//监听网络状态

privateboolean isOpenNetwork() {

ConnectivityManager connManager=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);if (connManager.getActiveNetworkInfo() != null) {returnconnManager.getActiveNetworkInfo().isAvailable();

}return false;

}

}

要在 Android 应用中将 MySQL 数据ListView 显示,可以使用以下步骤: 1. 创建一个包含 ListView 和适配器的布局文件。 2. 在应用中创建一个网络请求,连接到 MySQL 数据库并获取数据。 3. 将获取到的数据存储在一个数据模型中。 4. 创建一个自定义适配器,将数据模型中的数据绑定ListView 中。 5. 在应用中使用创建的适配器来显示数据。 以下是一个基本示例: 1. 创建布局文件: list_item.xml ```xml <TextView android:id="@+id/tv_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="18sp" android:textStyle="bold" /> <TextView android:id="@+id/tv_email" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="14sp" /> ``` activity_main.xml ```xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="@+id/list_view" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout> ``` 2. 创建网络请求: ```java public class NetworkUtils { public static String getData(String url) { String result = ""; try { URL apiUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) apiUrl.openConnection(); conn.setRequestMethod("GET"); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { result += inputLine; } in.close(); } catch (Exception e) { e.printStackTrace(); } return result; } } ``` 3. 创建数据模型: ```java public class User { private String name; private String email; public User(String name, String email) { this.name = name; this.email = email; } public String getName() { return name; } public String getEmail() { return email; } } ``` 4. 创建适配器: ```java public class UserAdapter extends ArrayAdapter<User> { private Context context; private int resource; public UserAdapter(Context context, int resource, List<User> objects) { super(context, resource, objects); this.context = context; this.resource = resource; } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { View view = convertView; if (view == null) { view = LayoutInflater.from(context).inflate(resource, parent, false); } User user = getItem(position); if (user != null) { TextView tvName = view.findViewById(R.id.tv_name); TextView tvEmail = view.findViewById(R.id.tv_email); tvName.setText(user.getName()); tvEmail.setText(user.getEmail()); } return view; } } ``` 5. 在 MainActivity 中使用适配器显示数据: ```java public class MainActivity extends AppCompatActivity { private ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = findViewById(R.id.list_view); String url = "http://example.com/get_users.php"; String result = NetworkUtils.getData(url); List<User> userList = new ArrayList<>(); try { JSONArray jsonArray = new JSONArray(result); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); String name = jsonObject.getString("name"); String email = jsonObject.getString("email"); User user = new User(name, email); userList.add(user); } } catch (JSONException e) { e.printStackTrace(); } UserAdapter userAdapter = new UserAdapter(this, R.layout.list_item, userList); listView.setAdapter(userAdapter); } } ``` 以上就是将 MySQL 数据ListView 显示的基本步骤。注意,这只是一个简单的示例,实际应用中还需要考虑网络安全性、数据缓存、异常处理等方面。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值