Validate Mobile number with the country code - android

I want to validate the mobile number user enters. I have two edit texts one for the code i.e. +91,0 etc and another for the phone number.
I have a question that how to stop entering the numbers in edit text if more than 10 numbers being entered by the user. Also it should get validated with code and the number.
I tried the validation with this code.
private boolean isValidMobile(String phone)
{
return android.util.Patterns.PHONE.matcher(phone).matches();
}
else if (!isValidMobile(code.getText().toString()+mobileNo.getText().toString()))
{
Toast.makeText(RegisterActivity.this,"Please enter correct Mobile No.",Toast.LENGTH_LONG).show();
}
But it dose not return true for the number. Always returns false i.e. please enter the correct number.
edit texts for number :
<EditText
android:layout_width="30dp"
android:layout_height="match_parent"
android:ems="10"
android:id="#+id/editText_code"
android:layout_marginLeft="20dp"
android:background="#android:color/transparent"
android:hint="+91"
android:textSize="14sp"
android:phoneNumber="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="40dp"
android:hint="MOBILE NO"
android:singleLine="false"
android:layout_below="#+id/linearLayoutFirstName"
android:layout_toRightOf="#+id/linearLayoutFirstName"
android:layout_toEndOf="#+id/linearLayoutFirstName"
android:background="#android:color/transparent"
android:layout_gravity="center"
android:textSize="12sp"
android:layout_marginLeft="05dp"
android:id="#+id/mobileNo"
android:phoneNumber="true" />
</LinearLayout>
How to do this? Thank you.

Try this Example...
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<EditText
android:id="#+id/edtCountryCode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="phone"
android:hint="country_code"/>
<EditText
android:id="#+id/edtPhoneNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/edtCountryCode"
android:inputType="phone"
android:hint="phone_no"/>
<TextView
android:id="#+id/tvIsValidPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/edtPhoneNumber"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"/>
<Button
android:id="#+id/btnValidate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvIsValidPhone"
android:text="validate"/>
</RelativeLayout>
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
public class MainActivity extends AppCompatActivity {
TextView tvIsValidPhone;
EditText edtPhone;
EditText edtCountryCode;
Button btnValidate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvIsValidPhone = (TextView) findViewById(R.id.tvIsValidPhone);
edtCountryCode = (EditText) findViewById(R.id.edtCountryCode);
edtPhone = (EditText) findViewById(R.id.edtPhoneNumber);
btnValidate = (Button) findViewById(R.id.btnValidate);
btnValidate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String countryCode = edtCountryCode.getText().toString().trim();
String phoneNumber = edtPhone.getText().toString().trim();
if(countryCode.length() > 0 && phoneNumber.length() > 0){
if(isValidPhoneNumber(phoneNumber)){
boolean status = validateUsing_libphonenumber(countryCode, phoneNumber);
if(status){
tvIsValidPhone.setText("Valid Phone Number (libphonenumber)");
} else {
tvIsValidPhone.setText("Invalid Phone Number (libphonenumber)");
}
}
else {
tvIsValidPhone.setText("Invalid Phone Number (isValidPhoneNumber)");
}
} else {
Toast.makeText(getApplicationContext(), "Country Code and Phone Number is required", Toast.LENGTH_SHORT).show();
}
}
});
}
private boolean isValidPhoneNumber(CharSequence phoneNumber) {
if (!TextUtils.isEmpty(phoneNumber)) {
return Patterns.PHONE.matcher(phoneNumber).matches();
}
return false;
}
private boolean validateUsing_libphonenumber(String countryCode, String phNumber) {
PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
String isoCode = phoneNumberUtil.getRegionCodeForCountryCode(Integer.parseInt(countryCode));
Phonenumber.PhoneNumber phoneNumber = null;
try {
//phoneNumber = phoneNumberUtil.parse(phNumber, "IN"); //if you want to pass region code
phoneNumber = phoneNumberUtil.parse(phNumber, isoCode);
} catch (NumberParseException e) {
System.err.println(e);
}
boolean isValid = phoneNumberUtil.isValidNumber(phoneNumber);
if (isValid) {
String internationalFormat = phoneNumberUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);
Toast.makeText(this, "Phone Number is Valid " + internationalFormat, Toast.LENGTH_LONG).show();
return true;
} else {
Toast.makeText(this, "Phone Number is Invalid " + phoneNumber, Toast.LENGTH_LONG).show();
return false;
}
}}
Download jar file and add in libs folder from below link..
http://www.java2s.com/Code/Jar/l/Downloadlibphonenumber41jar.htm

