gpt4 book ai didi

android - 我应该怎么做才能将数据从 json 插入到 Android 中的 sqlite

转载 作者:行者123 更新时间:2023-11-29 01:37:54 24 4
gpt4 key购买 nike

我在 android 中创建 sqlit 数据库以将来自 json 的数据存储在数据库中,以便在应用程序离线时查看数据我添加代码来创建数据库和列,但我不知道如何将数据从 json 插入到我的数据库中。我应该怎么做才能将数据从 json 插入到 sqlite我应该在代码中添加什么来做到这一点?

SQLiteOpenHelper

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class BookingTabel extends SQLiteOpenHelper {


private static final int DB_VERSION = 1;

private static final String DB_NAME = "myDB";

// Books table name
private static final String TABLE_BOOKINDS = "bookings";

// Books Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_BOOKING_NUM = "booking_num";
private static final String KEY_TITLE = "title";
private static final String KEY_BOOKING_START= "booking_start";
private static final String KEY_BOOKING_END = "booking_end";
private static final String KEY_PROPERTY = "property_type";
private static final String KEY_CUSTOMER_ID = "customer_id";
private static final String KEY_DESCRIPTION = "description";
private static final String KEY_ACCEPT_STATUS = "accept_status";
private static final String KEY_BOOLING_ADDRESS = "booking_address";
private static final String KEY_PO_BOX = "po_box";
private static final String KEY_CREATED = "created";
private static final String KEY_POSTCODE = "postcode";
private static final String KEY_STATE = "state";
private static final String KEY_STREET_ADDRESS = "street_address";
private static final String KEY_STREET_NUMBER = "street_number";
private static final String KEY_SUBURB = "suburb";
private static final String KEY_UNIT_LOT_NUMBER = "unit_lot_number";
private static final String KEY_STATUS = "status";
private static final String KEY_CONVERT_STATUS = "convert_status";
private static final String KEY_QOUTE = "qoute";
private static final String KEY_SUB_TOTAL = "sub_total";
private static final String KEY_TOTAL_DISCOUNT = "total_discount";
private static final String KEY_BOOKING_DISTANCE = "booking_distance";
private static final String KEY_GST = "gst";
private static final String KEY_ORIGINAL_BOOKING_ID = "original_booking_id";

public BookingTabel(Context context) {
super(context, DB_NAME, null,DB_VERSION);
// TODO Auto-generated constructor stub
}

private static final String[] COLUMNS = {KEY_ID,KEY_BOOKING_NUM,KEY_TITLE,KEY_BOOKING_START,KEY_BOOKING_END,KEY_PROPERTY,
KEY_CUSTOMER_ID,KEY_DESCRIPTION,KEY_ACCEPT_STATUS,KEY_BOOLING_ADDRESS,KEY_PO_BOX,KEY_CREATED ,
KEY_POSTCODE,KEY_STATE,KEY_STREET_ADDRESS,KEY_STREET_NUMBER,KEY_SUBURB,KEY_UNIT_LOT_NUMBER,KEY_STATUS,
KEY_CONVERT_STATUS,KEY_QOUTE,KEY_SUB_TOTAL,KEY_TOTAL_DISCOUNT,KEY_BOOKING_DISTANCE,KEY_GST,
KEY_ORIGINAL_BOOKING_ID,};

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub

// SQL statement to create book table
String CREATE_BOOKINDS_TABLE =
"CREATE TABLE booking ( " + "id INTEGER PRIMARY KEY"+ "booking_num VARCHAR(250)"+ "title VARCHAR(250)"+
"booking_start DATETIME "+"booking_end DATETIME "+
"property_type VARCHAR(250) NOT NULL DEFAULT 'House'"+
"customer_id INTEGER+description TEXT"+"accept_status VARCHAR(250)"+"booking_address VARCHAR(250)" +
"po_box VARCHAR(250)"+ "created INTEGER"+ "postcode INTEGER"+"state VARCHAR(250)"+
"street_address VARCHAR(250)"+"street_number INTEGER"+"suburb VARCHAR(250)"+"unit_lot_number INTEGER"+
"status VARCHAR(250)"+"convert_status VARCHAR(250)"+"qoute FLOAT"+"sub_total FLOAT"+"total_discount FLOAT"+
"booking_distance FLOAT"+"gst FLOAT"+"original_booking_id INTEGER )";


// create books table
db.execSQL(CREATE_BOOKINDS_TABLE);

}

@Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS bookings");

// create fresh books table
this.onCreate(db);
}

