显示来自 sql 数据库的 ListView / ListAdapter 的单个记录
Posted
技术标签:
【中文标题】显示来自 sql 数据库的 ListView / ListAdapter 的单个记录【英文标题】:Display single record from ListView / ListAdapter from sql database 【发布时间】:2015-11-13 08:54:25 【问题描述】:我做了一些旅行,我想创建一个应用程序,让我可以将出租车预订保存到数据库中。我只添加了几个字段来让我了解这一切是如何工作的。我对编程很陌生,并且遵循了许多教程来创建一个应用程序,该应用程序允许我获取一个 csv 文件并将其上传到应用程序数据库。这很好用,我在显示数据时没有问题。
我设法让它同时使用 Toast 和 alert 来显示包含数据的窗口,但只有 6 个字段...我需要显示所有 16 个字段... 我已经对此有了一些基础,但是当我单击列表项时仍然遇到应用程序终止问题。
我试图通过 TaxiDetails 中的新意图创建一个意图来调用新视图结果表。不高兴...所有帮助表示赞赏。 代码如下 - 感谢所有帮助并提前感谢....
MainActivity.java
package com.stravides.jdw;
import android.app.AlertDialog;
import android.content.Context;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends ListActivity
TextView lbl;
DBController controller = new DBController(this);
Button btnimport;
Button btnphone;
Button btnclear;
ListView lv;
ArrayList<HashMap<String, String>> myList;
public static final int requestcode = 1;
final Context context = this;
protected Cursor kursor;
protected ListAdapter adapter;
protected SQLiteDatabase db;
public AdapterView.OnItemClickListener mMessageClickedHandler = new AdapterView.OnItemClickListener()
public void onItemClick(AdapterView parent, View v, int position, long id)
Intent intent = new Intent("com.stravides.jdw.TaxiDetails.class");
Cursor kursor = (Cursor) adapter.getItem(position);
intent.putExtra("TAXI_ID", kursor.getInt(kursor.getColumnIndex("_id")));
startActivity(intent);
;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lbl = (TextView) findViewById(R.id.txtresulttext);
btnimport = (Button) findViewById(R.id.btnupload);
btnphone = (Button) findViewById(R.id.btnphone);
btnclear = (Button) findViewById(R.id.btnclear);
lv = getListView();
btnimport.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
Intent fileintent = new Intent(Intent.ACTION_GET_CONTENT);
fileintent.setType("gagt/sdf");
try
startActivityForResult(fileintent, requestcode);
catch (ActivityNotFoundException e)
lbl.setText("No activity that can handle file selection. Showing alternatives.");
);
btnclear.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
SQLiteDatabase db = controller.getWritableDatabase();
String tableName = "taxiinfo";
db.execSQL("delete from " + tableName);
myList = controller.getAllProducts();
if (myList.size() == 0)
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter(MainActivity.this, myList,R.layout.v, new String[]
"bID", "bDate", "bTime", "bFrom", "bTo","bFlightNum", "bFlightDest", "bPassenger", "bEmail", "bTelno", "bMobNo", "bCostCentre", "bPersNo", "bCombine", "bNumPass", "bRemarks", new int[]0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
setListAdapter(adapter);
lbl.setText("Data Cleared");
);
btnphone.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
String uri = "tel:" + "0031251491418";
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(uri));
startActivity(intent);
);
myList= controller.getAllProducts();
if (myList.size() != 0)
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter(MainActivity.this, myList,
R.layout.v, new String[]"bID", "bDate", "bTime", "bFrom", "bTo","bFlightNum", "bFlightDest", "bPassenger", "bEmail", "bTelno", "bMobNo", "bCostCentre", "bPersNo", "bCombine", "bNumPass", "bRemarks", new int[]
R.id.txttaxibID, R.id.txttaxibDate, R.id.txttaxibTime,R.id.txttaxibFrom, R.id.txttaxibTo, R.id.txttaxibFlightNum, R.id.txttaxibFlightDest, R.id.txttaxibPassenger, R.id.txttaxibEmail, R.id.txttaxibTelno, R.id.txttaxibMobNo, R.id.txttaxibCostCentre, R.id.txttaxibPersNo, R.id.txttaxibCombine, R.id.txttaxibNumPass, R.id.txttaxibRemarks);
setListAdapter(adapter);
lbl.setText("");
lv.setOnItemClickListener(mMessageClickedHandler);
protected void onActivityResult(int requestCode, int resultCode, Intent data)
if (data == null)
return;
switch (requestCode)
case requestcode:
String filepath = data.getData().getPath();
controller = new DBController(getApplicationContext());
SQLiteDatabase db = controller.getWritableDatabase();
String tableName = "taxiinfo";
db.execSQL("delete from " + tableName);
try
if (resultCode == RESULT_OK)
try
FileReader file = new FileReader(filepath);
BufferedReader buffer = new BufferedReader(file);
ContentValues contentValues = new ContentValues();
String line = "";
db.beginTransaction();
while ((line = buffer.readLine()) != null)
String[] str = line.split(",", 16);
String bID = str[0];
String bDate = str[1];
String bTime = str[2];
String bFrom = str[3];
String bTo = str[4];
String bFlightNum = str[5];
String bFlightDest = str[6];
String bPassenger = str[7];
String bEmail = str[8];
String bTelno = str[9];
String bMobNo = str[10];
String bCostCentre = str[11];
String bPersNo = str[12];
String bCombine = str[13];
String bNumPass = str[14];
String bRemarks = str[15];
contentValues.put("bID", bID);
contentValues.put("bDate", bDate);
contentValues.put("bTime", bTime);
contentValues.put("bFrom", bFrom);
contentValues.put("bTo", bTo);
contentValues.put("bFlightNum", bFlightNum);
contentValues.put("bFlightDest", bFlightDest);
contentValues.put("bPassenger", bPassenger);
contentValues.put("bEmail", bEmail);
contentValues.put("bTelno", bTelno);
contentValues.put("bMobNo", bMobNo);
contentValues.put("bCostCentre", bCostCentre);
contentValues.put("bPersNo", bPersNo);
contentValues.put("bCombine", bCombine);
contentValues.put("bNumPass", bNumPass);
contentValues.put("bRemarks", bRemarks);
db.insert(tableName, null, contentValues);
lbl.setText("Successfully Updated Database.");
db.setTransactionSuccessful();
db.endTransaction();
catch (IOException e)
if (db.inTransaction())
db.endTransaction();
Dialog d = new Dialog(this);
d.setTitle(e.getMessage().toString() + "first");
d.show();
else
if (db.inTransaction())
db.endTransaction();
Dialog d = new Dialog(this);
d.setTitle("Only CSV files allowed");
d.show();
catch (Exception ex)
if (db.inTransaction())
db.endTransaction();
Dialog d = new Dialog(this);
d.setTitle(ex.getMessage().toString() + "second");
d.show();
myList= controller.getAllProducts();
if (myList.size() != 0)
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter(MainActivity.this, myList,
R.layout.v, new String[]"bID", "bDate", "bTime", "bFrom", "bTo","bFlightNum", "bFlightDest", "bPassenger", "bEmail", "bTelno", "bMobNo", "bCostCentre", "bPersNo", "bCombine", "bNumPass", "bRemarks", new int[]
R.id.txttaxibID, R.id.txttaxibDate, R.id.txttaxibTime,R.id.txttaxibFrom, R.id.txttaxibTo, R.id.txttaxibFlightNum, R.id.txttaxibFlightDest, R.id.txttaxibPassenger, R.id.txttaxibEmail, R.id.txttaxibTelno, R.id.txttaxibMobNo, R.id.txttaxibCostCentre, R.id.txttaxibPersNo, R.id.txttaxibCombine, R.id.txttaxibNumPass, R.id.txttaxibRemarks);
DBController.java
package com.stravides.jdw;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashMap;
public class DBController extends SQLiteOpenHelper
private static final String LOGCAT = null;
public DBController(Context applicationcontext)
super(applicationcontext, "jdwtaxi.db", null, 1); // creating DATABASE
Log.d(LOGCAT, "Created");
@Override
public void onCreate(SQLiteDatabase database)
String query;
query = "CREATE TABLE IF NOT EXISTS taxiinfo ( Id INTEGER PRIMARY KEY, bID TEXT,bDate TEXT, bTime TEXT,bFrom TEXT, bTo TEXT, bFlightNum TEXT, bFlightDest TEXT, bPassenger TEXT, bEmail TEXT, bTelno TEXT, bMobNo TEXT, bCostCentre TEXT, bPersNo TEXT, bCombine TEXT, bNumPass TEXT, bRemarks TEXT)";
database.execSQL(query);
@Override
public void onUpgrade(SQLiteDatabase database, int version_old,int current_version)
String query;
query = "DROP TABLE IF EXISTS taxiinfo";
database.execSQL(query);
onCreate(database);
public ArrayList<HashMap<String, String>> getAllProducts()
ArrayList<HashMap<String, String>> taxiList;
taxiList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM taxiinfo";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst())
do
//Id, Company,Name,Price
HashMap<String, String> map = new HashMap<String, String>();
map.put("Id", cursor.getString(0));
map.put("bID", cursor.getString(1));
map.put("bDate", cursor.getString(2));
map.put("bTime", cursor.getString(3));
map.put("bFrom", cursor.getString(4));
map.put("bTo", cursor.getString(5));
map.put("bFlightNum", cursor.getString(6));
map.put("bFlightDest", cursor.getString(7));
map.put("bPassenger", cursor.getString(8));
map.put("bEmail", cursor.getString(9));
map.put("bTelno", cursor.getString(10));
map.put("bMobNo", cursor.getString(11));
map.put("bCostCentre", cursor.getString(12));
map.put("bPersNo", cursor.getString(13));
map.put("bCombine", cursor.getString(14));
map.put("bNumPass", cursor.getString(15));
map.put("bRemarks", cursor.getString(16));
taxiList.add(map);
while (cursor.moveToNext());
return taxiList;
TaxiDetails.java
package com.stravides.jdw;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.TextView;
/**
* Created by Ken on 09/08/2015.
*/
public class TaxiDetails extends Activity
protected TextView bID;
protected TextView bDate;
protected TextView bTime;
protected TextView bFrom;
protected TextView bTo;
protected TextView bFlightNum;
protected TextView bFlightDest;
protected TextView bPassenger;
protected TextView bEmail;
protected TextView bTelno;
protected TextView bMobNo;
protected TextView bCostCentre;
protected TextView bPersNo;
protected TextView bCombine;
protected TextView bNumPass;
protected TextView bRemarks;
protected int taxiPos;
@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.resultstable);
taxiPos = getIntent().getIntExtra("TAXI_ID", 0);
SQLiteDatabase db = (new DBController(this)).getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT bID, bDate, bCombine FROM taxiinfo WHERE bID = ?", new String[]""+taxiPos);
if (cursor.getCount() == 1)
cursor.moveToFirst();
bID = (TextView) findViewById(R.id.txttaxibID2);
bID.setText(cursor.getString(cursor.getColumnIndex("bID")));
bDate = (TextView) findViewById(R.id.txttaxibDate2);
bDate.setText(cursor.getString(cursor.getColumnIndex("bDate")));
bCombine = (TextView) findViewById(R.id.txttaxibCombine2);
bCombine.setText(cursor.getString(cursor.getColumnIndex("bCombine")));
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_
android:layout_
android:orientation="vertical"
android:weightSum="9"
android:background="#FFC7C7C7"
>
<TextView
android:layout_
android:layout_
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Booking Details"
android:id="@+id/textView"
android:layout_gravity="center_horizontal"
android:layout_weight="0.24" />
<!-- divider -->
<LinearLayout
android:id="@+id/lvcontainer"
android:layout_
android:layout_
android:layout_weight="0.5"
android:layout_alignParentTop="true"
android:orientation="horizontal"
android:padding="1dp"
android:background="#FFC7C7C7"
android:weightSum="6">
<TextView
android:id="@+id/txttaxibID"
android:layout_
android:layout_
android:layout_weight=".8"
android:gravity="left"
android:text="Ref"
android:textColor="#000000"
android:textSize="13sp"
android:clickable="false" />
<TextView
android:id="@+id/txttaxibDate"
android:layout_
android:layout_
android:layout_weight="1"
android:gravity="left"
android:padding="3dp"
android:text="Date"
android:textColor="#000000"
android:textSize="13sp" />
<TextView
android:id="@+id/txttaxibTime"
android:layout_
android:layout_
android:layout_weight=".8"
android:gravity="left"
android:text="Time"
android:padding="3dp"
android:textColor="#000000"
android:textSize="13sp" />
<TextView
android:id="@+id/txttaxibFrom"
android:layout_
android:layout_
android:layout_weight="1"
android:gravity="left"
android:text="From"
android:padding="3dp"
android:textColor="#000000"
android:textSize="13sp" />
<TextView
android:id="@+id/txttaxibTo"
android:layout_
android:layout_
android:layout_weight="1"
android:gravity="left"
android:text="To"
android:padding="3dp"
android:textColor="#000000"
android:textSize="13sp" />
<TextView
android:id="@+id/txttaxibCombine"
android:layout_
android:layout_
android:layout_weight="1"
android:gravity="left"
android:text="Combine"
android:padding="1dp"
android:textColor="#000000"
android:textSize="13sp" />
</LinearLayout>
<ListView
android:id="@android:id/list"
android:layout_
android:layout_
android:layout_below="@+id/lvcontainer"
android:layout_weight="6.59"
android:clickable="false"></ListView>
<TextView
android:id="@+id/txtresulttext"
android:layout_
android:layout_
android:layout_marginLeft="5dp"
android:layout_below="@android:id/list"
android:layout_marginTop="2dp"
android:layout_weight="0.5"
android:gravity="left"
android:text=""
android:textColor="#FFF55F54"
android:textSize="10sp"
android:textStyle="italic|bold"></TextView>
<LinearLayout
android:id="@+id/lvbottom"
android:layout_
android:layout_
android:layout_alignParentBottom="true"
android:orientation="horizontal"
android:layout_weight="1"
android:weightSum="1">
<Button
android:id="@+id/btnupload"
android:layout_
android:layout_
android:layout_weight="0.33"
android:gravity="center"
android:text="UPLOAD"
android:textColor="#ffffff"
android:background="#1083f5"
android:textSize="15sp"
android:textStyle="bold" />
<Button
android:id="@+id/btnclear"
android:layout_
android:layout_
android:layout_weight="0.33"
android:gravity="center"
android:text="CLEAR"
android:textColor="#ffffff"
android:background="#1003f5"
android:textSize="15sp"
android:textStyle="bold" />
<Button
android:id="@+id/btnphone"
android:layout_
android:layout_
android:layout_weight="0.34"
android:gravity="center"
android:text="CALL JDW"
android:textColor="#ffffff"
android:background="#ffff0000"
android:textSize="15sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
v.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_
android:layout_
android:orientation="vertical" >
<LinearLayout
android:id="@+id/lvh"
android:layout_
android:layout_
android:orientation="horizontal"
android:scrollbars="horizontal"
android:background="#ffe6e6e6"
android:weightSum="5"
android:minHeight="30dp"
android:measureWithLargestChild="false"
android:longClickable="false">
<TextView
android:id="@+id/txttaxibID"
android:layout_
android:layout_
android:layout_weight="1"
android:gravity="left"
android:text="Ref"
android:textColor="#000000"
android:textSize="13sp" />
<TextView
android:id="@+id/txttaxibDate"
android:layout_
android:layout_
android:layout_weight="1"
android:gravity="left"
android:padding="3dp"
android:text="Date"
android:textColor="#000000"
android:textSize="13sp" />
<TextView
android:id="@+id/txttaxibTime"
android:layout_
android:layout_
android:layout_weight="1"
android:gravity="left"
android:text="Time"
android:padding="3dp"
android:textColor="#000000"
android:textSize="13sp" />
<TextView
android:id="@+id/txttaxibFrom"
android:layout_
android:layout_
android:layout_weight="1"
android:gravity="left"
android:text="From"
android:padding="3dp"
android:textColor="#000000"
android:textSize="13sp" />
<TextView
android:id="@+id/txttaxibTo"
android:layout_
android:layout_
android:layout_weight="1"
android:gravity="left"
android:text="To"
android:padding="3dp"
android:textColor="#000000"
android:textSize="13sp" />
</LinearLayout>
</LinearLayout>
resultstable.xml
<TextLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_
android:layout_
>
<TextView
android:id="@+id/status2"
android:layout_
android:layout_gravity="center"
android:text="Booking Details"
android:textColor="#890000"
android:textSize="25sp"
android:textStyle="bold"
/>
<TextView
android:id="@+id/txttaxibID2"
android:layout_
android:layout_
android:textColor="#000000"
android:layout_marginLeft="20dip"
/>
<TextView
android:id="@+id/txttaxibDate2"
android:layout_
android:layout_
android:textColor="#000000"
android:layout_marginLeft="20dip" />
<TextView
android:id="@+id/txttaxibCombine2"
android:layout_
android:layout_
android:textColor="#000000"
android:layout_marginLeft="20dip" />
</TextLayout>
用于测试的 csv 数据
372187,20/09/2015,20:00,Schiphol Taxi Counter Jan de Wit Group,Hotel Lion D'or Golden Tulip,KL1064,Cardiff,Ken Midgley,me@home.com,Ken Midgley,441234567889,41024830,1044889,None,1,
372188,21/09/2015,08:00,Hotel Lion D'or Golden Tulip,3H.18 Dudokhuis Hoofdingang,None,None,Ken Midgley,me@home.com,Ken Midgley,441234567889,41024830,1044889,None,1,Have to be in office by 8:30!!!
372189,21/09/2015,17:30,3H.18 Dudokhuis Hoofdingang,Hotel Lion D'or Golden Tulip,None,None,Ken Midgley,me@home.com,Ken Midgley,441234567889,41024830,1044889,None,1,
372190,22/09/2015,08:00,Hotel Lion D'or Golden Tulip,3H.18 Dudokhuis Hoofdingang,None,None,Ken Midgley,me@home.com,Ken Midgley,441234567889,41024830,1044889,None,2,Mike Smith. Have to be in office by 8:30!!!
【问题讨论】:
【参考方案1】:您需要在您的ListView
上设置一个OnItemClickListener
。这是一个简单的教程,它是如何工作的 - http://www.mkyong.com/android/android-listview-example/
在你学会拦截和处理事件之后,你可以开始考虑导航到一个细节活动,或者打开一个细节对话框。
我建议您阅读 http://developer.android.com 中的所有基本教程 - 您需要的都在那里。
【讨论】:
我已经尝试并设法捕获该事件并用 6 个字段放置祝酒词......我现在要做的是通过我创建的意图打开第二个视图 - 不确定是否这是我应该做的。好吧,我很确定它不起作用;) 您的意图代码错误。尝试使用Intent intent = new Intent(this, TextDetails.class)
。第一个参数是你当前的活动,第二个是你想要达到的活动的类别。
感谢您的回答,不幸的是,在此修订之前,我做到了,我在 this 上得到了一个红色的underwiggle 我从以前用于员工详细信息的示例中复制了这个,但是这是ListView 不是 AdapterView。不知道为什么不工作/编译
这是因为您是从 OnClickListener 内部进行的。这里this
指的是监听器,这里监听器不能作为参数传递。您需要使用MainActivity.this
获取封闭的活动实例
好的,现在至少“编译”了——但是当我按下记录打开新活动时仍然有问题——它只是崩溃了,我得到“不幸的是,JDW 出租车已经停止”错误。一定是有其他问题。将 OnItemClickListener 的行一一注释掉,它失败的行是“'Cursor kursor = (Cursor) adapter.getItem(position);'”它无法设置适配器 - 一定是使用了错误的 ??? 【参考方案2】:
我会这样做:
public void onClickList(final ListView list)
list.setOnItemClickListener(new OnItemClickListener()
public void onItemClick(final AdapterView<?> parent,
final View view, final int position, long id)
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setCancelable(false);
alert.setMessage("youre message");
final AlertDialog.Builder ok = alert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
public void onClick(DialogInterface dialog, int which)
//add your code here
dialog.dismiss();
);
alert.show();
);
其中列表是您创建的 ListView 对象。您可以将您的 ListView 发送到此方法onClickListener()
以管理弹出窗口。顺便说一句,您可以创建自己的 xml 布局来呈现自定义视图。
【讨论】:
【参考方案3】:感谢您在上述问题上的帮助 - 我现在设法解决了这个问题。
问题是想太多关于传递点击的位置......
MainActivity.java 需要以下...
public AdapterView.OnItemClickListener mMessageClickedHandler = new AdapterView.OnItemClickListener()
public void onItemClick(AdapterView parent, View v, int position, long id)
Intent intent = new Intent(MainActivity.this,TaxiDetails.class);
intent.putExtra("TAXI_ID", position);
startActivity(intent);
;
TaxiDetails.java 然后可以获取 Intent 中的额外信息
taxiPos = getIntent().getIntExtra("TAXI_ID", 0);
taxiPos=taxiPos+1;
SQLiteDatabase db = (new DBController(this)).getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM taxiinfo WHERE Id = ?", new String[]""+taxiPos);
if (cursor.getCount() == 1)
【讨论】:
如您所见,这可行,但我必须增加位置:(以上是关于显示来自 sql 数据库的 ListView / ListAdapter 的单个记录的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 JDBC 在 ListView 或 TableView 中显示来自 SQL Server 的数据
ListView 显示来自 Firebase 问题的所有数据
UpdatePanel 和 ListView 控件不显示来自 BLOB 的数据
如何强制 ListView 在同一行中显示来自 ObservableCollection 不同元素的两个不同数据