- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在我的应用程序中,我允许用户向某些号码发送警报消息
。用户可以在 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/
我通过 spring ioc 编写了一些 Rest 应用程序。但我无法解决这个问题。这是我的异常(exception): org.springframework.beans.factory.BeanC
我对 TestNG、Spring 框架等完全陌生,我正在尝试使用注释 @Value通过 @Configuration 访问配置文件注释。 我在这里想要实现的目标是让控制台从配置文件中写出“hi”,通过
为此工作了几个小时。我完全被难住了。 这是 CS113 的实验室。 如果用户在程序(二进制计算器)结束时选择继续,我们需要使用 goto 语句来到达程序的顶部。 但是,我们还需要释放所有分配的内存。
我正在尝试使用 ffmpeg 库构建一个小的 C 程序。但是我什至无法使用 avformat_open_input() 打开音频文件设置检查错误代码的函数后,我得到以下输出: Error code:
使用 Spring Initializer 创建一个简单的 Spring boot。我只在可用选项下选择 DevTools。 创建项目后,无需对其进行任何更改,即可正常运行程序。 现在,当我尝试在项目
所以我只是在 Mac OS X 中通过 brew 安装了 qt。但是它无法链接它。当我尝试运行 brew link qt 或 brew link --overwrite qt 我得到以下信息: ton
我在提交和 pull 时遇到了问题:在提交的 IDE 中,我看到: warning not all local changes may be shown due to an error: unable
我跑 man gcc | grep "-L" 我明白了 Usage: grep [OPTION]... PATTERN [FILE]... Try `grep --help' for more inf
我有一段代码,旨在接收任何 URL 并将其从网络上撕下来。到目前为止,它运行良好,直到有人给了它这个 URL: http://www.aspensurgical.com/static/images/a
在过去的 5 个小时里,我一直在尝试在我的服务器上设置 WireGuard,但在完成所有设置后,我无法 ping IP 或解析域。 下面是服务器配置 [Interface] Address = 10.
我正在尝试在 GitLab 中 fork 我的一个私有(private)项目,但是当我按下 fork 按钮时,我会收到以下信息: No available namespaces to fork the
我这里遇到了一些问题。我是 node.js 和 Rest API 的新手,但我正在尝试自学。我制作了 REST API,使用 MongoDB 与我的数据库进行通信,我使用 Postman 来测试我的路
下面的代码在控制台中给出以下消息: Uncaught DOMException: Failed to execute 'appendChild' on 'Node': The new child el
我正在尝试调用一个新端点来显示数据,我意识到在上一组有效的数据中,它在数据周围用一对额外的“[]”括号进行控制台,我认为这就是问题是,而新端点不会以我使用数据的方式产生它! 这是 NgFor 失败的原
我正在尝试将我的 Symfony2 应用程序部署到我的 Azure Web 应用程序,但遇到了一些麻烦。 推送到远程时,我在终端中收到以下消息 remote: Updating branch 'mas
Minikube已启动并正在运行,没有任何错误,但是我无法 curl IP。我在这里遵循:https://docs.traefik.io/user-guide/kubernetes/,似乎没有提到关闭
每当我尝试docker组成任何项目时,都会出现以下错误。 我尝试过有和没有sudo 我在这台机器上只有这个问题。我可以在Mac和Amazon WorkSpace上运行相同的容器。 (myslabs)
我正在尝试 pip install stanza 并收到此消息: ERROR: No matching distribution found for torch>=1.3.0 (from stanza
DNS 解析看起来不错,但我无法 ping 我的服务。可能是什么原因? 来自集群中的另一个 Pod: $ ping backend PING backend.default.svc.cluster.l
我正在使用Hibernate 4 + Spring MVC 4当我开始 Apache Tomcat Server 8我收到此错误: Error creating bean with name 'wel
我是一名优秀的程序员,十分优秀!