gpt4 book ai didi

Android 无法将文本从编辑 TextView 保存到数据库

转载 作者:行者123 更新时间:2023-11-30 03:05:26 25 4
gpt4 key购买 nike

在我的应用程序中,我允许用户向某些号码发送警报消息。用户可以在 EditText 中编写自己选择的任何文本,也可以从 spinner 的预定义文本中选择文本。早些时候我将文本保存到 SharedPreferences 但现在我希望它在 SQLite 中。我能够将联系电话保存到用户想要发送的数据库中消息,但我无法将消息保存到数据库。我希望当用户输入自己的文本或从 spinner 中选择任何文本后,他按下保存按钮并将文本保存到数据库中。请帮助。P.S _ 我认为在从数据库调用方法到按钮 onclick 时遇到了问题。请查看我的代码并建议我该怎么做。

主 Activity .java

public class MainActivity extends Activity implements LocationListener {
String separator = "; ";
private Button btn_cntct;
private EditText message;
LinearLayout linearLayoutSec;
private Button GPSState;
Button b_alert;
Button b_save_message;
public int REQUESTCODE = 1;
int temp;
ScrollView ScrView;
Context c = MainActivity.this;
Button AlertMessages;
private static ArrayList<ContactItems> selectedContactList = new ArrayList<ContactItems>();
static CustomAdapter adapter;
public static String[] myvalue = new String[1];
Spinner spinner;
static String[] alert = { " ", "I am in danger", "Help Me", "Watch Out",
"Look For Me", "Cover ME" };
MySQLiteHelper dbHelper;
String savedMessage;
Button save;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
message = (EditText) findViewById(R.id.et_message);
// message.setFocusable(false);
dbHelper = new MySQLiteHelper(this);
String dis = dbHelper.getMsg();
if (dis != null) {
message.setText(dis);
}

bsave = (Button) findViewById(R.id.b_save);
bsave.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String str = message.getText().toString();
dbHelper.updateMsg(str);

}
});




spinner = (Spinner) findViewById(R.id.Spin_alert_message);

ArrayAdapter<String> adp = new ArrayAdapter<String>(
getApplicationContext(), android.R.layout.simple_spinner_item,
alert);
spinner.setAdapter(adp);

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {

String selectedItem = alert[position];
message.setText(selectedItem);

// loads the text that has been stored to SP and set it to
// EditText
//message.setText(pref.getString("AutoSave", ""));
// to bring cursor to front
message.setSelection(message.getText().length());



}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});

/************************** saving custom message *****************************/

// for saving text that user can change as per need

ListView contactlist = (ListView) findViewById(R.id.contactListitems);
Resources res = getResources();
adapter = new CustomAdapter(MainActivity.this, selectedContactList, res,MainActivity.this);
contactlist.setAdapter(adapter);

/********************************* GPS *******************************/

// checking if GPS is already on or not.
// If not then displaying the alert dialog
// requesting user to On GPS.
GPSState = (Button) findViewById(R.id.bGPSstate);
boolean isGPSEnabled = false; //
// Declaring a Location Manager
LocationManager locationManager;

locationManager = (LocationManager) getApplicationContext()
.getSystemService(LOCATION_SERVICE);

// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);

if (!isGPSEnabled) {
// no GPS provider is enabled
// displaying GPS status on the button and and opening GPS settings

GPSState.setText("GPS is off.turn it on");
GPSState.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivityForResult(
new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
REQUESTCODE);

}
});
// setting up the dialog box for GPS Settings

// creating alertdialog
AlertDialog.Builder builder = new AlertDialog.Builder(c);

builder.setTitle("Settings");
builder.setMessage("Enable GPS for the Application");

builder.setPositiveButton("GPS Setting",

new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));

dialog.dismiss();

}

});

builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {

new AlertDialog.Builder(MainActivity.this)
.setTitle("How to use Application")
.setMessage(
"You must enable the GPS in order to use this application. Press Activate and then press Power Button twice in order to send the alert message to the selected contacts")
.setNeutralButton(
"OK",
new DialogInterface.OnClickListener() {

@Override
public void onClick(
DialogInterface dialog,
int which) {
// do something // for //
// returning back to // //
// application
dialog.cancel();

}
}).show();
dialog.dismiss();

}
});

builder.show();

} else {
GPSState.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivityForResult(
new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
REQUESTCODE);
}
});
}

// defining button elements for picking contacts from phone-book
btn_cntct = (Button) findViewById(R.id.bpickperson);
btn_cntct.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
if (selectedContactList.size() < 4) {
// TODO Auto-generated method stub
// using Intent for fetching contacts from phone-book
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, REQUESTCODE);
} else {
// print toast for not allowing user to add more contacts
Toast.makeText(getApplicationContext(),
"You Can Only Add 4 Contacts ", Toast.LENGTH_SHORT)
.show();
}

}

});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

// calling onActivityResult when contacts has been selected from the
// phone-book, giving back the REQUESTCODE i started it with, the RC it
// returned with
// any additional data from it.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
boolean isGPSEnabled = false;
GPSState = (Button) findViewById(R.id.bGPSstate);
LocationManager locationManager;
locationManager = (LocationManager) getApplicationContext()
.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isGPSEnabled)
GPSState.setText("GPS is off.Turn it on");
else
GPSState.setText("GPS is on");

