Add validation so that EditText fields cannot be null - android

So I'm trying to add validation onto my btnSubmit which will check that all editText fields have some sort of data in before storing into the array. Would anyone be able to help?
if (btnSubmit == null) throw new AssertionError();
btnSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(editMod.getText().length()==0){
editMod.setError("Please fill in all fields");
}
else if(editRoom.getText().length()==0){
editRoom.setError("Please fill in all fields");
}
if (editMod.getText() != null) {
strModule = editMod.getText().toString();
}
if (editRoom.getText() != null) {
strRoomInfo = editMod.getText().toString();
}
inputData = strDay + " " + strTime + " " + strDuration + " " + strType + " " + strModule + " " + strRoomInfo;
parent.addItem(inputData);
try {
writeFile();
} catch (Exception e) {
Log.e("Writing to file Failed.", " ");
}
}
});
}

What's editMod here? EditText or TextInputLayout?
For this current code, here is the updated version:
if (btnSubmit == null) throw new AssertionError();
btnSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(editMod.getText().toString().isEmpty()){
editMod.setError("Please fill in all fields");
}
else if(editRoom.getText().toString().isEmpty()){
editRoom.setError("Please fill in all fields");
}
if (editMod.getText().toString() != null) {
strModule = editMod.getText().toString();
}
if (editRoom.getText().toString() != null) {
strRoomInfo = editMod.getText().toString();
}
inputData = strDay + " " + strTime + " " + strDuration + " " + strType + " " + strModule + " " + strRoomInfo;
parent.addItem(inputData);
try {
writeFile();
} catch (Exception e) {
Log.e("Writing to file Failed.", " ");
}
}
});
}
Update your question and add xml code plus the rest of Java Code.

Try this code:
if (TextUtils.isEmtpy(<Your EditText here>.getText().toString())) {
//Empty
}

Related

Get message from SMS content URI where message is not delivered

I am developing a system application in which I have to send a message from device programmatically and delete the message after sending.Everything working properly except below point
If the message sent successfully then I am able to find it from SMS content URI but if the message failures then I am not getting it from Content URI.I am using below code for deleting message
public void deleteTheMessage(Context context, String value) {
Uri uri = Uri.parse("content://sms");
Cursor c = context.getApplicationContext().getContentResolver().query(uri, null, null, null, null);
try {
if (c != null) {
Log.i("deleteTheMessage-->", " count : " + c.getCount());
} else {
Log.i("deleteTheMessage-->", " c null: ");
}
while (c.moveToNext()) {
try {
if (c != null && c.moveToFirst()) {
do {
String address = c.getString(2);
String id = c.getString(0);
long threadId = c.getLong(1);
Log.i("deleteTheMessage-->", " address: " + address + " body: " + "" + " threadId: " + threadId + " id: " + id);
try {
if (address.contains(value)) {
int deltedrowcount = context.getApplicationContext().getContentResolver().delete(uri, "thread_id = " + threadId, null);
if (deltedrowcount != 0) {
Log.i("deleteTheMessage-->", " SMS has Deleted successfully " + deltedrowcount);
}
Log.i("deleteTheMessage-->", " body " + address);
}
} catch (Exception e) {
Log.i("deleteTheMessage-->", "SmsWriteOpUtil Exception in deleting SMS " + e.getMessage());
}
} while (c.moveToNext());
}
} catch (Exception e) {
Log.i("deleteTheMessage-->", "c.moveToNext() Exception in deleting SMS" + e.getMessage());
}
}
} catch (Exception e) {
Log.i("deleteTheMessage-->", " try Exception in deleting SMS: " + e.getMessage());
} finally {
c.close();
}
}
I want to delete message address by 11345 Please see below screenshot.
Finally, I got the solution to delete the undelivered message using below code.
long threadId = Telephony.Threads.getOrCreateThreadId(context, phoneNumber);
LogMgr.i("deleteByThreadID-->" + " threadId : " + threadId);
int threadIdDeletedCount = context.getContentResolver().delete(Uri.parse("content://sms"), "thread_id =?", new String[]{String.valueOf(threadId)});
LogMgr.i("deleteByThreadID: --> threadIdDeletedCount " + threadIdDeletedCount);
phoneNumber this the number on which message was sent.

Definning a reference to method attribute for custom view

