使用sqlite数据库和类在活动之间传输数据时获取失败交付结果[重复]
Posted
技术标签:
【中文标题】使用sqlite数据库和类在活动之间传输数据时获取失败交付结果[重复]【英文标题】:Getting Failure delivering result while transfering data between activities using sqlite database and a class [duplicate] 【发布时间】:2021-10-15 11:15:38 【问题描述】:我正在开发一个任务应用程序,我想在几个活动之间传输一些数据。因此,为此,我创建了一个类,该类具有一种方法,可以让我获得在另一个活动中需要的结果。 (注意:类的名称viewmodel
与android 的ViewModel 无关。这样命名只是我这边的一个错误。)
错误信息:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.taskmasterv3, PID: 19537
java.lang.RuntimeException: Failure delivering result ResultInfowho=null, request=20, result=-1, data=Intent cmp=com.example.taskmasterv3/.TaskInfo (has extras) to activity com.example.taskmasterv3/com.example.taskmasterv3.TaskInfo: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getDatabasePath(java.lang.String)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:5209)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5250)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2242)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:245)
at android.app.ActivityThread.main(ActivityThread.java:8004)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:631)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:978)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getDatabasePath(java.lang.String)' on a null object reference
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:370)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:316)
at com.example.taskmasterv3.DBHelper.getdata(DBHelper.java:107)
at com.example.taskmasterv3.MyViewModel.timeIntFinder(MyViewModel.java:22)
at com.example.taskmasterv3.TaskInfo.onActivityResult(TaskInfo.java:441)
at android.app.Activity.dispatchActivityResult(Activity.java:8316)
at android.app.ActivityThread.deliverResults(ActivityThread.java:5202)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5250)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2242)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:245)
at android.app.ActivityThread.main(ActivityThread.java:8004)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:631)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:978)
Sqlite 数据库类代码:
package com.example.taskmasterv3;
import androidx.annotation.Nullable;
public class DBHelper extends SQLiteOpenHelper
public DBHelper(Context context)
super(context, "Subtaskdata.db", null, 1);
@Override
public void onCreate(SQLiteDatabase db)
db.execSQL("create Table Subtaskdata(subtaskname TEXT primary key, prihigh INTEGER, primed INTEGER, prilow INTEGER, timemore INTEGER, timemed INTEGER, timeless INTEGER, totalTime INTEGER, time INTEGER)");
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
db.execSQL("drop Table if exists Userdetails");
public Boolean insertSubtaskData(String subtaskName, int prihigh, int primed, int prilow, int timemore, int timemed, int timeless, int totalTime, int time)
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("subtaskname", subtaskName);
contentValues.put("priHigh", prihigh);
contentValues.put("priMed", primed);
contentValues.put("priLow", prilow);
contentValues.put("timeMore", timemore);
contentValues.put("timeMed", timemed);
contentValues.put("timeLess", timeless);
contentValues.put("totalTime", totalTime);
contentValues.put("time", time);
long result = db.insert("Subtaskdata", null, contentValues);
if (result < 0)
return false;
else
return true;
public Boolean updateSubtaskData(String subtaskName, int prihigh, int primed, int prilow, int timemore, int timemed, int timeless,int totalTime, int time)
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("subtaskname", subtaskName);
contentValues.put("prihigh", prihigh);
contentValues.put("primed", primed);
contentValues.put("prilow", prilow);
contentValues.put("timemore", timemore);
contentValues.put("timemed", timemed);
contentValues.put("timeless", timeless);
contentValues.put("totalTime", totalTime);
contentValues.put("time", time);
Cursor cursor = db.rawQuery("Select * from Subtaskdata where subtaskname = ?", new String[]subtaskName);
if (cursor.getCount()> 0)
long result = db.update("Subtaskdata", contentValues, "name=?", new String[]subtaskName);
if (result== -1)
return false;
else
return true;
else
return false;
public Boolean deletedata(String subtaskName)
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("Select * from Subtaskdata where subtaskname = ?", new String[]subtaskName);
if (cursor.getCount()> 0)
long result = db.delete("Subtaskdata","subtaskname=?", new String[]subtaskName);
if (result == -1)
return false;
else
return true;
else
return false;
public Cursor getdata ()
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("Select * from Subtaskdata", null);
return cursor;
public void deleteAll()
SQLiteDatabase db = getWritableDatabase();
db.delete("Subtaskdata", null, null);
db.execSQL("delete from "+ "Subtaskdata");
db.close();
活动代码:
package com.example.taskmasterv3;
public class TaskInfo extends AppCompatActivity
//Declaring variables
EditText etWorkingHours, etWorkingMinutes, etTaskName, etWorkingMins, etWorkinghrs, etSubtaskName;
Button btnNewSubtask;
Button btnSaveTaskName;
Button btnProceed;
ImageView ivLeft, ivRight;
TextView tvBreakTime;
TextView tvTaskName;
int breaktime = 10;
final int ENTER_SUBTASK = 20;
final int EDIT_SUBTASK = 40;
ListView lvSubtasks;
ArrayList<subtask> subtaskList = new ArrayList<>();
ScrollView scrollView;
TaskSummaryViewModel viewModel;
String taskName;
boolean NpriHigh;
boolean NpriMed;
boolean NpriLow;
boolean NtimeMore;
boolean NtimeMed;
boolean NtimeLess;
DBHelper dbHelper;
String subtname;
String pri;
String time;
int timeConstant;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_info);
tvTaskName.setVisibility(View.INVISIBLE);
if (tvTaskName.getText().equals(""))
tvTaskName.setClickable(false);
else
tvTaskName.setClickable(true);
// Code for the left right arrows along with break duration
ivRight.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
if (breaktime >= 10 && breaktime < 60)
breaktime += 5;
String time = breaktime + "";
tvBreakTime.setText(time);
else
String time = breaktime + "";
tvBreakTime.setText(time);
);
ivLeft.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
if (breaktime > 10 && breaktime <= 60)
breaktime -= 5;
String time = breaktime + "";
tvBreakTime.setText(time);
else
String time = breaktime + "";
tvBreakTime.setText(time);
);
btnNewSubtask.setEnabled(false);
btnSaveTaskName.setEnabled(false);
//save button enabler when task name is written
etTaskName.addTextChangedListener(new TextWatcher()
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
btnSaveTaskName.setEnabled(!TextUtils.isEmpty(s.toString().trim()));
@Override
public void afterTextChanged(Editable s)
);
btnSaveTaskName.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
tvTaskName.setVisibility(View.VISIBLE);
tvTaskName.setText(etTaskName.getText().toString().toUpperCase().trim());
etTaskName.setVisibility(View.GONE);
btnSaveTaskName.setVisibility(View.GONE);
btnNewSubtask.setEnabled(true);
);
tvTaskName.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
String tasksname = tvTaskName.getText().toString().trim();
tvTaskName.setText("");
etTaskName.setVisibility(View.VISIBLE);
etTaskName.setText(tasksname);
btnSaveTaskName.setVisibility(View.VISIBLE);
);
btnNewSubtask.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
Intent i2 = new Intent(TaskInfo.this, SubtaskActivity.class);
startActivityForResult(i2, ENTER_SUBTASK);
overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_up);
);
// THE DATABASE PART
btnProceed.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
if (etWorkingHours.getText().toString().isEmpty())
etWorkingHours.setText("0");
if (etWorkingMinutes.getText().toString().isEmpty())
etWorkingMinutes.setText("0");
if (etWorkinghrs.getText().toString().isEmpty())
etWorkinghrs.setText("0");
if (etWorkingMins.getText().toString().isEmpty())
etWorkingMins.setText("0");
int working_hours = Integer.parseInt(etWorkinghrs.getText().toString().trim());
int working_minutes = Integer.parseInt(etWorkingMins.getText().toString().trim());
int without_break_hours = Integer.parseInt(etWorkingHours.getText().toString().trim());
int without_break_minutes = Integer.parseInt(etWorkingMinutes.getText().toString().trim());
if (etWorkingHours.getText().toString().isEmpty() || etWorkingMinutes.getText().toString().isEmpty() || etWorkinghrs.getText().toString().isEmpty() || etWorkingMins.getText().toString().isEmpty())
Toast.makeText(TaskInfo.this, "Field cannot be empty, please try again.", Toast.LENGTH_SHORT).show();
else
if (working_hours != 0)
if (working_hours > without_break_hours)
int breaktime = Integer.parseInt(tvBreakTime.getText().toString());
Intent intent = new Intent(TaskInfo.this, TaskSummary.class);
intent.putExtra("working_hours", working_hours);
intent.putExtra("working_minutes", working_minutes);
intent.putExtra("without_break_hours", without_break_hours);
intent.putExtra("without_break_minutes", without_break_minutes);
intent.putExtra("break_duration", breaktime);
intent.putExtra("subtaskname", taskName);
intent.putExtra("priigh", NpriHigh);
intent.putExtra("primed", NpriMed);
intent.putExtra("prilow", NpriLow);
intent.putExtra("timemore", NtimeMore);
intent.putExtra("timemed", NtimeMed);
intent.putExtra("timeless", NtimeLess);
intent.putExtra("timeconstant", timeConstant);
startActivity(intent);
if (working_hours == without_break_hours)
if (working_minutes >= without_break_minutes)
int breaktime = Integer.parseInt(tvBreakTime.getText().toString());
Intent intent = new Intent(TaskInfo.this, TaskSummary.class);
intent.putExtra("working_hours", working_hours);
intent.putExtra("working_minutes", working_minutes);
intent.putExtra("without_break_hours", without_break_hours);
intent.putExtra("without_break_minutes", without_break_minutes);
intent.putExtra("break_duration", breaktime);
intent.putExtra("subtaskname", taskName);
intent.putExtra("priigh", NpriHigh);
intent.putExtra("primed", NpriMed);
intent.putExtra("prilow", NpriLow);
intent.putExtra("timemore", NtimeMore);
intent.putExtra("timemed", NtimeMed);
intent.putExtra("timeless", NtimeLess);
intent.putExtra("timeconstant", timeConstant);
startActivity(intent);
if (working_minutes < without_break_minutes)
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
if (working_hours < without_break_hours)
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
if (working_hours == 0)
if (without_break_hours == 0)
if (working_minutes >= without_break_minutes)
int breaktime = Integer.parseInt(tvBreakTime.getText().toString());
Intent intent = new Intent(TaskInfo.this, TaskSummary.class);
intent.putExtra("working_hours", working_hours);
intent.putExtra("working_minutes", working_minutes);
intent.putExtra("without_break_hours", without_break_hours);
intent.putExtra("without_break_minutes", without_break_minutes);
intent.putExtra("break_duration", breaktime);
intent.putExtra("subtaskname", taskName);
intent.putExtra("prihigh", NpriHigh);
intent.putExtra("primed", NpriMed);
intent.putExtra("prilow", NpriLow);
intent.putExtra("timemore", NtimeMore);
intent.putExtra("timemed", NtimeMed);
intent.putExtra("timeless", NtimeLess);
intent.putExtra("timeconstant", timeConstant);
startActivity(intent);
if (working_minutes < without_break_minutes)
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
if (without_break_hours != 0)
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
);
//Applying the max min thing for which the class InputFilterMinMax is defined
etWorkingHours.setFilters(new InputFilter[]new InputFilterMinMax("0", "24"));
etWorkingMinutes.setFilters(new InputFilter[]new InputFilterMinMax("0", "59"));
etWorkinghrs.setFilters(new InputFilter[]new InputFilterMinMax("0", "24"));
etWorkingMins.setFilters(new InputFilter[]new InputFilterMinMax("0", "59"));
// This is where I try to implement the executer :
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ENTER_SUBTASK)
if (resultCode == RESULT_OK)
SubtaskAdapter adapter = new SubtaskAdapter(this, subtaskList);
assert data != null;
String subtaskName = data.getStringExtra("subtaskName");
boolean priHigh = data.getBooleanExtra("priHigh", false);
boolean priMed = data.getBooleanExtra("priMed", false);
boolean priLow = data.getBooleanExtra("priLow", false);
boolean timeMore = data.getBooleanExtra("timeMore", false);
boolean timeMed = data.getBooleanExtra("timeMed", false);
boolean timeLess = data.getBooleanExtra("timeLess", false);
int time = data.getIntExtra("time", 1);
lvSubtasks.setAdapter(adapter);
subtask subtask = new subtask(subtaskName, priHigh, priMed, priLow, timeMore, timeMed, timeLess, time);
subtaskList.add(subtask);
adapter.addANewSubTask(subtask);
MyViewModel myViewModel = new MyViewModel();
timeConstant = myViewModel.timeIntFinder(subtaskList);
taskName = subtaskName;
NpriHigh = priHigh;
NpriMed = priMed;
NpriLow = priLow;
NtimeLess = timeLess;
NtimeMed = timeMed;
NtimeMore = timeMore;
boolean delete = getIntent().getBooleanExtra("deleted", false);
if (delete)
类代码:
package com.example.taskmasterv3;
import android.content.Context;
import android.database.Cursor;
import androidx.lifecycle.ViewModel;
import java.util.ArrayList;
public class MyViewModel
int timeInt;
int totalTime;
int timeConstant;
DBHelper dbHelper;
Context context;
public int timeIntFinder(ArrayList<subtask> list)
dbHelper = new DBHelper(context);
Cursor cursor = dbHelper.getdata();
for(int i = 0; i < list.size(); i++)
timeInt += list.get(i).getTime();
while (cursor.moveToNext())
totalTime = cursor.getInt(7);
timeConstant = totalTime / timeInt;
return timeConstant;
我想要数据的活动代码:
package com.example.taskmasterv3;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.PriorityQueue;
public class TaskSummary extends AppCompatActivity
ListView lvTaskList;
TextView tvBreak, tvBreakAfterEvery, txt1, txt2, text1, hmm;
TextView break_duration_mins;
ArrayList<SubtaskPartTwo> subtaskList = new ArrayList<>();
//String subtname;
//String pri;
//String time;
int working_hours;
int working_minutes;
int totalTime;
DBHelper dbHelper;
int timeInts;
int timeConstant;
int answer;
@Override
public boolean onCreateOptionsMenu(Menu menu)
getMenuInflater().inflate(R.menu.tasksummary, menu);
return super.onCreateOptionsMenu(menu);
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item)
dbHelper.deleteAll();
if (item.getItemId() == R.id.restore)
Intent inti = new Intent(this, TaskInfo.class);
startActivity(inti);
return super.onOptionsItemSelected(item);
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_summary);
MyViewModel myViewModel = new MyViewModel();
lvTaskList = findViewById(R.id.lvTaskList);
tvBreak = findViewById(R.id.tvBreak);
tvBreakAfterEvery = findViewById(R.id.tvBreakAfterEvery);
txt1 = findViewById(R.id.txt1);
txt2 = findViewById(R.id.txt2);
break_duration_mins = findViewById(R.id.break_duration_mins);
text1 = findViewById(R.id.text1);
hmm = findViewById(R.id.hmm);
dbHelper = new DBHelper(this);
working_hours = getIntent().getIntExtra("working_hours", 1);
working_minutes = getIntent().getIntExtra("working_minutes", 0);
timeConstant = getIntent().getIntExtra("timeconstant", 1);
int alol = working_hours * 60;
int blol = working_minutes;
totalTime = alol + blol;
double without_break_hours = getIntent().getIntExtra("without_break_hours", 1);
double without_break_minutes = getIntent().getIntExtra("without_break_minutes", 0);
double break_duration = getIntent().getIntExtra("break_duration", 20);
String a = working_hours + " h";
txt1.setText(a);
String b = working_minutes + " m";
break_duration_mins.setText(b);
String c = break_duration + " m";
txt2.setText(c);
//Mathematics
double g = working_hours * 100;
double h = g + working_minutes;
double i = h + break_duration;
double j = i / 60;
double p = (int) j;
double q = j - p;
double r = q * 60;
without_break_hours = p;
without_break_minutes = r;
String d = without_break_hours + " h";
String e = without_break_minutes + " m";
text1.setText(d);
hmm.setText(e);
Cursor res = dbHelper.getdata();
SubtaskDetailAdapter adapter = new SubtaskDetailAdapter(this, subtaskList);
lvTaskList.setAdapter(adapter);
while (res.moveToNext() && res != null)
SubtaskPartTwo subtaskPartTwo = new SubtaskPartTwo(res.getString(0), res.getInt(1), res.getInt(2), res.getInt(3), res.getInt(4), res.getInt(5), res.getInt(6), 0, res.getInt(8), totalTime, timeConstant);
//subtaskList.add(subtaskPartTwo);
adapter.addANewSubTask(subtaskPartTwo);
// method from data transfer interface
【问题讨论】:
请发布完整的日志详细信息以准确找出错误 @Udhaya 好的,当然。 【参考方案1】:好的,这是您的解决方案,
在您的MyViewModel.java
中,您已经通过传递一个为空的Context
对象来初始化DBHelper
。所以修改你的 MyViewModel 为
选项 1:
package com.example.taskmasterv3;
import android.content.Context;
import android.database.Cursor;
import androidx.lifecycle.ViewModel;
import java.util.ArrayList;
public class MyViewModel
int timeInt;
int totalTime;
int timeConstant;
DBHelper dbHelper;
public int timeIntFinder(ArrayList<subtask> list,Context context)
dbHelper = new DBHelper(context);
Cursor cursor = dbHelper.getdata();
for(int i = 0; i < list.size(); i++)
timeInt += list.get(i).getTime();
while (cursor.moveToNext())
totalTime = cursor.getInt(7);
timeConstant = totalTime / timeInt;
return timeConstant;
在 onActivityResult
的 ActivityCode 中更改
timeConstant = myViewModel.timeIntFinder(subtaskList);
到
timeConstant = myViewModel.timeIntFinder(subtaskList,this);
选项 2:
在构造函数中传递上下文
添加带有上下文的构造函数作为 MyViewModel 的参数
public class MyViewModel
int timeInt;
int totalTime;
int timeConstant;
DBHelper dbHelper;
Context context;
public MyViewModel(Context context)
this.context = context;
public int timeIntFinder(ArrayList<subtask> list)
dbHelper = new DBHelper(context);
Cursor cursor = dbHelper.getdata();
for(int i = 0; i < list.size(); i++)
timeInt += list.get(i).getTime();
while (cursor.moveToNext())
totalTime = cursor.getInt(7);
timeConstant = totalTime / timeInt;
return timeConstant;
现在无论您在哪里初始化 MyViewModel 都会传递有效的上下文。
【讨论】:
这确实有效。谢谢。该应用程序现在不会崩溃。即使我实现的公式(使用 for 循环)不起作用,这也是我要处理的问题。感谢您的帮助:)以上是关于使用sqlite数据库和类在活动之间传输数据时获取失败交付结果[重复]的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 android 中的 SQLite 扩展类在数据库中插入值?