如何使用数据库将大量数据从一个活动传递到android中的另一个活动
Posted
技术标签:
【中文标题】如何使用数据库将大量数据从一个活动传递到android中的另一个活动【英文标题】:How to pass large set of datas from one activity to another activity in android using database 【发布时间】:2021-01-20 23:46:38 【问题描述】:我有一个 json 文件,其中包含大量数据,例如地点 ID、纬度、经度和日期。我想将这些数据从一个活动传递到另一个活动。当我对 Intent 执行相同操作时,应用程序显示错误。如何使用数据库传递数据?我必须从服务器拉 json 文件。当我拉数据时,我想创建一个数据库表并将数据传递给另一个活动。
public class ExampleActivity extends AppCompatActivity
EditText collDate;
Button pullGPSData;
SharedPreferences shp;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_track_example);
collDate = findViewById(R.id.collection_date);
pullGPSData = findViewById(R.id.pull_track_data);
public void listeners(View view)
switch (view.getId())
case R.id.pull_track_data:
try
String collectionDateString = collectionDate.getText().toString();
GPSDetail gpsDetail = new GPSDetail();
SharedPreferences shp = getSharedPreferences(Const.Shared_Pref_name, MODE_PRIVATE);
DbHelper dbHelper = new DbHelper(this);
Calendar cal = Calendar.getInstance();
Date todayDate = cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String todayDateString = sdf.format(todayDate);
if ( !todayDateString.equals(collectionDateString))
JSONObject jsonObjectKeyValue = new JSONObject();
jsonObjectKeyValue.put("keyValue", Const.AUTH_KEY_VALUE);
JSONArray jsonArray = new JSONArray();
jsonArray.put(jsonObjectKeyValue);
JSONObject jsonObject = new JSONObject();
jsonObject.put("AuthKey", jsonArray);
jsonObject.put("EmployeeCode",shp.getString(Const.Shp_Agent_Id,""));
jsonObject.put("FromDate", collectionDateString);
JSONObject gpsDetailsObj = new JSONObject();
gpsDetailsObj.put("gpstrackdetails", jsonObject);
Log.d("LogGPSTrack Details",gpsDetailsObj.toString());
new PullGPSTrackDetailsTask(this, gpsDetailsObj).execute();
catch (JSONException e)
e.printStackTrace();
break;
private static class PullGPSTrackDetailsTask extends AsyncTask<String, String, String>
WeakReference<ExampleActivity> context;
Dialog pd;
OkHttpClient okHttpClient;
String url;
Request request;
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
List<GPSDetail> gpsDetailList;
DbHelper dbHelper;
JSONObject jsonObject;
JSONObject resultJson;
String resultString;
public PullGPSTrackDetailsTask(ExampleActivity contextObj, JSONObject gpsDetailsObj)
this.context = new WeakReference<>(contextObj);
this.jsonObject = gpsDetailsObj;
okHttpClient = new OkHttpClient.Builder()
.connectTimeout(180,TimeUnit.SECONDS)
.readTimeout(180,TimeUnit.SECONDS)
.callTimeout(180,TimeUnit.SECONDS)
.build();
// pd = Fns.getProgressDialogLottie(context.get());
pd = new ProgressDialog(contextObj);
pd.setTitle("Please Wait");
pd.setCancelable(false);
@Override
protected void onPreExecute()
super.onPreExecute();
pd.show();
@Override
protected String doInBackground(String... strings)
try
url = USING_IP + URL_GET_GPS;
request = new Request.Builder()
//.header("X-Client-Type", "android")
.url(url)
.post(body)
.build();
Response response = okHttpClient.newCall(request).execute();
if (!response.isSuccessful())
return "failure";
resultString = response.body().string();
Log.e("LogresultString", resultString); //
catch (Exception e)
Log.e("Log", "Exception", e);
return "failure";
return "success";
@Override
protected void onPostExecute(String s)
super.onPostExecute(s);
pd.dismiss();
if (s.equals("success"))
Intent intent = new Intent(context.get(), ExampleSecondActivity.class);
intent.putExtra("value", resultString);
context.get().startActivity(intent);
Log.d("LogIntent",String.valueOf(intent));
else if (s.equals("failure"))
Toast.makeText(context.get(), "Pull Failed", Toast.LENGTH_LONG).show();
我的json
"GPS Track Details": [
"id": 1280,
"Longitude": -122.084,
"Latitude": 37.422,
"Date": "2020-08-21"
,
"id": 1232,
"Longitude": -121.023,
"Latitude": 37.302,
"Date": "2020-08-21"
,
"id": 1213,
"Longitude": -121.037,
"Latitude": 37.300,
"Date": "2020-08-21"
,
"id": 1226,
"Longitude": -120.098,
"Latitude": 37.422,
"Date": "2020-08-21"
,
.....
.....
]
我的日志猫
E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 5834308)
D/AndroidRuntime: Shutting down VM
E/CustomActivityOnCrash: App has crashed, executing CustomActivityOnCrash's UncaughtExceptionHandler
java.lang.RuntimeException: Failure from system
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1525)
at android.app.Activity.startActivityForResult(Activity.java:4224)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676)
at android.app.Activity.startActivityForResult(Activity.java:4183)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:663)
at android.app.Activity.startActivity(Activity.java:4507)
at android.app.Activity.startActivity(Activity.java:4475)
at android.os.AsyncTask.finish(AsyncTask.java:660)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: android.os.TransactionTooLargeException: data parcel size 5834308 bytes
at android.os.BinderProxy.transactNative(Native Method)
at android.os.BinderProxy.transact(Binder.java:615)
at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:3070)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1518)
at android.app.Activity.startActivityForResult(Activity.java:4224)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676)
at android.app.Activity.startActivityForResult(Activity.java:4183)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:663)
at android.app.Activity.startActivity(Activity.java:4507)
at android.app.Activity.startActivity(Activity.java:4475)
at android.os.AsyncTask.finish(AsyncTask.java:660)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
【问题讨论】:
【参考方案1】:Android 中的 Transaction 有 1 MB 的限制。您必须做一些工作才能传递数据。 这些是您可以尝试的一些解决方案。
解决方案 1
将数据保存到一个公共静态变量成员中,然后从第二个活动中访问它。
解决方案 2
将您的数据拆分成小块,并通过 bundle 从 Intent 传递。
解决方案 3
使用共享首选项,将 json 数据存储在共享首选项中,并在需要时从共享首选项访问它。
解决方案 4(如果数据真的很大)
保存到磁盘,根本不传输,然后直接从磁盘访问。
【讨论】:
以上是关于如何使用数据库将大量数据从一个活动传递到android中的另一个活动的主要内容,如果未能解决你的问题,请参考以下文章