Я немного путешествую, и я хотел создать приложение, которое позволило мне сохранить заказы на такси в базу данных. Я добавил несколько полей, чтобы дать мне представление о том, как все это работает. Я довольно новичок в программировании и следил за несколькими учебниками, чтобы создать приложение, которое позволяет мне взять файл csv и загрузить его в базу данных приложений. Это работает хорошо, и у меня нет проблем с отображением данных.Показать одиночную запись из ListView/ListAdapter из базы данных sql
Мне удалось получить его как с помощью Toast, так и с предупреждением, чтобы отобразить окна с данными, но только 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_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="9"
android:background="#FFC7C7C7"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
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_width="match_parent"
android:layout_height="0dp"
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_width="0dp"
android:layout_height="wrap_content"
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_width="15dp"
android:layout_height="wrap_content"
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_width="0dp"
android:layout_height="wrap_content"
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_width="0dp"
android:layout_height="wrap_content"
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_width="0dp"
android:layout_height="wrap_content"
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_width="0dp"
android:layout_height="wrap_content"
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_width="match_parent"
android:layout_height="0dp"
android:layout_below="@+id/lvcontainer"
android:layout_weight="6.59"
android:clickable="false"></ListView>
<TextView
android:id="@+id/txtresulttext"
android:layout_width="match_parent"
android:layout_height="0dp"
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_width="match_parent"
android:layout_height="0dp"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
android:layout_weight="1"
android:weightSum="1">
<Button
android:id="@+id/btnupload"
android:layout_width="0dp"
android:layout_height="match_parent"
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_width="0dp"
android:layout_height="match_parent"
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_width="0dp"
android:layout_height="match_parent"
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_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/lvh"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
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_width="1dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:text="Ref"
android:textColor="#000000"
android:textSize="13sp" />
<TextView
android:id="@+id/txttaxibDate"
android:layout_width="15dp"
android:layout_height="wrap_content"
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_width="1dp"
android:layout_height="wrap_content"
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_width="1dp"
android:layout_height="wrap_content"
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_width="1dp"
android:layout_height="wrap_content"
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_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/status2"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:text="Booking Details"
android:textColor="#890000"
android:textSize="25sp"
android:textStyle="bold"
/>
<TextView
android:id="@+id/txttaxibID2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:layout_marginLeft="20dip"
/>
<TextView
android:id="@+id/txttaxibDate2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:layout_marginLeft="20dip" />
<TextView
android:id="@+id/txttaxibCombine2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
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,[email protected],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,[email protected],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,[email protected],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,[email protected],Ken Midgley,441234567889,41024830,1044889,None,2,Mike Smith. Have to be in office by 8:30!!!
Я попытался и сумел захватить событие и поместите тост с 6 полями .... То, что я пытаюсь сделать сейчас, - это открыть второй вид с намерением, который я создаю, - не уверен, что это то, что я должен делать. хорошо, я уверен, что он не работает;) – Stravides
Ваш код намерения неверен. Попробуйте использовать «Intent intent = new Intent (this, TextDetails.class)». Первый параметр - это текущая активность, вторая - класс активности, которую вы хотите достичь. –
Спасибо за ваш ответ, к сожалению, до этого пересмотра, я сделал, и я получил красное подшучивание на ** это ** Я скопировал это из предыдущего примера, который я использовал для сведений о сотрудниках, однако это был ListView, а не AdapterView. Не знаю, почему не работает/компилируется – Stravides