I want my custom view to have an attribute that can be set via XML that defines a callback for some custom behaviour that this view would support.
I know that i can tweak a simple string to be such using reflections, but it exists in the android API as Button has android:onClick so i wonder if this is something i can get out of the box instead of reinventing the wheel.
Anyone familiar with how it is done or do i must go ahead and implement it on my own using refelections?
seeing the android source code, looks as they did the same as i was going to :
case R.styleable.View_onClick:
if (context.isRestricted()) {
throw new IllegalStateException("The android:onClick attribute cannot "
+ "be used within a restricted context");
}
final String handlerName = a.getString(attr);
if (handlerName != null) {
setOnClickListener(new OnClickListener() {
private Method mHandler;
public void More ...onClick(View v) {
if (mHandler == null) {
try {
mHandler = getContext().getClass().getMethod(handlerName,
View.class);
} catch (NoSuchMethodException e) {
int id = getId();
String idText = id == NO_ID ? "" : " with id '"
+ getContext().getResources().getResourceEntryName(
id) + "'";
throw new IllegalStateException("Could not find a method " +
handlerName + "(View) in the activity "
+ getContext().getClass() + " for onClick handler"
+ " on view " + View.this.getClass() + idText, e);
}
}
try {
mHandler.invoke(getContext(), View.this);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Could not execute non "
+ "public method of the activity", e);
} catch (InvocationTargetException e) {
throw new IllegalStateException("Could not execute "
+ "method of the activity", e);
}
}
});
}
So this i guess is the only way...

Android sqlite id missing after update

after I update an object in my syncAdapter I can't get it back by id again. It seems that the id get lost after the update. What leaves behind is a null object.
Here's my source code how I update the object:
#Override
public void updateUserThread(Context ctxt, UserThread userThread, boolean notified)
{
try
{
ContentValues values = new ContentValues();
values.put(DBHandler.TOPIC, userThread.getTopic());
if(userThread.getCreationDate() != null)
values.put(DBHandler.USER_THREAD_CREATION_DATE, userThread.getCreationDate().getTime());
values.put(DBHandler.THREAD_TYPE, Helper.threadTypeToString(userThread.getThreadType()));
values.put(DBHandler.MEETING_PLACE, userThread.getMeetingPlace());
values.put(DBHandler.SUBJECT, userThread.getSubject());
values.put(DBHandler.SENT, Helper.convertBooleanToInt(userThread.isSent()));
if(userThread.getStartDate() != null)
values.put(DBHandler.START_DATE, userThread.getStartDate().getTime()); //Helper.getDateTime(
values.put(DBHandler.FOR_ALL, userThread.isForAll());
values.put(DBHandler.ID_SERVER, userThread.getIdServer());
if(userThread.getAuthor() != null)
values.put(DBHandler.ID_USER_FK, userThread.getAuthor().getIdUser());
if(notified)
{
ctxt.getContentResolver().update(TeamChannelProvider.USER_THREAD_URI, values, DBHandler.ID_USER_THREAD + "=" + "?", new String[]{String.valueOf(userThread.getIdUserThread())});
}
else
{
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
long status = db.update(TABLE_USER_THREAD, values, DBHandler.ID_USER_THREAD + "=?", new String[]{String.valueOf(userThread.getIdUserThread())});
db.setTransactionSuccessful();
db.endTransaction();
Log.i(Constants.TAG, "Status: " + status);
}
}
catch(Exception exc)
{
Log.e(Constants.TAG, "ERROR - DBHandlerTeamChannel -> updateUserThread", exc);
}
finally
{
Log.i(Constants.TAG, "UserThread updated with ID " + (notified ? "(notified) " : "not notified ") + userThread.getIdUserThread() + ", Server-ID: " + userThread.getIdServer());
}
}

Cannot delete last char of StringBuffer String