public void addBookings(Bookings booking){
Log.d("addBooking", booking.toString());

SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(KEY_BOOKING_NUM,booking.getbookingnum());
values.put(KEY_TITLE,booking.gettitle());
values.put(KEY_BOOKING_START ,booking.getbookingstart() );
values.put(KEY_BOOKING_END ,booking.getbooking_end() );
values.put(KEY_PROPERTY ,booking.getpropertytype() );
values.put(KEY_CUSTOMER_ID ,booking.getcustomer_id() );
values.put( KEY_DESCRIPTION,booking.getdescription() );
values.put( KEY_ACCEPT_STATUS,booking.getaccept_status() );
values.put( KEY_BOOLING_ADDRESS,booking.getbookingaddress() );
values.put( KEY_PO_BOX,booking.getpo_box() );
values.put( KEY_CREATED,booking.getcreated() );
values.put( KEY_POSTCODE,booking.getpostcode() );
values.put( KEY_STATE,booking.getstate() );
values.put( KEY_STREET_ADDRESS,booking.getstreet_address() );
values.put( KEY_STREET_NUMBER,booking.getstreet_number() );
values.put( KEY_SUBURB,booking.getsuburb() );
values.put( KEY_UNIT_LOT_NUMBER,booking.getunit_lot_number() );
values.put( KEY_STATUS,booking.getstatus() );
values.put( KEY_CONVERT_STATUS,booking.getconvert_status() );
values.put( KEY_QOUTE,booking.getqoute() );
values.put( KEY_SUB_TOTAL,booking.getsub_total() );
values.put( KEY_TOTAL_DISCOUNT,booking.gettotal_discount() );
values.put( KEY_BOOKING_DISTANCE,booking.getbooking_distance() );
values.put( KEY_GST,booking.getgst() );
values.put( KEY_ORIGINAL_BOOKING_ID,booking.getoriginal_booking_id() );

db.insert(TABLE_BOOKINDS, null, values);
db.close();
}


}

预订

public class Bookings {

private int id;
private String booking_num;
private String title;
private String booking_start;
private String booking_end;
private String property_type;
private int customer_id;
private String description;
private String accept_status;
private String booking_address;
private String po_box;
private int created;
private int postcode;
private String state;
private String street_address;
private int street_number;
private String suburb;
private int unit_lot_number;
private String status;
private String convert_status;
private Float qoute;
private Float sub_total;
private Float total_discount;
private Float booking_distance;
private Float gst;
private int original_booking_id;

public Bookings(){}

public Bookings(String booking_num ,String title ,String booking_start ,String booking_end ,
String property_type ,int customer_id ,String description ,String accept_status ,String booking_address ,
String po_box ,int created ,int postcode ,String state ,String street_address ,int street_number ,
String suburb ,int unit_lot_number ,String status ,String convert_status ,Float qoute ,Float sub_total ,
Float total_discount ,Float booking_distance ,Float gst ,int original_booking_id){
this.booking_num = booking_num;
this.title = title;
this.booking_start = booking_start;
this.booking_end =booking_end ;
this.property_type =property_type;
this.customer_id = customer_id;
this.description = description;
this.accept_status = accept_status;
this.booking_address = booking_address;
this.po_box = po_box;
this.created = created;
this.postcode = postcode;
this.state = state;
this.street_address = street_address;
this.street_number = street_number;
this.suburb = suburb;
this.unit_lot_number = unit_lot_number;
this.status = status;
this.convert_status = convert_status;
this.qoute = qoute;
this.sub_total = sub_total;
this.total_discount = total_discount;
this.booking_distance = booking_distance;
this.gst = gst;
this.original_booking_id = original_booking_id;
}


// ---- setter
public void setId(int id){
this.id = id;
}

public void setbookingnum(String booking_num){
this.booking_num = booking_num;
}

public void settitle(String title){
this.title = title;
}
public void setbookingstart(String booking_start){
this.booking_start = booking_start;
}
public void setbookingend(String booking_end ){
this.booking_end = booking_end ;
}
public void setpropertytype(String property_type){
this.property_type = property_type;
}
public void setcustomerid(int customer_id){
this.customer_id = customer_id;
}
public void setdescription(String description){
this.description = description;
}
public void setacceptstatus(String accept_status){
this.accept_status = accept_status;
}
public void setbookingaddress(String booking_address){
this.booking_address = booking_address;
}
public void setpobox(String po_box ){
this.po_box = po_box ;
}
public void setcreated(int created){
this.created = created ;
}
public void setpostcode(int postcode){
this.postcode = postcode;
}
public void setstate(String state){
this.state =state ;
}
public void setstreetaddress(String street_address){
this.street_address = street_address ;
}
public void setstreetnumber(int street_number){
this.street_number = street_number;
}
public void setsuburb(String suburb){
this.suburb = suburb;
}
public void setunit_lot_number(int unit_lot_number ){
this.unit_lot_number = unit_lot_number;
}
public void setstatus(String status){
this.status =status ;
}
public void setconvert_status(String convert_status){
this.convert_status =convert_status ;
}
public void setqoute(Float qoute){
this.qoute = qoute;
}
public void setsubtotal(Float sub_total ){
this.sub_total =sub_total ;
}
public void settotal_discount(Float total_discount){
this.total_discount =total_discount ;
}
public void setbookingdistance(Float booking_distance){
this.booking_distance =booking_distance ;
}
public void setgst(Float gst){
this.gst = gst;
}
public void setoriginal_booking_id(int original_booking_id){
this.original_booking_id = original_booking_id ;
}


// --- getter ---


public int getId(){
return id;
}
public String getbookingnum(){
return booking_num;
}
public String gettitle(){
return title ;
}
public String getbookingstart(){
return booking_start ;
}
public String getbooking_end(){
return booking_end;
}
public String getpropertytype(){
return property_type;
}
public int getcustomer_id(){
return customer_id ;
}
public String getdescription(){
return description;
}
public String getaccept_status(){
return accept_status;
}
public String getbookingaddress(){
return booking_address ;
}
public String getpo_box(){
return po_box;
}
public int getcreated(){
return created;
}
public int getpostcode(){
return postcode ;
}
public String getstate(){
return state ;
}
public String getstreet_address(){
return street_address ;
}
public int getstreet_number(){
return street_number ;
}
public String getsuburb(){
return suburb ;
}
public int getunit_lot_number(){
return unit_lot_number ;
}
public String getstatus(){
return status;
}
public String getconvert_status(){
return convert_status;
}
public Float getqoute(){
return qoute ;
}
public Float getsub_total(){
return sub_total;
}
public Float gettotal_discount(){
return total_discount;
}
public Float getbooking_distance(){
return booking_distance;
}
public Float getgst(){
return gst;
}
public int getoriginal_booking_id(){
return original_booking_id ;
}


public String toString(){
return "Booking >> id:"+id+" | booking_num:"+booking_num+" | title:"+title+
" | booking_start"+booking_start+" | booking_end"+booking_end+" | property_type"+property_type+
" | customer_id "+customer_id +" |description "+description+" | accept_status"+accept_status+
" | booking_address"+booking_address+" | po_box"+po_box+" | created"+created+" | postcode"+postcode+
" | state"+state+" | street_address"+street_address+" | street_number"+street_number+
" | suburb"+suburb+" | unit_lot_number"+unit_lot_number+" | status"+status+
" | convert_status"+convert_status+" | qoute"+qoute+" | sub_total"+sub_total+
" | total_discount"+total_discount+" | booking_distance"+booking_distance+" | gst"+gst+
" | original_booking_id"+original_booking_id;
}


}