if (data != null) {
Uri uri = data.getData();
Log.i("data", uri.toString());
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver()
.query(uri,
new String[] {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);

if (c != null && c.moveToFirst()) {
final ContactItems item = new ContactItems(
c.getString(0), c.getString(1), c.getInt(2));
item.setName(c.getString(0));
item.setNumber(c.getString(1));
item.setType(c.getInt(2));
selectedContactList.add(item);

Set<ContactItems> s = new TreeSet<ContactItems>(
new Comparator<ContactItems>() {

@Override
public int compare(ContactItems o1,
ContactItems o2) {
// for preventing duplicacy of contacts
// and calling toast
if (o1.number.equals(o2.number)) {

Toast.makeText(
getApplicationContext(),
"Selected Number Already Exists",
Toast.LENGTH_SHORT).show();
} else {


}
return o1.getNumber().compareTo(
o2.getNumber());

}
});

s.addAll(selectedContactList);
selectedContactList.clear();
selectedContactList.addAll(s);
adapter.notifyDataSetChanged();
// save the task list to preference

dbHelper.insertContact(item);
}
} finally {
if (c != null) {
c.close();
}
}
}
}

}

@Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub

}

@Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub

}

/*
* @Override public void onSaveInstanceState(Bundle outState) {
* super.onSaveInstanceState(outState); // You put the content of your list,
* which is this.mCachedData, in the // state
* outState.putParcelableArrayList("ABC", selectedContactList); }
*/
@Override
public void onResume() {
super.onResume();
boolean isGPSEnabled = false;
GPSState = (Button) findViewById(R.id.bGPSstate);
LocationManager locationManager;
locationManager = (LocationManager) getApplicationContext()
.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isGPSEnabled)
GPSState.setText("GPS is off.Turn it on");
else
GPSState.setText("GPS is on");
}

}// final parentheses

MySQLiteHelper.java

public class MySQLiteHelper extends SQLiteOpenHelper {

public static final String TABLE_NAME = "userdetails";
public static final String TABLE_NAME_MSG = "usermessage";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NUMBER = "NUMBER";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_TYPE = "type";
public static final String COLUMN_ID_MSG = "_id";
public static final String COLUMN_MSG = "message";
private static final String DATABASE_NAME = "userInformation.db";

private static final int DATABASE_VERSION = 1;
private static final String LOG = "DatabaseHelper";

// Database creation sql statement
private static final String DATABASE_CREATE_TABLE_CONTACTS = "create table "
+ TABLE_NAME + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_NAME
+ " text not null,"+COLUMN_NUMBER+" text not null,"+COLUMN_TYPE+" text not null);";
private static final String DATABASE_CREATE_TABLE_MSG = "create table "
+ TABLE_NAME_MSG + "(" + COLUMN_ID_MSG
+ " integer primary key autoincrement, " + COLUMN_MSG + " text not null);";
private static final String DATABASE_INSERT_MSG = "insert into "
+ TABLE_NAME_MSG + "(" + COLUMN_MSG+") VALUES('enter your message');";


public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE_TABLE_CONTACTS);
database.execSQL(DATABASE_CREATE_TABLE_MSG);
database.execSQL(DATABASE_INSERT_MSG);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}

public long insertContact(ContactItems contItem) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(COLUMN_NAME, contItem.getName());
values.put(COLUMN_NUMBER, contItem.getNumber());
values.put(COLUMN_TYPE, contItem.getType());

// insert row
long result = db.insert(TABLE_NAME, null, values);

// assigning tags to todo
/*for (long tag_id : tag_ids) {
createTodoTag(todo_id, tag_id);
}*/

return result;
}


public ArrayList<ContactItems> getAllContacts() {
ArrayList<ContactItems> contactList = new ArrayList<ContactItems>();
String selectQuery = "SELECT * FROM " + TABLE_NAME;

Log.e(LOG, selectQuery);

SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);

// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
ContactItems conItems = new ContactItems();
conItems.setName(c.getString((c.getColumnIndex(COLUMN_NAME))));
conItems.setNumber((c.getString(c.getColumnIndex(COLUMN_NUMBER))));
conItems.setType(Integer.parseInt(c.getString(c.getColumnIndex(COLUMN_TYPE))));

// adding to todo list
contactList.add(conItems);
} while (c.moveToNext());
}

return contactList;
}

public void updateMsg(String msg) {
// TODO Auto-generated method stub
// String selectQuery = "update " + TABLE_NAME_MSG+" set "+COLUMN_MSG+" = '"+msg+"' where "+COLUMN_ID_MSG+" = 1";
ContentValues values = new ContentValues();
values.put(COLUMN_MSG, msg);
SQLiteDatabase db = this.getReadableDatabase();
db.update(TABLE_NAME_MSG, values, null, null);

}
public String getMsg() {
String message ="";
String selectQuery = "SELECT * FROM " + TABLE_NAME_MSG;

SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()) {
do {
message = c.getString(c.getColumnIndex(COLUMN_MSG));
} while (c.moveToNext());
}

