我是新的android developer.how来创建列表视图。在列表视图中包含两个文本视图,一个复选框和从sqlite数据库中检索数据以显示文本视图值。当我按下按钮发送短信以包含选择列表视图。和一个t视图复选框选择所有选项。请帮助我吗?
package com.example.dao;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.dto.DriverSelectedRouteArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class StudentListDatabaseHelper extends SQLiteOpenHelper
{
SQLiteDatabase db;
// ParseDriverSelectedRouteId parseDriverSelectedRouteId = new ParseDriverSelectedRouteId();
//database version
private final static int DATABASE_VERSION = 3;
//table name
private final static String TABLE_NAME = "studentlist";
//table column
private final String KEY_ID = "_id";
private final String ROUTE_ID = "route_id";
private final String KEY_FIRST_NAME = "first_name";
private final String KEY_MIDDLE_NAME = "middle_name";
private final String KEY_LAST_NAME = "last_name";
private final String KEY_PH_NO = "phone_number";
DriverSelectedRouteArrayList driverSelectedRouteArrayList = new DriverSelectedRouteArrayList();
// list object create for student list
List<DriverSelectedRouteArrayList> studentList = new ArrayList<DriverSelectedRouteArrayList>();
//constructor
public StudentListDatabaseHelper(Context context)
{
super(context, "sbtsystem.db", null, DATABASE_VERSION);
//SQLiteDatabase simpleDb = this.
db = context.openOrCreateDatabase("sbtsystem.db", Context.MODE_PRIVATE,null);
// Log.d("constructor for database handler====>", "database handler");
}
@Override
public void onCreate(SQLiteDatabase db)
{
//Log.d("on create method==========================>>>>>", "sql helper class");
String CREATE_STUDENT_LIST_TABLE = "CREATE TABLE IF NOT EXISTS "+ TABLE_NAME +"("+
KEY_ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"+
ROUTE_ID+" INTEGER,"+
KEY_FIRST_NAME+" TEXT,"+
KEY_MIDDLE_NAME+" TEXT,"+
KEY_LAST_NAME+ " TEXT,"+ KEY_PH_NO +" TEXT"+")";
db.execSQL(CREATE_STUDENT_LIST_TABLE);
//Log.d("on create database helper calss", "database helper class on create");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
Log.d("on upgrade method in sqlite database helper class=====>", "before on crete method call in onUpgrade method");
this.onCreate(db);
}
public void insertRecord(DriverSelectedRouteArrayList driverSelectedRouteArrayList) throws JSONException
{
this.onUpgrade(db, 0, 2);
db = this.getWritableDatabase();
//get list size from driverSelectedRouteArraylist
int listSize = driverSelectedRouteArrayList.getStudentArrayList().size();
// Log.d("list size in database helper class", listSize+"");
String respose = driverSelectedRouteArrayList.getStudentArrayList().toString();
JSONArray jsonArray = new JSONArray(respose);
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
ContentValues values = new ContentValues();
String routeId = jsonObject.get("route_id").toString();
values.put(ROUTE_ID, routeId);
String firstName = jsonObject.get("first_name").toString();
values.put(KEY_FIRST_NAME, firstName);
String middle_name = jsonObject.get("middle_name").toString();
values.put(KEY_MIDDLE_NAME, middle_name);
String last_name = jsonObject.get("last_name").toString();
values.put(KEY_LAST_NAME,last_name);
String phone_number = jsonObject.get("phone_number").toString();
values.put(KEY_PH_NO, phone_number);
try{
//onUpgrade(db, 1, 2);
// Log.d("end insertRecord loop route id", values.getAsString("route_id")+"end insert record loop route id");
db.insert(TABLE_NAME, null, values);
selectRecord();
// Log.d("insert record:: :: :: :: ::", driverSelectedRouteArrayList.getFirst_name());
//db.close();
//Log.d("insert query", query+"");
}catch(Exception e)
{
e.printStackTrace();
}
Log.d("inser======0----->", TABLE_NAME+"");
// db.close();
}
}
public <T> List<DriverSelectedRouteArrayList> selectRecord() throws JSONException
{
ArrayList<T> studentArrayList = new ArrayList<T>();
String selectQuery = "SELECT * FROM "+TABLE_NAME;
// Log.d("select query=-=-=-=-=-=-=-=-=> ", selectQuery);
//db = this.getReadableDatabase();
db = this.getWritableDatabase();
Cursor curser = db.rawQuery(selectQuery, null);
//Log.d("select all student list=====>", );
if(curser.moveToFirst())
{
do{
//json object create for stored data
JSONObject jsonObjectForStudenntList = new JSONObject();
/* int _id = (curser.getInt(curser.getColumnIndex(KEY_ID)));
jsonObjectForStudenntList.put("_id", _id);*/
int _id = driverSelectedRouteArrayList.set_id(curser.getInt(curser.getColumnIndex(KEY_ID)));
jsonObjectForStudenntList.put("_id", _id);
Log.d("sqlite database values_id",""+_id);
//Log.d("values from database handler class _id:::::::::-->", (curser.getInt(curser.getColumnIndex(KEY_ID)))+"=====values");
String firstName = driverSelectedRouteArrayList.setFirst_name(curser.getString(curser.getColumnIndex(KEY_FIRST_NAME)));
jsonObjectForStudenntList.put("firstName", firstName);
Log.d("first Name=======>>>>>", firstName+"first Name");
String middleName = driverSelectedRouteArrayList.setMiddle_name(curser.getString(curser.getColumnIndex(KEY_MIDDLE_NAME)));
jsonObjectForStudenntList.put("middleName", middleName);
String lastName = driverSelectedRouteArrayList.setLast_name(curser.getString(curser.getColumnIndex(KEY_LAST_NAME)));
jsonObjectForStudenntList.put("lastName", lastName);
String phoneNumber = driverSelectedRouteArrayList.setPhone_number(curser.getString(curser.getColumnIndex(KEY_PH_NO)));
jsonObjectForStudenntList.put("phoneNumber", phoneNumber);
studentList.add(driverSelectedRouteArrayList);
studentArrayList.add((T) jsonObjectForStudenntList.toString());
}while(curser.moveToNext());
driverSelectedRouteArrayList.setDriverSelectedRouteArrayList((List<DriverSelectedRouteArrayList>) studentArrayList);
//driverSelectedRouteArrayList.setStudentListInSqliteDatabse((ArrayList<String>) studentList);
//Log.d("all select values from sqlite database******",""+studentArrayList);
}
Log.d("driver list==>","nnnnnnnnnnnnn\n"+""+driverSelectedRouteArrayList.getDriverSelectedRouteArrayList());
return studentList;
}
}
package com.example.dto;
import java.util.ArrayList;
import java.util.List;
public class DriverSelectedRouteArrayList
{
// ArrayList arrayList = new ArrayList();
ArrayList<String> studentArrayList = new ArrayList<String>();
// create list view object
public List<DriverSelectedRouteArrayList> driverSelectedRouteArrayList;
public int _id;
public String first_name;
public String middle_name;
public String last_name;
public String route_id;
public String phone_number;
boolean Box;
public DriverSelectedRouteArrayList()
{
first_name = null;
middle_name = null;
last_name = null;
route_id = null;
phone_number = null;
}
public int get_id()
{
return _id;
}
public int set_id(int _id)
{
return this._id = _id;
}
public ArrayList<String> getStudentArrayList()
{
return studentArrayList;
}
public void setStudentArrayList(ArrayList<String> studentArrayList)
{
this.studentArrayList = studentArrayList;
}
public String getFirst_name() {
return first_name;
}
public String setFirst_name(String first_name) {
return this.first_name = first_name;
}
public String getMiddle_name()
{
return middle_name;
}
public String setMiddle_name(String middle_name)
{
return this.middle_name = middle_name;
}
public String getLast_name()
{
return last_name;
}
public String setLast_name(String last_name)
{
return this.last_name = last_name;
}
public String getRoute_id()
{
return route_id;
}
public String setRoute_id(String routeId)
{
return this.route_id = routeId;
}
public String getPhone_number()
{
return phone_number;
}
public String setPhone_number(String phone_number)
{
return this.phone_number = phone_number;
}
public List<DriverSelectedRouteArrayList> getDriverSelectedRouteArrayList()
{
return driverSelectedRouteArrayList;
}
public void setDriverSelectedRouteArrayList(
List<DriverSelectedRouteArrayList> driverSelectedRouteArrayList)
{
this.driverSelectedRouteArrayList = driverSelectedRouteArrayList;
}
}
package com.example.main;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import com.example.dao.StudentListDatabaseHelper;
import com.example.dto.DriverSelectedRouteArrayList;
import com.example.extra.CustomAdapter;
import com.example.extra.StudentListView;
import com.example.input.DriverSelectedRouteinput;
import com.example.url.UrlAccess;
import com.example.webservcie.ParseDriverSelectedRouteId;
import com.google.ads.mediation.customevent.CustomEventAdapter;
import android.R.string;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class StudentCheckBoxAndListShow extends Activity implements OnItemClickListener
{
//private String SERVICE_URL = "http://10.0.2.2:8080/SBTsystem/service/viewAllStudentlist";
UrlAccess urlAccess = new UrlAccess();
String urlAccessStringVariable = urlAccess.SERVICE_URL;
String SERVICE_URL = urlAccessStringVariable+"/viewAllStudentlist";
ProgressDialog progressDialog;
HttpPost httpPost;
HttpResponse httpResponse;
HttpClient httpclient ;
StatusLine statusLine;
TextView srNumberTextView;
//regarding list view object
ListView listView;
// List<DriverSelectedRouteArrayList> studentList;
// ListView listView;
DriverSelectedRouteArrayList driverSelectedRouteArrayList = new DriverSelectedRouteArrayList();
ParseDriverSelectedRouteId parseDriverSelectedRouteId = new ParseDriverSelectedRouteId();
StudentListView studentlistView = new StudentListView();
//customer adapter class
// CustomAdapter customAdapter;
StudentListDatabaseHelper studentListDatabaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.student_list_view_show);
studentListDatabaseHelper = new StudentListDatabaseHelper(this);
srNumberTextView = (TextView) findViewById(R.id.srNumberTextView);
listView = (ListView) findViewById(R.id.studentlistView);
httpclient = new DefaultHttpClient();
Log.d("student check box class", "oncreate method");
Log.d("list view ----StudentCheckBoxAndListShow--->","on create method");
// call async task class
new StudentListShowAsyncTask().execute();
}
private void populateListView(StudentListDatabaseHelper studentListDatabaseHelper,ListView listView,TextView srNumberTextView) throws JSONException
{
//studentList = studentListDatabaseHelper.selectRecord();
/*// call values from DriverSelectedRouteArrayList class
List<DriverSelectedRouteArrayList> data = studentListDatabaseHelper.selectRecord();
List<DriverSelectedRouteArrayList> allStudentList = driverSelectedRouteArrayList.getDriverSelectedRouteArrayList();
Log.d("all student list", ""+allStudentList);
if(data.size() == 0)
{
String meassage = "student list empty";
Toast.makeText(StudentCheckBoxAndListShow.this, "student list empty...", Toast.LENGTH_LONG).show();
}
else
{
// Log.d("list view data...", ""+allStudentList);
driverSelectedRouteArrayList = data.get(0);
int srNumber = driverSelectedRouteArrayList.get_id();
Log.d("serial number value", srNumber+"");
ArrayAdapter arrayAdapter = new ArrayAdapter(StudentCheckBoxAndListShow.this,android.R.layout.simple_list_item_1,srNumber);
listView.setAdapter(arrayAdapter);
srNumberTextView.setText(srNumber);
}*/
}
private class StudentListShowAsyncTask extends AsyncTask<String, String, String>
{
//this.getIntent().getExtras();
@Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = ProgressDialog.show(StudentCheckBoxAndListShow.this,""
,"Loading. Please wait...", true);
progressDialog.show();
Log.d("on pre execute method=====>", "on preexcute");
}
@Override
protected String doInBackground(String... params)
{
Bundle extras = getIntent().getExtras();
String routeIdFromDriverSelected = extras.getString("routeId");
try {
httpPost = new HttpPost(SERVICE_URL);
DriverSelectedRouteinput driverSelectedRouteinput = new DriverSelectedRouteinput();
String jsonRequest = driverSelectedRouteinput.createjsonRequestForDriverSelectedRoute(routeIdFromDriverSelected);
StringEntity stringEntety;
stringEntety = new StringEntity(jsonRequest);
stringEntety.setContentEncoding("UTF-8");
stringEntety.setContentType("application/json");
httpPost.setEntity(stringEntety);
httpResponse = httpclient.execute(httpPost);
statusLine = httpResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
if(statusCode == 200)
{
Log.d("status code", statusCode+"");
driverSelectedRouteArrayList = parseDriverSelectedRouteId.parseResponseForRouteIdResult(httpResponse);
/*int arrayListSize = parseDriverSelectedRouteId.studentList.size();
for(int i =0; i<arrayListSize; i++)
{
Log.d("response first name=-=-==-===-=-=-=-=>"+i, driverSelectedRouteArrayList.getFirst_name()+"");
}*/
//String routeId = driverSelectedRouteArrayList.getRoute_id();
//Log.d("route id------>", routeId);
StudentListDatabaseHelper studentListDatabaseHelper1 = new StudentListDatabaseHelper(getBaseContext());
//studentListDatabaseHelper.getWritableDatabase();
studentListDatabaseHelper1.insertRecord( driverSelectedRouteArrayList);
//int _id = driverSelectedRouteArrayList.get_id();
/*String _idString = ""+_id;
Log.d("id get from the sqlite database-==-=-=-=>",_idString);*/
Log.d("database created", "sqlite database created");
}
//Log.d("status code", statusCode+"");
} catch (Exception e)
{
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result)
{
progressDialog.dismiss();
super.onPostExecute(result);
try {
populateListView(studentListDatabaseHelper,listView,srNumberTextView);
} catch (JSONException e)
{
e.printStackTrace();
}
}
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:0)
使用以下代码,
public class Classes extends Activity{
ImageView imageViewNewClass, imageViewDelete;
static ListView mListView;
String[] stg1;
static List<String[]> names2 = null;
private static List<String> myList = new ArrayList<String>();
DataManipulatorClass dataManipulator;
ArrayAdapter<CharSequence> adapterSpinner;
ArrayAdapter<String> adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.classes);
imageViewNewClass = (ImageView) findViewById(R.id.newclass);
mListView = (ListView) findViewById(R.id.displaydata);
imageViewNewClass.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Classes.this, Class_Create.class);
startActivity(intent);
}
});
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View item,
int position, long id) {
SparseBooleanArray sp = mListView.getCheckedItemPositions();
StringBuffer str = new StringBuffer();
for (int i = 0; i < sp.size(); i++) {
if (sp.valueAt(i) == true) {
String s = ((TextView) mListView.getChildAt(i))
.getText().toString();
str = str.append(" " + s);
}
}
Toast.makeText(Classes.this,
"Selected items are " + str.toString(),
Toast.LENGTH_LONG).show();
}
});
dataManipulator = new DataManipulatorClass(this);
}
@Override
protected void onResume() {
super.onResume();
names2 = dataManipulator.selectAll();
stg1 = new String[names2.size()];
int x = 0;
String stg;
for (String[] name : names2) {
stg = "Class Name : " + name[1];
stg1[x] = stg;
x++;
}
adapter = new ArrayAdapter<String>(this, R.layout.custom_list_item,
stg1);
mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mListView.setBackgroundResource(R.drawable.assignmentheader);
mListView.setCacheColorHint(Color.TRANSPARENT);
mListView.setDivider(new ColorDrawable(0x99000000));
mListView.setDividerHeight(1);
mListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (dataManipulator != null)
dataManipulator.close();
}
}
<强> DataManipulatorClass 强>
public class DataManipulatorClass {
public static final String KEY_ROWID = "id";
private static final String DATABASE_NAME = "mydatabaseclass.db";
private static final int DATABASE_VERSION = 1;
static final String TABLE_NAME = "newtableclass";
private static Context context;
static SQLiteDatabase db;
OpenHelper openHelper = null;
private SQLiteStatement insertStmt;
private static final String INSERT = "insert into " + TABLE_NAME
+ "(classname) values (?)";
public DataManipulatorClass(Context context) {
DataManipulatorClass.context = context;
OpenHelper openHelper = new OpenHelper(DataManipulatorClass.context);
DataManipulatorClass.db = openHelper.getWritableDatabase();
this.insertStmt = DataManipulatorClass.db.compileStatement(INSERT);
}
public long insert(String classname) {
this.insertStmt.bindString(1, classname);
return this.insertStmt.executeInsert();
}
public void close() {
if (openHelper != null) {
openHelper.close();
}
}
public void deleteAll() {
db.delete(TABLE_NAME, null, null);
}
public List<String[]> selectAll() {
List<String[]> list = new ArrayList<String[]>();
Cursor cursor = db.query(TABLE_NAME,
new String[] { "id", "classname" }, null, null, null, null,
"classname asc");
int x = 0;
if (cursor.moveToFirst()) {
do {
String[] b1 = new String[] { cursor.getString(0),
cursor.getString(1) };
list.add(b1);
x = x + 1;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
cursor.close();
return list;
}
public boolean delete(long rowId) {
/** this method deletes by id, the first column in your database */
return db.delete(TABLE_NAME, KEY_ROWID + "=" + rowId, null) > 0;
}
public int update(String updateClass) {
ContentValues values = new ContentValues();
values.put("classname", Code.className);
return db.update(TABLE_NAME, values, KEY_ROWID + "=" + updateClass,
null);
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME
+ " (id INTEGER PRIMARY KEY, classname TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
并在提交按钮点击事件中调用以下代码。
this.dataManipulatorClass = new DataManipulatorClass(this);
this.dataManipulatorClass.insert(Code.className);
this.dataManipulatorClass.close();