allbookingfrag

import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class allbookingfrag extends Fragment {

public static final String PREFS_NAME = "MyApp_Settings";
private static final String givenUsername = "email";
private static final String givenPassword = "password";

private static final String TAG_RESULT = "result";
private static final String TAG_BOOKING_NUM = "booking_num";
private static final String TAG_TITLE = "title";
private static final String TAG_STATUS = "status";
private static final String TAG_BOOKING_START = "booking_start";
private static final String TAG_BOOKING_END = "booking_end";
private static final String TAG_QOUTE = "qoute";
private static final String TAG_BOOKING_ADDRESS = "booking_address";
private static final String TAG_CUSTOMER = "customer";
private static final String TAG_CUSTOMER_NAME = "name";
String result = null;
ArrayList<HashMap<String, String>> resultList;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.allbookingfrag, container, false);

SharedPreferences settings = getActivity().getSharedPreferences(PREFS_NAME, 0);
String email = settings.getString("email",givenUsername);
String password = settings.getString("password",givenPassword);
System.out.println("In allbooking activity names is : " + email + "password is : " + password );

connectWithHttpGet(email, password );

resultList = new ArrayList<HashMap<String, String>>();

ListView listallbooking = (ListView)rootView.findViewById(R.id.listallbooking);

return rootView;


}