// TODO Auto-generated method stub
Log.e(LOG, "message = "+message);
return message;

}

public int removeData(String number) {
// TODO Auto-generated method stub

SQLiteDatabase db = this.getReadableDatabase();
//db.drawQuery(deleteQuery, null);
return db.delete(TABLE_NAME, COLUMN_NUMBER + "='" + number+"'", null) ;

}

}

自定义适配器.java

public class CustomAdapter extends BaseAdapter {

/*********** Declare Used Variables *********/
private Activity activity;
private ArrayList<ContactItems> data;
private static LayoutInflater inflater = null;
public Resources res;

MySQLiteHelper dbHelper;
// ListModel tempValues=null;
int i = 0;
String selectedNum = " ";
Context contxt;

/************* CustomAdapter Constructor *****************/
public CustomAdapter(Activity a, ArrayList<ContactItems> d,
Resources resLocal,Context context) {

/********** Take passed values **********/
activity = a;
data = d;
res = resLocal;
contxt= context;
dbHelper= new MySQLiteHelper(contxt);

/*********** Layout inflator to call external xml layout () ***********/
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}

/******** What is the size of Passed Arraylist Size ************/
public int getCount() {

if (data.size() <= 0)
return 1;
return data.size();
}

public Object getItem(int position) {
return position;
}

public long getItemId(int position) {
return position;
}

/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder {

public TextView text;
public TextView textNumber;

public ImageView image;

}

/****** Depends upon data size called for each row , Create each ListView row *****/
@SuppressLint("DefaultLocale")
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
View vi = convertView;
ViewHolder holder;
// check if converView is null, if it is null it probably means
if (convertView == null) {

/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
vi = inflater.inflate(R.layout.contactlistitem, null);

/****** View Holder Object to contain tabitem.xml file elements ******/
// if it is not null, just reuse it from the recycler
holder = new ViewHolder();
holder.text = (TextView) vi.findViewById(R.id.contactname);
holder.textNumber = (TextView) vi.findViewById(R.id.contactnumber);
holder.image = (ImageView) vi.findViewById(R.id.deleteimage);

/************ Set holder with LayoutInflater ************/
vi.setTag(holder);
} else
holder = (ViewHolder) vi.getTag();

if (data.size() <= 0) {

holder.text.setText("Add");
holder.textNumber.setText(" ");
holder.image.setVisibility(View.GONE);

} else {
/***** Get each Model object from Arraylist ********/

/************ Set Model values in Holder elements ***********/

holder.text.setText("" + data.get(position).getName());

holder.textNumber.setText("" + data.get(position).getNumber());
holder.image.setVisibility(View.VISIBLE);
holder.image.setImageResource(res.getIdentifier("delete_button",
null, null));

holder.image.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
AlertDialog.Builder build = new AlertDialog.Builder(
activity);
build.setTitle("Delete");
build.setMessage("Are You Sure");
build.setPositiveButton("Delete",
new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub

dbHelper.removeData(data.get(pos).getNumber());
data.remove(pos);
MainActivity.adapter.notifyDataSetChanged();
dialog.dismiss();
}
});

/*
* data.remove(pos);
* MainActivity.adapter.notifyDataSetChanged();
*/
build.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
build.show();
}

});
/******** Set Item Click Listner for LayoutInflater for each row *******/

}
// return the view for a single item in the listview
return vi;
}

}

ContactItems.java

public class ContactItems implements Parcelable {
String name = "";
String number = "";
int type = 0;

public ContactItems(String name, String number, int type) {
super();
this.name = name;
this.number = number;
this.type = type;
}

public ContactItems(Parcel source) {
// TODO Auto-generated constructor stub

this.name = source.readString();
this.number = source.readString();
this.type = source.readInt();
}
public ContactItems() {
// TODO Auto-generated constructor stub

super();
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getNumber() {
return number;
}

public void setNumber(String number) {
this.number = number;
}

public int getType() {
return type;
}

public void setType(int type) {
this.type = type;
}

@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}

public static final Parcelable.Creator<ContactItems> CREATOR = new Parcelable.Creator<ContactItems>() {

@Override
public ContactItems createFromParcel(Parcel source) {
return new ContactItems(source);
}

@Override
public ContactItems[] newArray(int size) {
return new ContactItems[size];
}

};

@Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeString(name);
dest.writeString(number);
dest.writeInt(type);

}

最佳答案

只需在单击按钮时调用将消息插入或更新到数据库中的方法,在调用该方法之前,只需将 EditText 的值获取到某个变量中,并将该变量作为参数传递到数据库中.

尝试如下:

 save.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {

String str = message.getText().toString();
dbHelper.updateMsg(str);
}
});

已编辑:

public boolean updateMsg(String msg) {

ContentValues values = new ContentValues();
values.put(COLUMN_MSG, msg);
SQLiteDatabase db = this.getReadableDatabase();
return db.update(TABLE_NAME_MSG, values, COLUMN_ID_MSG +"=1"+, null)>0;

}

关于Android 无法将文本从编辑 TextView 保存到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21898769/

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