Try to use isGlobalPhoneNumber() method of PhoneNumberUtils to detect whether a number is valid phone number or not.

Related

Spinner not showing selected or default choice

I've created a spinner that takes some user-generated strings (in my case classes - the school type) and displays them in a typical spinner way. My problem occurs when trying to select an item from the spinner. I can tap on the spinner and select the class, but the spinner never shows that I have the class selected. Before adding user-generated strings, I had a string-array xml file that worked perfectly.
I've tried adding notifyDataSetChanged() at the end of the onCreate() method, created a spinner layout with a transparent background and black text, and setting an setOnItemSelectedListener(). None of these worked, so I reverted code back to original state.
Screenshot of problem:
addAssignment.java
package com.nbdeg.unityplanner;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Spinner;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.nbdeg.unityplanner.data.Assignments;
import com.nbdeg.unityplanner.data.Classes;
import java.util.ArrayList;
public class addAssignment extends AppCompatActivity {
EditText mAssignmentName;
EditText mDueDate;
EditText mExtraInfo;
Spinner mDueClass;
SeekBar mPercentComplete;
int percentComplete = 0;
FirebaseAnalytics mFirebaseAnalytics;
DatabaseReference assignmentDb;
DatabaseReference classDb;
FirebaseUser user;
long assignmentCounter;
ArrayList<String> classList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_assignment);
// Sets title to "Create an assignment"
try {getSupportActionBar().setTitle("Create An Assignment");}
catch (NullPointerException e) {
e.printStackTrace();
}
// Getting number of assignments (serves as assignment ID in database)
Bundle extras = getIntent().getExtras();
assignmentCounter = extras.getLong("counter");
// Finds firebase database
user = FirebaseAuth.getInstance().getCurrentUser();
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
assignmentDb = FirebaseDatabase.getInstance().getReference().child("users").child(user.getUid()).child("assignments");
classDb = FirebaseDatabase.getInstance().getReference().child("users").child(user.getUid()).child("classes");
// Gets all classes
classDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
Classes mClass = userSnapshot.getValue(Classes.class);
Log.i("Info", "Class loaded: " + mClass.getClassName());
classList.add(mClass.getClassName());
}
Log.i("Info", "Classes loaded: " + classList);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("DB", "Error: " + databaseError.getMessage());
}
});
// Find view by ID calls
mAssignmentName = (EditText) findViewById(R.id.assignment_name);
mDueDate = (EditText) findViewById(R.id.due_date_edittext);
mExtraInfo = (EditText) findViewById(R.id.extra_homework_info);
mDueClass = (Spinner) findViewById(R.id.class_spinner);
mPercentComplete = (SeekBar) findViewById(R.id.percentComplete);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, classList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mDueClass.setAdapter(adapter);
// Sets DueDate EditText to open a datepicker when clicked
new EditTextDatePicker(this, R.id.due_date_edittext);
mPercentComplete.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
percentComplete = progress;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
// Adds a SAVE button to the Action Bar
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.save, menu);
return true;
}
// Gets and saves information when SAVE is clicked
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Getting information from views
String dueDate = mDueDate.getText().toString();
String assignmentName = mAssignmentName.getText().toString();
String extraInfo = mExtraInfo.getText().toString();
String dueClass = mDueClass.getItemAtPosition(mDueClass.getSelectedItemPosition()).toString();
mFirebaseAnalytics.logEvent("Assignment Created", null);
Log.i("DB", "Creating assignment named " + assignmentName);
assignmentDb.child(Long.toString(assignmentCounter)).setValue
(new Assignments(assignmentName, dueClass, dueDate, extraInfo, percentComplete));
/*
// Test to make sure info is being collected correctly.
Log.i("Class", dueClass);
Log.i("Due", dueDate);
Log.i("Name", homeworkName);
Log.i("Extra", extraInfo);
*/
// Bring user back to MainActivity
startActivity(new Intent(addAssignment.this, MainActivity.class));
return super.onOptionsItemSelected(item);
}
}
activity_add_assignment.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_add_homework"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.nbdeg.unityplanner.addAssignment">
<EditText
android:layout_width="match_parent"
android:layout_height="40dp"
android:inputType="textCapSentences"
android:ems="10"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/assignment_name"
android:hint="Assignment Name"
android:padding="5dp"
android:textSize="18sp"
android:background="#null" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#c0c0c0"
android:layout_below="#id/assignment_name"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="43dp"
android:orientation="horizontal"
android:layout_below="#id/assignment_name"
android:layout_alignParentStart="true"
android:id="#+id/linearLayout">
<Spinner
android:layout_width="0dp"
android:layout_height="match_parent"
android:id="#+id/class_spinner"
android:theme="#android:style/Theme.Holo.Light.DarkActionBar"
android:layout_weight="1"
android:background="#null"/>
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#c0c0c0"/>
<EditText
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="#+id/due_date_edittext"
android:padding="5dp"
android:focusable="false"
android:hint="Due Date"
android:textSize="16sp"
android:background="#null" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#c0c0c0"
android:layout_below="#id/linearLayout"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_below="#+id/linearLayout"
android:layout_alignParentStart="true"
android:id="#+id/percentCompleteLayout"
android:layout_marginTop="2dp"
android:layout_marginBottom="2dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Completion"
android:padding="5dp"
android:textColor="#color/black"
android:textSize="15sp"/>
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/percentComplete"
android:layout_marginBottom="1dp"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#c0c0c0"
android:layout_below="#id/percentCompleteLayout"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/extra_homework_info"
android:hint="Extra Infomation"
android:textSize="16sp"
android:layout_below="#id/percentCompleteLayout"
android:layout_alignParentStart="true"
android:layout_marginTop="2dp"
android:padding="5dp"
android:background="#null" />
</RelativeLayout>
spinner_layout.xml*
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:gravity="left"
android:padding="5dip"
android:textColor="#android:color/black"
android:background="#android:color/transparent"
/>
I'm wondering if there is a way to fix this and have the spinner display the default / user choice. If you need any more of the code, all of it can be found in the GitHub. Thanks in advance for all answers!
Solution: Try loading the classes prior to starting the activity, for example in the MainActivity. Then pass the values along through an intent.
Example:
MainActivty.java
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Launch Add Homework Activity
Intent intent = new Intent(MainActivity.this, addAssignment.class);
intent.putExtra("classListNames", classListNames);
startActivity(intent);
...
classDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
classList.clear();
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
Classes mClass = userSnapshot.getValue(Classes.class);
Log.i(TAG, "Class loaded: " + mClass.getClassName());
classList.add(mClass);
classListNames.add(mClass.getClassName());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "Error: " + databaseError.getMessage());
}
});
addAssignment.java
// Gets class list
Bundle extras = getIntent().getExtras();
classListNames = extras.getStringArrayList("classListNames");
...
mDueClass = (Spinner) findViewById(R.id.class_spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, classListNames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mDueClass.setAdapter(adapter);
Cause: After some debugging, I discovered the cause of the problem to be timing differences. The app would request the classes be sent, create the spinner, then load the classes. The difference in timing was milliseconds, but just enough to cause the problem.

Getting DATABASE MISSING when trying to create a database

I have made my simple project using SQLite database. As per my code, app should show Database Created when I click on 'create database' but it shows Database Missing. I have checked logcat but I don't get any error over there.
MainActivity
package com.maka.sujan.sqllitedatabase;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.File;
public class MainActivity extends ActionBarActivity {
SQLiteDatabase contactsDB = null;
Button createDBButton, addContactButton, deleteContactButton, getContactsButton,
deleteDBButton;
EditText nameEditText, emailEditText, contactListEditText, idEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createDBButton = (Button) findViewById(R.id.createDBButton);
addContactButton = (Button) findViewById(R.id.addContactButton);
deleteContactButton = (Button) findViewById(R.id.deleteContactButton);
getContactsButton = (Button) findViewById(R.id.getContactsButton);
deleteDBButton = (Button) findViewById(R.id.deleteDBButton);
nameEditText = (EditText) findViewById(R.id.nameEditText);
emailEditText = (EditText) findViewById(R.id.emailEditText);
contactListEditText = (EditText) findViewById(R.id.contactListEditText);
idEditText = (EditText) findViewById(R.id.idEditText);
}
public void createDatabase(View view) {
try{
// Opens a current database or creates it
// Pass the database name, designate that only this app can use it
// and a DatabaseErrorHandler in the case of database corruption
contactsDB = this.openOrCreateDatabase("MyContacts", MODE_PRIVATE, null);
// Execute an SQL statement that isn't select
contactsDB.execSQL("CREATE TABLE IF NOT EXISTS contacts " +
"(id integer primary key, name VARCHAR, email VARCHAR);");
// The database on the file system
File database = getApplicationContext().getDatabasePath("MyContacts.db");
// Check if the database exists
if (database.exists()) {
Toast.makeText(this, "Database Created", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Database Missing", Toast.LENGTH_SHORT).show();
}
}
catch(Exception e){
Log.e("CONTACTS ERROR", "Error Creating Database");
}
// Make buttons clickable since the database was created
addContactButton.setClickable(true);
deleteContactButton.setClickable(true);
getContactsButton.setClickable(true);
deleteDBButton.setClickable(true);
}
public void addContact(View view) {
// Get the contact name and email entered
String contactName = nameEditText.getText().toString();
String contactEmail = emailEditText.getText().toString();
// Execute SQL statement to insert new data
contactsDB.execSQL("INSERT INTO contacts (name, email) VALUES ('" +
contactName + "', '" + contactEmail + "');");
}
public void getContacts(View view) {
// A Cursor provides read and write access to database results
Cursor cursor = contactsDB.rawQuery("SELECT * FROM contacts", null);
// Get the index for the column name provided
int idColumn = cursor.getColumnIndex("id");
int nameColumn = cursor.getColumnIndex("name");
int emailColumn = cursor.getColumnIndex("email");
// Move to the first row of results
cursor.moveToFirst();
String contactList = "";
// Verify that we have results
if(cursor != null && (cursor.getCount() > 0)){
do{
// Get the results and store them in a String
String id = cursor.getString(idColumn);
String name = cursor.getString(nameColumn);
String email = cursor.getString(emailColumn);
contactList = contactList + id + " : " + name + " : " + email + "\n";
// Keep getting results as long as they exist
}while(cursor.moveToNext());
contactListEditText.setText(contactList);
} else {
Toast.makeText(this, "No Results to Show", Toast.LENGTH_SHORT).show();
contactListEditText.setText("");
}
}
public void deleteContact(View view) {
// Get the id to delete
String id = idEditText.getText().toString();
// Delete matching id in database
contactsDB.execSQL("DELETE FROM contacts WHERE id = " + id + ";");
}
public void deleteDatabase(View view) {
// Delete database
this.deleteDatabase("MyContacts");
}
#Override
protected void onDestroy() {
contactsDB.close();
super.onDestroy();
}
}
activity_main
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Create Database"
android:id="#+id/createDBButton"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="createDatabase"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Contact"
android:id="#+id/addContactButton"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/createDBButton"
android:layout_toEndOf="#+id/createDBButton"
android:layout_marginLeft="10dp"
android:onClick="addContact"
android:clickable="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete Contact"
android:id="#+id/deleteContactButton"
android:layout_below="#+id/createDBButton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="deleteContact"
android:clickable="false"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Contacts"
android:id="#+id/getContactsButton"
android:layout_below="#+id/createDBButton"
android:layout_toRightOf="#+id/deleteContactButton"
android:layout_toEndOf="#+id/deleteContactButton"
android:layout_marginLeft="10dp"
android:onClick="getContacts"
android:clickable="false"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/nameEditText"
android:layout_below="#+id/deleteContactButton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="Name"
android:layout_marginTop="5dp"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/emailEditText"
android:layout_below="#+id/nameEditText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="Email"
android:layout_marginTop="5dp"
android:inputType="textEmailAddress"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/idEditText"
android:layout_below="#+id/emailEditText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="ID to Delete"
android:layout_marginTop="5dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete Database"
android:id="#+id/deleteDBButton"
android:onClick="deleteDatabase"
android:layout_below="#+id/idEditText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:clickable="false" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/contactListEditText"
android:lines="8"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
put the extension in the line :
contactsDB = this.openOrCreateDatabase("MyContacts", MODE_PRIVATE, null);
to
contactsDB = this.openOrCreateDatabase("MyContacts.db", MODE_PRIVATE, null);
Your call to openOrCreateDatabase() create a database with the file name MyContacts.
Your call to getDatabasePath() searches for a file with a different name, i.e., MyContacts.db.

contacts app Manager

I want to make android Contacts app, there is no problem with my code but when I execute the code, the App crush and show a message
"Exavier unfortunately has stopped working "
--Main Activity.java
package com.example.enig.exaviser;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.File
public class MainActivity extends ActionBarActivity {
SQLiteDatabase contactsDB = null;
Button createDBButton, addContactButton, deleteContactButton, getContactsButton,
deleteDBButton;
EditText nameEditText, emailEditText, contactListEditText, idEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
createDBButton = (Button) findViewById(R.id.createDBButton);
addContactButton = (Button) findViewById(R.id.addContactButton);
deleteContactButton = (Button) findViewById(R.id.deleteContactButton);
getContactsButton = (Button) findViewById(R.id.getContactsButton);
deleteDBButton = (Button) findViewById(R.id.deleteDBButton);
nameEditText = (EditText) findViewById(R.id.nameEditText);
emailEditText = (EditText) findViewById(R.id.emailEditText);
contactListEditText = (EditText) findViewById(R.id.contactListEditText);
idEditText = (EditText) findViewById(R.id.idEditText);
}
public void createDatabase(View view) {
try{
// Opens a current database or creates it
// Pass the database name, designate that only this app can use it
// and a DatabaseErrorHandler in the case of database corruption
contactsDB = this.openOrCreateDatabase("MyContacts", MODE_PRIVATE, null);
// Execute an SQL statement that isn't select
contactsDB.execSQL("CREATE TABLE IF NOT EXISTS contacts " +
"(id integer primary key, name VARCHAR, email VARCHAR);");
// The database on the file system
File database = getApplicationContext().getDatabasePath("MyContacts.db");
// Check if the database exists
if (database.exists()) {
Toast.makeText(this, "Database Created", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Database Missing", Toast.LENGTH_SHORT).show();
}
}
catch(Exception e){
Log.e("CONTACTS ERROR", "Error Creating Database");
}
// Make buttons clickable since the database was created
addContactButton.setClickable(true);
deleteContactButton.setClickable(true);
getContactsButton.setClickable(true);
deleteDBButton.setClickable(true);
}
public void addContact(View view) {
// Get the contact name and email entered
String contactName = nameEditText.getText().toString();
String contactEmail = emailEditText.getText().toString();
// Execute SQL statement to insert new data
contactsDB.execSQL("INSERT INTO contacts (name, email) VALUES ('" +
contactName + "', '" + contactEmail + "');");
}
public void getContacts(View view) {
// A Cursor provides read and write access to database results
Cursor cursor = contactsDB.rawQuery("SELECT * FROM contacts", null);
// Get the index for the column name provided
int idColumn = cursor.getColumnIndex("id");
int nameColumn = cursor.getColumnIndex("name");
int emailColumn = cursor.getColumnIndex("email");
// Move to the first row of results
cursor.moveToFirst();
String contactList = "";
// Verify that we have results
if(cursor != null && (cursor.getCount() > 0)){
do{
// Get the results and store them in a String
String id = cursor.getString(idColumn);
String name = cursor.getString(nameColumn);
String email = cursor.getString(emailColumn);
contactList = contactList + id + " : " + name + " : " + email + "\n";
// Keep getting results as long as they exist
}while(cursor.moveToNext());
contactListEditText.setText(contactList);
} else {
Toast.makeText(this, "No Results to Show", Toast.LENGTH_SHORT).show();
contactListEditText.setText("");
}
}
public void deleteContact(View view) {
// Get the id to delete
String id = idEditText.getText().toString();
// Delete matching id in database
contactsDB.execSQL("DELETE FROM contacts WHERE id = " + id + ";");
}
public void deleteDatabase(View view) {
// Delete database
this.deleteDatabase("MyContacts");
}
#Override
protected void onDestroy() {
contactsDB.close();
super.onDestroy();
}
}
fragment_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Create Database"
android:id="#+id/createDBButton"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="createDatabase"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Contact"
android:id="#+id/addContactButton"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/createDBButton"
android:layout_toEndOf="#+id/createDBButton"
android:layout_marginLeft="10dp"
android:onClick="addContact"
android:clickable="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete Contact"
android:id="#+id/deleteContactButton"
android:layout_below="#+id/createDBButton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="deleteContact"
android:clickable="false"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Contacts"
android:id="#+id/getContactsButton"
android:layout_below="#+id/createDBButton"
android:layout_toRightOf="#+id/deleteContactButton"
android:layout_toEndOf="#+id/deleteContactButton"
android:layout_marginLeft="10dp"
android:onClick="getContacts"
android:clickable="false"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/nameEditText"
android:layout_below="#+id/deleteContactButton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="Name"
android:layout_marginTop="5dp"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/emailEditText"
android:layout_below="#+id/nameEditText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="Email"
android:layout_marginTop="5dp"
android:inputType="textEmailAddress"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/idEditText"
android:layout_below="#+id/emailEditText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="ID to Delete"
android:layout_marginTop="5dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete Database"
android:id="#+id/deleteDBButton"
android:onClick="deleteDatabase"
android:clickable="false"
android:layout_above="#+id/contactListEditText"
android:layout_alignRight="#+id/contactListEditText"
android:layout_alignEnd="#+id/contactListEditText" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/contactListEditText"
android:lines="8"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
How can I fix this problem? thanks in advance
The reason you are having this problem is because the activity is extending ActionBarActivity which requires the AppCompat theme to be applied.
All you need to do is add android:theme="#style/Theme.AppCompat.Light" to your application tag in the AndroidManifest.xml file.

how text to speech works in android

I am creating an android application using text to speech capability I used the built in text to speech
I only want to know how it has been developed and maintained in the android SDK, if any one knows a termed paper about developing text to speech in android i'll be blessed
This thread will help. Also, an abstract class for TTS Engine Implementation was introduced in API Level 14. Check this link. You can also read this information about speech synthesis to guide you on how it should be implemented.
by luck i was working in this also , take my code
package com.example.texttospeech;
import java.util.Locale;
import android.os.Bundle;
import android.app.Activity;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener, OnInitListener {
private TextToSpeech tts;
EditText editxt;
Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this , this);
editxt = (EditText) findViewById(R.id.editText1);
b1 = (Button) findViewById(R.id.read);
b1.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.read:
convert_text();
break;
default:
break;
}
}
private void convert_text() {
String speech = editxt.getText().toString();
tts.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
}
#Override
public void onInit(int status) {
if(status == TextToSpeech.SUCCESS){
int result = tts.setLanguage(Locale.getDefault());
if(result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){
Log.e("DEBUG" , "Language Not Supported");}
else{
b1.setEnabled(true);
convert_text();
}
}
else{
Log.i("DEBUG" , "MISSION FAILED");
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (tts != null){
tts.stop();
tts.shutdown();
}
}
}
mylayout activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="21sp"
android:layout_marginTop="23dp"
android:text="Text To Speech Test" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="35dp"
android:ems="10" />
<Button
android:id="#+id/read"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/editText1"
android:layout_marginLeft="46dp"
android:layout_marginTop="50dp"
android:text="Read" />
</RelativeLayout>