private void connectWithHttpGet(String email, String password ) {

class HttpGetAsyncTask extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... params) {

// As you can see, doInBackground has taken an Array of Strings as the argument
//We need to specifically get the givenUsername and givenPassword
String email = params[0];
String password = params[1];
// String uuid = params[2];
System.out.println("paramUsername: " + email + " paramPassword is : " + password + "paramuuid is: ");

// Create an intermediate to connect with the Internet
HttpClient httpClient = new DefaultHttpClient();

// Sending a GET request to the web page that we want
// Because of we are sending a GET request, we have to pass the values through the URL
HttpGet httpGet = new HttpGet("xxxxxxxxxx?email=" + email + "&password=" + password +"&uuid=fdgsfsdfsfsf"+"&mode=booking" );
StringBuilder stringBuilder = new StringBuilder();


try {
HttpResponse httpResponse = httpClient.execute(httpGet);


HttpEntity httpEntity = httpResponse.getEntity();
String jsonStr = null;
jsonStr = EntityUtils.toString(httpEntity);
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONObject resultObj = jsonObj.getJSONObject("result");
JSONArray resultArr = resultObj.getJSONArray("result");
//Log.d("Response: ", "> " + jsonStr);


// looping through All Contacts
for (int i = 0; i < resultArr.length(); i++) {
JSONObject c = resultArr.getJSONObject(i);
String booking_num = c.getString(TAG_BOOKING_NUM);
String title = c.getString(TAG_TITLE);

/* String splittitle= title;
String [] mysplit_title = null;
mysplit_title = splittitle.split("-");
String First_title=mysplit_title[0];
String Qoute_title=mysplit_title[1];
String Username_title=mysplit_title[2];*/

String status = c.getString(TAG_STATUS);
String booking_start = c.getString(TAG_BOOKING_START);

String my_starttime=booking_start;
String [] my_date_time_start = null;
my_date_time_start = my_starttime.split(" ");
String Date_str_start=my_date_time_start[0];
String Time_str_start=my_date_time_start[1];


String booking_end = c.getString(TAG_BOOKING_END);

String my_endtime=booking_start;
String [] my_date_time_end = null;
my_date_time_end = my_endtime.split(" ");
String Date_str_end=my_date_time_end[0];
String Time_str_end=my_date_time_end[1];

String qoute = c.getString(TAG_QOUTE);
String booking_address = c.getString(TAG_BOOKING_ADDRESS);
// System.out.println("booking_num: " + booking_num + " title is : " + title + "booking_start: "+ booking_start);

JSONObject customer = c.getJSONObject(TAG_CUSTOMER);
String name = customer.getString(TAG_CUSTOMER_NAME);

BookingTabel db = new BookingTabel(getActivity());
// tmp hashmap for single contact
HashMap<String, String> result3 = new HashMap<String, String>();

// adding each child node to HashMap key => value
result3.put(TAG_BOOKING_NUM, booking_num);
result3.put(TAG_TITLE, title);
result3.put(TAG_STATUS, status);
result3.put(TAG_BOOKING_START, Time_str_start);
result3.put(TAG_BOOKING_END, Time_str_end);
result3.put(TAG_QOUTE, qoute);
result3.put(TAG_BOOKING_ADDRESS, booking_address);
result3.put(TAG_CUSTOMER_NAME, name);


// Hashmap for ListView
// ArrayList<HashMap<String, String>> resultList = new ArrayList<HashMap<String, String>>();

// adding contact to contact list
resultList.add(result3);
System.out.println("resultList: " + resultList);

}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;


}

// Argument comes for this method according to the return type of the doInBackground() and
//it is the third generic type of the AsyncTask
@Override
protected void onPostExecute(String result) {

ListView listallbooking = (ListView)getActivity().findViewById(R.id.listallbooking);

ListAdapter adapter = new SimpleAdapter(getActivity(), resultList,
R.layout.list_item_allbooking,
new String[] { TAG_TITLE,TAG_STATUS, TAG_BOOKING_START,
TAG_BOOKING_END,TAG_QOUTE,TAG_BOOKING_ADDRESS,TAG_CUSTOMER_NAME }, new int[] {
R.id.listtitle,R.id.liststatus,
R.id.listbooking_start, R.id.listbooking_end,R.id.listqoute,R.id.listbooking_address,R.id.listcustomername});
listallbooking.setAdapter(adapter);
// System.out.println("resultList: " + resultList);
// setOnItemClickListener
listallbooking.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View view, int postion,
long arg3) {
// TODO Auto-generated method stub
Intent detailesitem = new Intent(getActivity().getBaseContext(), estimates.class);
startActivity(detailesitem);
}
});


}
}

// Initialize the AsyncTask class
HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
// Parameter we pass in the execute() method is relate to the first generic type of the AsyncTask
// We are passing the connectWithHttpGet() method arguments to that
httpGetAsyncTask.execute(email, password );

}



}

最佳答案

为了更好地维护代码,我建议使用 Android Volley 库。您获得异步 API 来调用 rest API,回调直接提供您的 JSON 对象。

并使用 GSON 库将 JSON 转换为您定义的 Java 对象(预订)。您唯一需要做的就是定义与 JSON 结构中的键相同的 Bookings 成员变量名称。

现在您应该有一个实用方法可以通过从 Bookings 对象中读取值来插入到数据库中。

然后生成可维护的无错误代码。

关于android - 我应该怎么做才能将数据从 json 插入到 Android 中的 sqlite,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26713555/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com