I am facing a strange(for me) problemm of not being able to delete the last char of a stringbuffer string. I am building an app in which i have many checkboxes and i want to take multiple values so thats why i used the stringbuffer to append the checkboxes names.
Code:
int length = iceCreamPreference.length();
if (length>0){
iceCreamPreference = iceCreamPreference.deleteCharAt(length - 1);
}
Toast.makeText(SweetsLayoutActivity.this,
"Quantity: " + quantityNumberFinal +
"\nIce Cream Flavors: " + iceCreamPreference.toString() +
"\nIce Scream Scoops: " + quantityIceCreamNumberFinal +
"\nSyrups: " + syrupPreference.toString(), Toast.LENGTH_LONG).show();
Where i build the StringBuffer:
private void checkWhatIceCreamSelected() {
iceCreamPreference = new StringBuffer();
if (chocolate.isChecked()){
iceCreamPreference.append(chocolate.getText().toString() + ", ");
}
if (strawberry.isChecked()){
iceCreamPreference.append(strawberry.getText().toString() + ", ");
}
if (vanilla.isChecked()){
iceCreamPreference.append(vanilla.getText().toString() + ", ");
}
if (banana.isChecked()){
iceCreamPreference.append(banana.getText().toString() + ", ");
}
if (cookies.isChecked()){
iceCreamPreference.append(cookies.getText().toString() + ", ");
}
if (pistachio.isChecked()){
iceCreamPreference.append(pistachio.getText().toString() + ", ");
}
if (cheeseCake.isChecked()){
iceCreamPreference.append(cheeseCake.getText().toString() + ", ");
}
if (oreo.isChecked()){
iceCreamPreference.append(oreo.getText().toString() + ", ");
}
if (mango.isChecked()){
iceCreamPreference.append(mango.getText().toString() + ", ");
}
if (caramel.isChecked()){
iceCreamPreference.append(caramel.getText().toString() + ", ");
}
if (pineapple.isChecked()){
iceCreamPreference.append(pineapple.getText().toString() + ", ");
}
if (sorbet.isChecked()){
iceCreamPreference.append(sorbet.getText().toString() + ", ");
}
}
The Result:
HERE
I would like to have the last "," comma removed.
Any suggestions will be highly appreciated!!!
The last char in the your StringBuffer will be a space, so you need to delete the last two characters to get rid of the final comma.
You can use the comma before the name and put a logic so that it doesn't append comma before first data entry. So code will be
Declare a boolean variable
boolean comma=false;
Then do code like following
private void checkWhatIceCreamSelected() {
iceCreamPreference = new StringBuffer();
if (chocolate.isChecked()){
if(comma!=false)
{
iceCreamPreference.append( ", ");
}
iceCreamPreference.append(chocolate.getText().toString());
comma=true;
}
//do same for all other if
}

CookieManager not sending cookie after first and second request

Currently working on an Android app with CookieManager..
I am trying to do PUT requests using a for loop but for some odd reason, only the first two requests succeed. I asked the server guy for help and he indicated that the other PUT requests fail because they do not have a cookie attached.
This is the for loop that I'm using.
for(int i = 0; i < userList.size(); i++) {
User user = userList.get(i);
String url = apiURL;
String address = user.getEmail() == null ? "nil":user.getEmail();
String jsonString = "{build:\"" + String.valueOf(BuildConfig.VERSION_CODE) + "\",device_id:\"" + ((MainActivity)activity).tmDevice + "\",platform:\"android\",\n" +
" type:\"User\",\n" +
" id:\"" + String.valueOf(user.getId()) + "\",\n" +
" first_name:\"" + user.getFirstName() + "\",\n" +
" last_name:\"" + user.getLastName() + "\",\n" +
" name:\"" + user.getName() + "\",\n" +
" image:{\n" +
" type:\"UserPhoto\",\n" +
" id:\"1a035500-012f-1cc2-9d22-96a73beda35e\"\n" +
" },\n" +
" emails:[\n" +
" {\n" +
" type:\"Email\",\n" +
" address:" + address + "\n" +
" }\n" +
" ],\n" +
" phone_numbers:[]\n" +
" }";
JSONObject js = null;
try {
js = new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
final JSONObject finalJs = js;
JsonObjectRequest jsObjRequest = new JsonObjectRequest(
Request.Method.PUT,url, finalJs,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i("putresponse", String.valueOf(response));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("puterror", String.valueOf(error));
}
});
VolleySingleton.getInstance((MainActivity) activity).addToRequestQueue(jsObjRequest);
}
This is the code for setting CookieManager.
manager = new CookieManager();
CookieHandler.setDefault(manager);
Even the GET requests right before the PUT requests work fine..
Any help?
After 3 days of seaching and reading about CookieManager
I finally find and make a perfect solution :
static CookieManager myCookies = new CookieManager(null, CookiePolicy.ACCEPT_ALL);;
final public static void saveCookies(HttpURLConnection connection , Context context) {
Map<String, List<String>> headerFields = connection.getHeaderFields();
List<String> cookiesHeader = null;
try {
cookiesHeader = headerFields.get("Set-Cookie");
} catch (Exception e) {
e.printStackTrace();
}
if (cookiesHeader != null && myCookies != null) {
for (String cookie : cookiesHeader) {
try {
cookie = cookie.replace("\"", "");
myCookies.getCookieStore().add(connection.getURL().toURI(), HttpCookie.parse(cookie).get(0));
String new_cookie = TextUtils.join(";", myCookies.getCookieStore().getCookies());
PreferenceManager.getDefaultSharedPreferences(context).edit().putString("cookie", new_cookie).commit();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
final public static void loadCookies(HttpURLConnection connection , Context context) {
if (myCookies != null && myCookies.getCookieStore().getCookies().size() > 0) {
connection.setRequestProperty("Cookie", TextUtils.join(";", myCookies.getCookieStore().getCookies()));
}
else {
String new_cookie = PreferenceManager.getDefaultSharedPreferences(context).getString("cookie" , "");
connection.setRequestProperty("Cookie", new_cookie );
}
}

Categories

Resources