my application freezes after entering into the loop

I am developing a code breaking game i.e. Bulls and Cows in android. The problem is that in my main class I have applied a logic to check the numbers. This logic falls under a loop but when i run the application it freezes after entering into the loop. I'm tired of searching the answer on internet. I would be grateful to you people here if you could help out in some way. I regret if my code look lame to you as I'm a beginner in android programming.
The following is the code of my main class. :-
package com.bullsncows.bnc;
import java.util.Random;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Startingpoint extends Activity {
EditText etn1, etn2, etn3, etn4;
Button bsub;
TextView errormsg,res;
Random r = new Random();
int num = 0;
boolean guessed = false;
int count =0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
initializevar();
// making the computer select a random four digit number
while(hasDupes(num= (r.nextInt(9000) + 1000)));
// on clicking the submit button
bsub.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String n1 = etn1.getText().toString();
String n2 = etn2.getText().toString();
String n3 = etn3.getText().toString();
String n4 = etn4.getText().toString();
String cnum = num+"";
if (n1.length()==0||n2.length()==0||n3.length()==0||n4.length()==0) {
errormsg.setText("Fields cannot be left blank");
errormsg.setTextColor(Color.RED);
errormsg.setGravity(Gravity.CENTER);
} else if (n1.equals(n2) || n1.equals(n3) || n1.equals(n4)
|| n2.equals(n3) || n2.equals(n4) || n3.equals(n4)) {
errormsg.setText("Please enter distinct number");
errormsg.setTextColor(Color.RED);
errormsg.setGravity(Gravity.CENTER);
}else{
String guess = n1+n2+n3+n4;
errormsg.setText("Correct "+ cnum + " "+ guess);
errormsg.setTextColor(Color.GREEN);
errormsg.setGravity(Gravity.CENTER);
do{
int bulls = 0;
int cows = 0;
count++;
for(int i= 0;i < 4;i++){
if(guess.charAt(i) == cnum.charAt(i)){
bulls++;
}else if(cnum.contains(guess.charAt(i)+"")){
cows++;
}
else if(bulls == 4){
guessed = true;
break;
}else{
res.setText(cows+" Cows and "+bulls+" Bulls.");
res.setTextColor(Color.BLUE);
res.setGravity(Gravity.CENTER);
}
}
}while(!guessed);
errormsg.setText("You won after "+count+" guesses!");
errormsg.setTextColor(Color.MAGENTA);
errormsg.setGravity(Gravity.CENTER);
}
}
});
}
private void initializevar() {
// TODO Auto-generated method stub
etn1 = (EditText) findViewById(R.id.etnum1);
etn2 = (EditText) findViewById(R.id.etnum2);
etn3 = (EditText) findViewById(R.id.etnum3);
etn4 = (EditText) findViewById(R.id.etnum4);
bsub = (Button) findViewById(R.id.bsubmit);
errormsg = (TextView) findViewById(R.id.tverror);
res = (TextView) findViewById(R.id.tvres);
}
public static boolean hasDupes(int n){
boolean[] digs = new boolean[10];
while(n > 0){
if(digs[n%10]) return true;
digs[n%10] = true;
n/= 10;
}
return false;
}
}
The following is the XML coding for the same page :-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Please select the numbers below" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal" >
<EditText
android:id="#+id/etnum1"
android:layout_width="40dp"
android:layout_height="wrap_content"
android:inputType="number"
android:maxLength="1" />
<EditText
android:id="#+id/etnum2"
android:layout_width="40dp"
android:layout_height="wrap_content"
android:inputType="number"
android:maxLength="1" />
<EditText
android:id="#+id/etnum3"
android:layout_width="40dp"
android:layout_height="wrap_content"
android:inputType="number"
android:maxLength="1" />
<EditText
android:id="#+id/etnum4"
android:layout_width="40dp"
android:layout_height="wrap_content"
android:inputType="number"
android:maxLength="1" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView android:id="#+id/tverror"
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
<TextView android:id="#+id/tvres"
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal" >
<Button
android:id="#+id/bsubmit"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_gravity="fill_vertical"
android:text="Submit" />
</LinearLayout>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</TableLayout>
</LinearLayout>
without reading all of your code, i seems very unlikely
else if(bulls == 4)
will ever evalute to true, since you reset bulls each iteration
int bulls = 0;
and you only have four tries:
for(int i= 0;i < 4;i++)
Since
else if(bulls == 4){
guessed = true;
break;
is your only termination condition, you loop forever.
If you could narrow down your code to just the area that is causing problems that will help. But I might guess that the loop that has an error is
while(n > 0){
n/= 10;
}
n might never get to 0. Can you step through your code and work out exactly which part is failing?

Categories

Resources