我尝试为发送作业配置文件创建并保存脱机SQLite数据库。但是没有创建数据库。 请告诉我如何创建sqlite数据库并在文件资源管理器中表示。
Fragment.java
import org.apache.http.HttpResponse;
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.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.sunmobileappnow.mobileappnow.*;
public class FragmentSendJob extends Fragment implements OnClickListener {
// this Fragment will be called from MainActivity
private Button submit,cancel;
private EditText ename,mobno,picktime,unit,street,suburb,destination,fare,city;
private Spinner state,group;
private ViewGroup vgroup ;
private String sename,smobno,spicktime,sunit,sstreet,ssuburb,sstate, ssendjob,scity,sdestination,sfare,sgroup,login_token;
private static FragmentDialog dialog;
private SendJobDataBase db;
static final int DIALOG_ID = 0;
private Typeface ftype;
private SharedPreferences pref1;
String latitude,longitude;
public FragmentSendJob(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.sendjob_fragment, container, false);
pref1=this.getActivity().getSharedPreferences("LocDetails", getActivity().MODE_WORLD_READABLE);
latitude = pref1.getString("latitude","latitude");
longitude = pref1.getString("longitude","longitude");
ename = (EditText) rootView.findViewById(R.id.ename);
mobno = (EditText) rootView.findViewById(R.id.mobno);
picktime = (EditText) rootView.findViewById(R.id.picktime);
unit = (EditText) rootView.findViewById(R.id.unit);
street = (EditText) rootView.findViewById(R.id.street);
suburb = (EditText) rootView.findViewById(R.id.suburb);
destination = (EditText) rootView.findViewById(R.id.destination);
state = (Spinner) rootView.findViewById(R.id.state);
fare=(EditText) rootView.findViewById(R.id.fare);
group = (Spinner) rootView.findViewById(R.id.group);
city = (EditText) rootView.findViewById(R.id.city);
vgroup = (ViewGroup) rootView.findViewById(R.id.rel);
submit = (Button) rootView.findViewById(R.id.submit);
submit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
new SendJob().execute();
Intent intent =new Intent(getActivity(),GetCurrentLocation.class);
startActivity(intent);
System.out.println(">>>>>>>>>>>>>>>>>"+latitude+"***********");
System.out.println(">>>>>>>>>>>>"+longitude+"***********");
}
});
cancel = (Button) rootView.findViewById(R.id.cancel);
cancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
for (int i = 0, count = vgroup.getChildCount(); i < count; ++i) {
View view = vgroup.getChildAt(i);
if (view instanceof EditText) {
((EditText)view).setText("");
}
}
}
});
String[] mystate= new String[]{"Select state","New South Wales","Victoria","Queensland","Northern Territory","Western Australia","South Australia"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), R.layout.listrow, mystate);
state.setAdapter(adapter);
state.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,int pos, long arg3) {
// TODO Auto-generated method stub
scity = state.getSelectedItem().toString();
String s1=arg0.getItemAtPosition(pos).toString();
if(s1.equals("New South Wales"))
city.setText("Sydney");
else if(s1.equals("Victoria"))
city.setText("Melbourne");
else if(s1.equals("Queensland"))
city.setText("Brisbane");
else if(s1.equals("Northern Territory"))
city.setText("Darwin");
else if(s1.equals("Western Australia"))
city.setText("Perth");
else if(s1.equals("South Australia"))
city.setText("Adelaide");
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
String[] mygroups= new String[]{"Select Groups","My Group","My Secondary group","Everyone"};
ArrayAdapter<String> adapters = new ArrayAdapter<String>(this.getActivity(),
R.layout.listrow, mygroups);
group.setAdapter(adapters);
group.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
// TODO Auto-generated method stub
ssendjob = group.getItemAtPosition(pos).toString();
//gender.setText(setgender);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
return rootView;
}
private class SendJob extends AsyncTask<String, String, String[]> {
ProgressDialog pDialog = new ProgressDialog(getActivity());
@Override
protected String[] doInBackground(final String... params)
{
ConnectivityManager conMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected())
{
HttpClient httpclient = new DefaultHttpClient();
try
{
JSONObject job= new JSONObject();
sename = ename.getText().toString();
smobno = mobno.getText().toString();
spicktime = picktime.getText().toString();
sunit = unit.getText().toString();
sstreet = street.getText().toString();
ssuburb = suburb.getText().toString();
sstate = state.getSelectedItem().toString();
scity = city.getText().toString();
sdestination = destination.getText().toString();
sgroup = group.getSelectedItem().toString();
sfare = fare.getText().toString();
sename.replace("" ,"%20");
smobno.replace("" ,"%20");
spicktime.replace("" ,"%20");
sunit.replace("" ,"%20");
sstreet.replace("" ,"%20");
sstate.replace("" ,"%20");
ssuburb.replace("" ,"%20");
scity.replace("" ,"%20");
sdestination.replace("" ,"%20");
sgroup.replace("" ,"%20");
sfare.replace("" ,"%20");
job.put("name",sename);
job.put("mobile_no",smobno);
job.put("pickup_time",spicktime);
job.put("unit_no",sunit);
job.put("street_name",sstreet);
job.put("state",sstate);
job.put("suburb",ssuburb);
job.put("city",scity);
job.put("destination",sdestination);
job.put("group",sgroup);
job.put("fare",sfare);
job.put("latitude",latitude);
job.put("longitude",longitude);
job.put("status_key","2");
job.put("method","send_job");
job.put("login_token",login_token);
StringEntity se = new StringEntity(job.toString());
HttpPost httppost = new HttpPost("http://suntechwebsolutions.com/clients/mobileapp_now/webservice.php");
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String data = EntityUtils.toString(response.getEntity());
Log.i("response", data);
System.out.println("response "+data);
String call;
call = data;
System.out.println(" print me.............."+call);
System.out.println(sename+".....please print my name......."+login_token);
System.out.println(smobno+"......please print my name......."+smobno);
System.out.println(sstate +"......please print my name......."+sstate);
System.out.println(sstreet+"........please print my name......."+street);
System.out.println(login_token+".....please print my name......."+login_token);
System.out.println(ssuburb+"......please print my name......."+suburb);
System.out.println(sgroup +"......please print my name......."+group);
System.out.println(sdestination+"........please print my name......."+destination);
System.out.println(scity+"......please print my name......."+city);
System.out.println(sfare +"......please print my name......."+fare);
System.out.println(spicktime+"........please print my name......."+spicktime);
JSONObject jo = new JSONObject(data);
Log.d("response", jo.toString(4));
JSONArray jArray = jo.getJSONArray("driver_details");
Log.d("Array", jArray.toString(4));
for (int i=0; i < jArray.length(); i++)
{
try {
JSONObject jsob = jArray.getJSONObject(i);
sename= jsob.getString("sename");
smobno = jsob.getString("mobile_no");
spicktime = jsob.getString("pickup_time");
sstreet = jsob.getString("street_name");
ssuburb = jsob.getString("Suburb");
sstate = jsob.getString("State");
sgroup = jsob.getString("group");
sdestination = jsob.getString("destination");
scity = jsob.getString("city");
sfare = jsob.getString("fare");
login_token=jsob.getString("login_token");
db = new SendJobDataBase(getApplicationContext());
db.insert(sename,smobno, spicktime, sunit, sstreet,sstate, ssuburb,scity, sdestination, sgroup, sfare);
Object pref = getSharedPreferences("Driver");
SharedPreferences.Editor edit= ((SharedPreferences) pref).edit();
edit.putString("sename", sename);
edit.putString("smobno", smobno);
edit.putString("spicktime", spicktime);
edit.putString("sunit", sunit);
edit.putString("sstreet", sstreet);
edit.putString("sstate", sstate);
edit.putString("ssuburb", ssuburb);
edit.putString("scity", scity);
edit.putString("sdestination", sdestination);
edit.putString("sgroup", sgroup);
edit.putString("sfare", sfare);
edit.putString("latitude",latitude);
edit.putString("longitude",longitude);
edit.putString("status_key","2");
edit.putString("method","send_job");
edit.putString("login_token",login_token);
edit.commit();
} catch (JSONException e) {
e.printStackTrace();
}
/*System.out.println("response "+data);
String call;
call = data;*/
if(jo.getString("err-code").equals("0"))
{
final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle("Alert!!!");
alert.setMessage(jo.getString("message"));
alert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton)
{
pDialog.dismiss();
dialog.dismiss();
}
});
getActivity().runOnUiThread(new Runnable() {
public void run() {
alert.show();
}
});
}
else
{
final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle("Alert !");
alert.setMessage(jo.getString("message"));
alert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
dialog.dismiss();
}
});
}
getActivity().runOnUiThread(new Runnable()
{
public void run()
{
pDialog.dismiss();
//alert.show();
}
});
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
return params;
}
private Object getSharedPreferences(String string) {
// TODO Auto-generated method stub
return null;
}
private Context getApplicationContext() {
// TODO Auto-generated method stub
return null;
}
@Override
protected void onPostExecute(String[] result)
{
super.onPostExecute(result);
}
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
SendJobDatabase.java
package com.sunmobile.navigationdrawer;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class SendJobDataBase
{
private static final String DATABASE_NAME = "myjob.db";
private static final int DATABASE_VERSION = 2;
static final String TABLE_NAME = "jobsend";
private static final String KEY_ID = "id";
private static Context context;
static SQLiteDatabase db;
private final ArrayList<member> user = new ArrayList<member>();
OpenHelper helper;
private SQLiteStatement insertStmt;
private static final String INSERT = "insert into " + TABLE_NAME + " (sename,smobno,spicktime,sunit,sstreet,ssuburb,sstate,scity,sdestination,sfare,sgroup) values (?,?,?,?,?,?,?,?,?,?,?)";
protected static final String enternpw = null;
public SendJobDataBase(Context context) {
SendJobDataBase.context = context;
OpenHelper openHelper = new OpenHelper(SendJobDataBase.context);
SendJobDataBase.db = openHelper.getWritableDatabase();
this.insertStmt = SendJobDataBase.db.compileStatement(INSERT);
}
public long insert(String sename,String smobno,String spicktime,String sunit,String sstreet,String ssuburb,String sstate,String scity,String sdestination,String sfare,String sgroup) {
this.insertStmt.bindString(1, sename);
this.insertStmt.bindString(2, smobno);
this.insertStmt.bindString(3, spicktime);
this.insertStmt.bindString(4, sunit);
this.insertStmt.bindString(5, sstreet);
this.insertStmt.bindString(6, ssuburb);
this.insertStmt.bindString(7, sstate);
this.insertStmt.bindString(8, scity);
this.insertStmt.bindString(9, sdestination);
this.insertStmt.bindString(10, sfare);
this.insertStmt.bindString(11, sgroup);
return this.insertStmt.executeInsert();
}
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","sename","smobno","spicktime","sunit","sstreet","ssuburb","sstate","scity","sdestination","sfare","sgroup" }, null, null, null, null, "sename asc");
int x=0;
if (cursor.moveToFirst()) {
do {
String[] b1=new String[]{cursor.getString(0),cursor.getString(1),cursor.getString(2),
cursor.getString(3),cursor.getString(4),cursor.getString(5),
cursor.getString(6),cursor.getString(7),cursor.getString(8),cursor.getString(9),cursor.getString(10),cursor.getString(11)};
list.add(b1);
x=x+1;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
cursor.close();
return list;
}
public ArrayList<member> getMembersList() {
ArrayList<member> user = new ArrayList<member>();
String selectQuery = "SELECT * FROM jobsend WHERE ssendjob LIKE '%One%'" ;
Cursor cursor = db.rawQuery(selectQuery,null);
if(cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
member contact = new member();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
user.add(contact);
} while (cursor.moveToNext());
}
}
cursor.close();
return user;
}
public ArrayList<member> getMembersList2() {
ArrayList<member> user = new ArrayList<member>();
String selectQuery = "SELECT * FROM jobsend WHERE ssendjob LIKE '%Two%'" ;
Cursor cursor = db.rawQuery(selectQuery,null);
if(cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
member contact = new member();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
user.add(contact);
} while (cursor.moveToNext());
}
}
cursor.close();
return user;
}
public void delete(int rowId) {
db.delete(TABLE_NAME, null, 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, sename TEXT, smobno TEXT,spicktime TEXT, spickaddr TEXT , ssendjob TEXT, sunit TEXT, sstreet TEXT, sstate TEXT, sdestination TEXT, sfare TEXT, sgroup TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
public Cursor rawQuery(String selectQuery ,Object object) {
// TODO Auto-generated method stub
return null;
}
public static SendJobDataBase getDBAdapterInstance(FragmentGroups viewPassword) {
// TODO Auto-generated method stub
return null;
}
public Object getenternpw() {
// TODO Auto-generated method stub
return null;
}
public static Cursor getSinlgeEntry() {
// TODO Auto-generated method stub
Cursor cur =db.rawQuery("SELECT * FROM "+ TABLE_NAME, null);
// colName1+"='"+name+"'" -> wherclause
System.out.println("Record count are "+cur.getCount());
return cur;
}
static public void close() {
// TODO Auto-generated method stub
}
/* public SendJobDataBase open() throws SQLException {
// TODO Auto-generated method stub
db = helper.getWritableDatabase();
return this;
} */
public SendJobDataBase getWritableDatabase() {
// TODO Auto-generated method stub
return null;
}
public void Delete_Contact(int id) {
SQLiteDatabase db = helper.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ?",
new String[] { String.valueOf(id) });
db.close();
}
public ArrayList<member> Get_Contacts() {
try {
user.clear();
// Select All Query
String selectQuery = "SELECT * FROM jobsend";
SQLiteDatabase db = helper.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
member contact = new member();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
// contact.setPhoneNumber(cursor.getString(2));
// contact.setEmail(cursor.getString(3));
// Adding contact to list
user.add(contact);
} while (cursor.moveToNext());
}
// return contact list
cursor.close();
db.close();
return user;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_contact", "" + e);
}
return user;
}
public void insert(String sename, String smobile, String spicktime, String sstreet,
String sstate, String scity, String ssuburb, String sdestination,
String sgroup, String sfare, String msuburb, String login_token) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:1)
这是一个片段代码,可能对创建Android的SQLite DB很有帮助。
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataHandler extends SQLiteOpenHelper {
/* DB Info*/
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "TASP_JARVIS";
public static DataHandler oDatabaseHander = null;
/* Tables */
private static final String TABLE_WLANInfo = "WLANInfo";
/* WLAN Info Table*/
private static final String KEY_wlan_SerNo = "SerNO";
private static final String KEY_wlan_IP = "IP";
private static final String KEY_wlan_Port = "Port";
private static final String KEY_wlan_Name = "Name";
private static final String KEY_wlan_Type = "Type";
public DataHandler(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static DataHandler getInstance(Context context) {
// Use the application context, which will ensure that you
// don't accidentally leak an Activity's context.
// See this article for more information: http://bit.ly/6LRzfx
if (oDatabaseHander == null){
oDatabaseHander = new DataHandler(context.getApplicationContext());
}
return oDatabaseHander;
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE_WLANINFO = "CREATE TABLE " + TABLE_WLANInfo + "("+KEY_wlan_SerNo+ " INTEGER ," +KEY_wlan_IP+ " TEXT ," +KEY_wlan_Port+ " INTEGER ," +KEY_wlan_Name+" INTEGER ," +KEY_wlan_Type+" INTEGER" + ");";
db.execSQL(CREATE_TABLE_WLANINFO);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_WLANInfo);
/*Create tables again*/
onCreate(db);
}
/* Insert WLAN Details */
public boolean InsertWLANInfo(WLANInfo wlanInfo){
long resvalue = -1;
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_wlan_SerNo, wlanInfo.getSerialNo());
values.put(KEY_wlan_IP, wlanInfo.getIP());
values.put(KEY_wlan_Port, wlanInfo.getPort());
values.put(KEY_wlan_Name, wlanInfo.getName());
values.put(KEY_wlan_Type, wlanInfo.getType());
resvalue = db.insert(TABLE_WLANInfo, null, values);
if(resvalue == -1)
return false;
return true;
}
/* Fetch WLAN Information from table */
public List<WLANInfo> FetchAllWLANDetails()
{
List<WLANInfo> WLANInfoList = new ArrayList<WLANInfo>();
String selectQuery = "SELECT * FROM " + TABLE_WLANInfo + "";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = null;
try{
cursor = db.rawQuery(selectQuery, null);
if(cursor.getCount() > 0){
if (cursor.moveToFirst())
do{
WLANInfo wlanInfo = new WLANInfo();
wlanInfo.setSerialNo(cursor.getInt(0));
wlanInfo.setIP(cursor.getString(1));
wlanInfo.setPort(cursor.getString(2));
wlanInfo.setIPName(cursor.getString(3));
wlanInfo.setType(cursor.getString(4));
WLANInfoList.add(wlanInfo);
}while (cursor.moveToNext());
cursor.close();
return WLANInfoList;
}else{
cursor.close();
return null;
}
}
finally{
cursor.close();
}
}
}
答案 1 :(得分:1)
我想你忘记了要做的事情。你甚至没有调用函数来打开你的数据库。
你可以这样做:
db = new SendJobDataBase(getApplicationContext());
db.open();
db.insert(sename,smobno, spicktime, sunit, sstreet,sstate, ssuburb,scity, sdestination, sgroup, sfare);
但首先在你的SEndJobDataBase上取消注释这个部分
/* public SendJobDataBase open() throws SQLException {
// TODO Auto-generated method stub
db = helper.getWritableDatabase();
return this;
} */
希望它有所帮助。干杯!