App crashes when trying to load image from SQLite Database - android

In my app I have a few EditText's that users can fill in and hit save and it will save those details. I also have a button that opens up a blank canvas for the user to sign on (digital signature). Then when the user selects save the image is displayed in an ImageView, and then finally the user can tap on save again to save the form with the image. All of this works, but as soon as the user selects save to save the form the app crashes with the following error:
java.lang.NumberFormatException: Invalid int: "android.widget.ImageView$ImageViewBitmapDrawable#efa14f0"
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parse(Integer.java:410)
at java.lang.Integer.parseInt(Integer.java:367)
at java.lang.Integer.parseInt(Integer.java:334)
at com.pta.sign.form.CreateFormActivity.persistPerson(CreateFormActivity.java:413)
at com.pta.sign.form.CreateFormActivity.onClick(CreateFormActivity.java:245)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10814)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Here is the code I use:
FormDBHelper.class
public static final String USER_SIGNATURE = "signature";
....
USER_SIGNATURE + " BLOB, " +
....
public boolean insertPerson(String customername,
......
byte customersign, int
jobnumber) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NAME_CUSTOMER, customername);
....
contentValues.put(USER_SIGNATURE, customersign);
contentValues.put(USER_JOB_NUMBER, jobnumber);
db.insert(PERSON_TABLE_NAME, null, contentValues);
return true;
}
public boolean updatePerson(Integer id,
String customername,
....
byte customersign,
int jobnumber) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NAME_CUSTOMER, customername);
....
contentValues.put(USER_SIGNATURE, customersign);
contentValues.put(PERSON_JOB_NUMBER, jobnumber);
db.update(PERSON_TABLE_NAME, contentValues, PERSON_COLUMN_ID + " = ? ", new String[]{Integer.toString(id)});
return true;
}
Then in my CreateFormActivity.class
private FormDBHelper dbHelper;
EditText nameCustomer;
....
ImageView signatureImage;
Button saveButton;
LinearLayout buttonLayout;
Button editButton, deleteButton;
int personID;
.....
nameCustomer = (EditText) findViewById(R.id.editCustName);
....
signatureImage = (ImageView) findViewById(R.id.custimagesig);
....
dbHelper = new FormDBHelper(this);
if (personID > 0) {
saveButton.setVisibility(View.GONE);
buttonLayout.setVisibility(View.VISIBLE);
rs = dbHelper.getPerson(personID);
rs.moveToFirst();
String customerName = rs.getString(rs.getColumnIndex(FormDBHelper.NAME_CUSTOMER));
....
byte[] custsign = rs.getBlob(rs.getColumnIndex(FormDBHelper.USER_SIGNATURE));
int personAge = rs.getInt(rs.getColumnIndex(FormDBHelper.PERSON_JOB_NUMBER));
if (!rs.isClosed()) {
rs.close();
}
nameCustomer.setText(customerName);
nameCustomer.setFocusable(false);
nameCustomer.setClickable(false);
....
signatureImage.setImageBitmap(bitmap);
signatureImage.setFocusable(false);
signatureImage.setClickable(false);
.....
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.saveButton:
persistPerson(); **This is where is crashes (245)**
return;
case R.id.editButton:
saveButton.setVisibility(View.VISIBLE);
buttonLayout.setVisibility(View.GONE);
nameCustomer.setEnabled(true);
nameCustomer.setFocusableInTouchMode(true);
nameCustomer.setClickable(true);
....
signatureImage.setEnabled(false);
signatureImage.setFocusableInTouchMode(true);
signatureImage.setClickable(false);
......
public void persistPerson() {
if (personID > 0) {
if (dbHelper.updatePerson(
personID,
nameCustomer.getText().toString(),
....
(byte) Integer.parseInt(signImage.getDrawable().toString()),
....
Integer.parseInt(jobEditText.getText().toString()))) {
Toast.makeText(getApplicationContext(), "Form Update Successful", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), FragmentJob.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Form Update Failed", Toast.LENGTH_SHORT).show();
}
} else {
if (dbHelper.insertPerson(
nameCustomer.getText().toString(),
....
(byte) Integer.parseInt(signImage.getDrawable().toString()), **this is where it crashes (413)**
Integer.parseInt(jobEditText.getText().toString()))) {
Toast.makeText(getApplicationContext(), "Form Inserted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Could not Insert Form", Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(), FragmentFormJob.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
This is my code (in the same class) where the user taps on the button to create their signature:
Button.OnClickListener onButtonClick = new Button.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(CreateFormActivity.this, CaptureUserSig.class);
startActivityForResult(i, 0);
}
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (resultCode == 1) {
Bitmap b = BitmapFactory.decodeByteArray(
data.getByteArrayExtra("byteArray"), 0,
data.getByteArrayExtra("byteArray").length);
signatureImage.setImageBitmap(Bitmap.createScaledBitmap(b, 512, 512, false));
}
}
}
AFAIK this should work, unless I have made a mistake somewhere along the line. But for the life of me I can't seem to figure it out.

Related

Android - App is crashing when trying to save image

I am new to Android and I hope I can find a solution here.
On my activity I can take a picture and select it from the gallery. After I press the save button the app should save the image in the database. But all i get is the following error:
08-17 22:52:41.326 2683-2697/android.process.media E/DatabaseUtils: Writing exception to parcel
java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/35 from pid=4424, uid=10060 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
at android.content.ContentProvider.enforceReadPermissionInner(ContentProvider.java:605)
at android.content.ContentProvider$Transport.enforceReadPermission(ContentProvider.java:480)
at android.content.ContentProvider$Transport.enforceFilePermission(ContentProvider.java:471)
at android.content.ContentProvider$Transport.openTypedAssetFile(ContentProvider.java:416)
at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:313)
at android.os.Binder.execTransact(Binder.java:453)
08-17 22:42:31.929 4290-4290/com.group6.travlhoe E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.group6.travlhoe, PID: 4290
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.drawable.BitmapDrawable.getBitmap()' on a null object reference
at com.group6.TakeOff.activity_unterkunft.imageViewToByte(activity_unterkunft.java:187)
at com.group6.TakeOff.activity_unterkunft$3.onClick(activity_unterkunft.java:205)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
My Java code:
public class activity_unterkunft extends AppCompatActivity {
DatabaseHelper myDb;
Button btn_save;
Spinner ChooseProject;
EditText Entfernung,Price,MWST;
String selectedspinner;
ImageView imageView6;
private static int PICK_IMAGE = 100;
Uri imageUri;
private BottomNavigationViewEx bottomNavigationViewEx;
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_unterkunft);
myDb = new DatabaseHelper(this);
ChooseProject = (Spinner) findViewById(R.id.ChooseProject);
Entfernung = (EditText) findViewById(R.id.Entfernung);
Price = (EditText) findViewById(R.id.Preis);
MWST = (EditText) findViewById(R.id.MwSt);
btn_save=(Button) findViewById(R.id.btn_save);
ImageButton btnCamera= (ImageButton)findViewById(R.id.btnCamera);
imageView6=(ImageView) findViewById(R.id.imageView6);
loadSpinnerData();
SaveData();
//CameraInitialisierung
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
builder.detectFileUriExposure();
//++++++++++++BOTTOM NAVIGATION BAR++++++++++++//
bottomNavigationViewEx = (BottomNavigationViewEx) findViewById(R.id.bottomNavigationView);
bottomNavigationViewEx.setOnNavigationItemSelectedListener(new BottomNavigationViewEx.OnNavigationItemSelectedListener(){
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item){
if (item.getItemId()==R.id.menu_start){
startActivity(new Intent(activity_unterkunft.this, MainActivity.class));
} else if(item.getItemId()==R.id.menu_allgemein){
startActivity(new Intent(activity_unterkunft.this, activity_allgemein.class));
} else if(item.getItemId()==R.id.menu_transport){
startActivity(new Intent(activity_unterkunft.this, activity_transport.class));
} else if(item.getItemId()==R.id.menu_rechnung){
startActivity(new Intent(activity_unterkunft.this, activity_rechnung.class));
} else if(item.getItemId()==R.id.menu_unterkunft){
startActivity(new Intent(activity_unterkunft.this, activity_unterkunft.class));
}
return true;
}
});
bottomNavigationViewEx.setSelectedItemId(R.id.menu_unterkunft);
BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx);
}
public void onButtonClicked(View v){
if(v.getId()==R.id.btnCamera) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureName= getPictureName();
File imageFile= new File(pictureDirectory,pictureName);
//URI weil putExtra sonst nicht mit File elementen klar kommt!
Uri pictureUri = Uri.fromFile(imageFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
startActivityForResult(intent, 0);
}
if(v.getId()==R.id.goToGPS) {
//Intent intent2 = new Intent(activity_unterkunft.this, function_gps.class );
Intent intent2 = new Intent(activity_unterkunft.this, MapsActivity.class );
startActivity(intent2);
}
if(v.getId()==R.id.btnGallery){
openGallery();
}
}
private void openGallery() {
Intent Gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Gallery, PICK_IMAGE);
}
private String getPictureName() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String timestamp = sdf.format(new Date());
return "Rechnung"+ timestamp + ".jpg";
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK && requestCode==PICK_IMAGE){
imageUri= data.getData();
imageView6.setImageURI(imageUri);
}
// Bitmap bitmap = (Bitmap)data.getExtras().get("data");
//imageView.setImageBitmap(bitmap);
}
/**
* Function to load the spinner data from SQLite database
* */
private void loadSpinnerData() {
// database handler
DatabaseHelper db = new DatabaseHelper (getApplicationContext());
// Spinner Drop down elements
List<String> projects = db.getAllProjects();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, projects);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ChooseProject.setPrompt("Projekt auswählen");
// attaching data adapter to spinner
ChooseProject.setAdapter(dataAdapter);
//Listener für den Spinner damit ich den Wert abspeichern kann
ChooseProject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
//selectedspinner =String.ValueOf(parent.getItemAtPosition(pos));
selectedspinner = (String) ChooseProject.getSelectedItem();
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public static byte[] imageViewToByte(ImageView image) {
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
return byteArray;
}
//++++++++++++Save Data++++++//
public void SaveData(){
btn_save.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDb.createUnterkunft(
selectedspinner,
Integer.valueOf(Price.getText().toString()),
Integer.valueOf(MWST.getText().toString()),
Integer.valueOf(Entfernung.getText().toString()),
imageViewToByte(imageView6)
);
if(isInserted=true)
Toast.makeText(activity_unterkunft.this, "Daten gespeichert", Toast.LENGTH_LONG).show();
else
Toast.makeText(activity_unterkunft.this, "Daten nicht gespeichert", Toast.LENGTH_LONG).show();
}
}
);
}
}
The corresponding method in my DB-Helper:
//+++++++++++++CREATE A UNTERKUNFT++++++++++++//
public boolean createUnterkunft(String project, int price, int steuer, int entfernung, byte [] image){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_PROJECT, project);
contentValues.put(KEY_PRICE, price);
contentValues.put(KEY_MWST, steuer);
contentValues.put(KEY_ENTFERNUNG, entfernung);
contentValues.put(KEY_RECHNUNG_IMG, image);
long result = db.insert(TABLE_UNTERKUNFT,null,contentValues);
if(result == -1)
return false;
else
return true;
}
I hope that someone can help me with this problem.
Runtime permission has been introduced since Android 6.0. Make sure that you have already requested for READ_EXTERNAL_STORAGE permission otherwise you will not be able to access file in the external storage. More information: https://developer.android.com/training/permissions/requesting.html

why the captured image keep on changing?

I'm trying to pass captured image and valuefrom C to B, finally to listView A. When the list in Activity A is clicked, it will display the passed image on imageView and values on editText B . But the problem now is the image displayed on Activity B is not from row I have clicked on listview A.
Activity A
ArrayAdapter<String> adapter;
ArrayList<String> m_listItems = new ArrayList<String>();
int mClickedPosition;
adapter=new ArrayAdapter<String (getActivity(),R.layout.claims,R.id.textView1,m_listItems);
listV = (ListView) claims.findViewById(R.id.listView1);
listV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> listView, View view,int position, long id)
{
mClickedPosition = position;
String temp[] = m_listItems.get(position).split("\\s\\s+");
result = temp[temp.length - 1].trim();
result = result.replace("RM", "");
name = temp[1].trim();
Log.e("TAG", result + "");
if (name.equals("Project"))
{
Intent intent = new Intent(Claims1.this.getActivity(), Project1.class);
intent.putExtra("bitmap", true);
intent.putExtra("name", name);
intent.putExtra("result", result);
startActivityForResult(intent, 0);
Log.e("RESULT", "Result= " + result);
}
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 0: // for Project
result = data.getStringExtra("text"); //get from B
name = data.getStringExtra("a");
description = data.getStringExtra("c");
Log.d("FIRST", "result:" + result);
Text = " " + name + " " + "RM" + result + "";
if (mClickedPosition == -1)
{ // if is icon button clicked
m_listItems.add(Text);
}
else
{
m_listItems.set(mClickedPosition, Text);
}
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
}
}
Activity B
if(getIntent().getExtras()!=null) { //if has value pass from A
final String Amount = getIntent().getExtras().getString("result");
final String description1 = getIntent().getExtras().getString("description");
txt1.setText(description1);
txt.setText(Amount);
}
b.setOnClickListener(new View.OnClickListener() { // return to A
public void onClick(View arg0) {
Intent returnIntent = new Intent();
a = "Project";
text = txt.getText().toString(); // amount
returnIntent.putExtra("text", text);
returnIntent.putExtra("a", a);
returnIntent.putExtra("c", c); // receive from Activity C
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
viewImage.setImageBitmap(Global.img); // image receive from C
}
public void onActivityResult(int requestCode,int resultCode, Intent data)
{ //receive from C
if(requestCode==PROJECT_REQUEST_CODE) {
if(data!=null&&data.hasExtra("text")) {
c = data.getStringExtra("text");
txt1.setText(c);
viewImage.setImageBitmap(Global.img); //display image
}
}
else if (requestCode==CAMERA_REQUEST_CODE)
{
}
}
Activity C
ImageView b;
ok.setOnClickListener(new View.OnClickListener()
{ // return image to B
public void onClick(View arg0)
{
Intent returnIntent=new Intent();
text=t.getText().toString();
b.setDrawingCacheEnabled(true);
b.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
b.layout(0, 0, b.getMeasuredWidth(), b.getMeasuredHeight());
b.buildDrawingCache(true);
returnIntent.putExtra("text", text);
if (b.getDrawingCache() != null) {
Bitmap bitmap = Bitmap.createBitmap(b.getDrawingCache());
if (bitmap == null) {
Log.e("TAG", "getDrawingCache() == null");
}
Global.img = bitmap;
}
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
Add image into database
When ok button in Activity A is clicked, I want save all the image todatabase.
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
byte[] data=getBitmapAsByteArray(getActivity(),Global.img);// this is a function
SB.insertStaffBenefit(data);
}
}
}
public static byte[] getBitmapAsByteArray(final Context context,Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, outputStream);
Toast.makeText(context, outputStream.size()/1024+"KB", Toast.LENGTH_LONG).show();
return outputStream.toByteArray();
}
1: ListView in A. Values were get fom C and B.
2: Activity B. Assume the list is clicked and intent to B. Noted that the value and image are from Activity C and B.
3: New value and images added and return to A
4: Two list in Activity A now
5: When first list clicked, image changed
You may add bitmap array list (in your Activity A):
ArrayList<Bitmap> m_listBitmapItems = new ArrayList<Bitmap>();
in onItemClick of your listV:
Global.img = m_listBitmapItems.get(position);
in onActivityResult():
if (mClickedPosition == -1)
{ // if is icon button clicked
m_listItems.add(Text);
m_listBitmapItems.add(Global.img);
}
else
{
m_listItems.set(mClickedPosition, Text);
m_listBitmapItems.set(mClickedPosition, Global.img);
}

Send SMS to multi users

In my application,i have created an edit-text view and three buttons. When user clicks on "Add More Contacts" button, it will add another edit-text view and when user clicks "Add Contact" this will take him to contacts of phone-book from where he can choose the contacts to which he wants to send the SMS. I have written program for all this but i don't know how to send message to all users automatically without the user confirmation when he just pressed the "Send Message"Button. I tried SMSManager but its depreciated.Please suggest me.
public class MainActivity extends Activity {
private Button btn_cntct;
public int REQUESTCODE = 1;
private LinearLayout layoutLinear;
private Button btn_addmore_cntct;
private int id = 1;
Button b_alert;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 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) {
// 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);
}
});
// defining button and edit-text values for adding mutli edit-texts
// views
layoutLinear = (LinearLayout) findViewById(R.id.mLayout);
btn_addmore_cntct = (Button) findViewById(R.id.baddmorecontacts);
btn_addmore_cntct.setOnClickListener(OnClick());
EditText editview = new EditText(this);
editview.setText("Add more");
}
// implementing OnClickListener OnClick() method for "btn_addmore_cntct"
// button
private OnClickListener OnClick() {
// TODO Auto-generated method stub
// changing return type "null" to "new OnClickListner"
return new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final EditText tab = new EditText(getApplicationContext());
tab.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
// setting id for edit-text views
tab.setId(id);
// and increment
id++;
// adding (0) to display edit-text view on the top
layoutLinear.addView(tab, 0);
tab.requestFocus();
// for sending sms
b_alert = (Button) findViewById(R.id.balert);
b_alert.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String smsNumber = tab.getText().toString();
String smsText = "I am in danger";
Uri uri = Uri.parse("smsto:" + smsNumber);
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.putExtra("sms_body", smsText);
startActivity(intent);
}
});
}
};
}
#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);
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()) {
String name = c.getString(0);
String number = c.getString(1);
int type = c.getInt(2);
showSelectedNumber(name, number, type);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
// defining showSelectedNummber to display selected contact from phone-book
// to Edit-Text View
public void showSelectedNumber(String name, String number, int type) {
if (layoutLinear == null) {
Log.i("layoutLinear is null", "null");
} else {
Log.i("layoutLinear is not null", "not null");
}
EditText userNumber = (EditText) layoutLinear.getChildAt(0);
if (userNumber == null) {
Log.i("edittext is null", "null");
} else {
Log.i("edittext is not null", "not null");
}
String typeNumber = (String) ContactsContract.CommonDataKinds.Phone
.getTypeLabel(getResources(), type, "");
userNumber.setText(name + ": " + number + " " + typeNumber);
}
}
You this with loop of Numbers you need to send
SmsManager.getDefault().sendTextMessage("NUMBER",
null, "TEXT_TO_SEND", null, null);

Control back button functionality

From the given ListView in picture, I select the contact to send sms and move to another activity (second picture). And from this sms Activity picture. When I press back hardware button available on phone, I should move where I want. I don't want a default Activity to be displayed. How can I do this?
public class SendSms extends Activity{
ListView listView;
List<RowItems> rowItems;
CustomListViewAdapter adapter;
String toNumbers = "";
String separator;
int i=0,j,count=0,count1; String a[]=new String[5];
String number,val2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new4);
listView = (ListView) findViewById(R.id.list);
rowItems = new ArrayList<RowItems>();
val2=getIntent().getStringExtra("name");
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String rawContactId = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
Cursor c = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] {
ContactsContract.CommonDataKinds.Phone.NUMBER,
// ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.PHOTO_ID
}, ContactsContract.Data.RAW_CONTACT_ID + "=?", new String[] { rawContactId }, null);
if (c != null) {
if (c.moveToFirst()) {
String number = c.getString(0);
//int type = c.getInt(1);
String name = c.getString(1);
int photoId = c.getInt(2);
Bitmap bitmap = queryContactImage(photoId);
RowItems p=new RowItems(bitmap, number, name);
rowItems.add(p);
}
adapter = new CustomListViewAdapter(this,
R.layout.new5, rowItems);
listView.setAdapter(adapter);
c.close();
}
}
}
}
private Bitmap queryContactImage(int imageDataRow) {
Cursor c = getContentResolver().query(ContactsContract.Data.CONTENT_URI, new String[] {
ContactsContract.CommonDataKinds.Photo.PHOTO
}, ContactsContract.Data._ID + "=?", new String[] {
Integer.toString(imageDataRow)
}, null);
byte[] imageBytes = null;
if (c != null) {
if (c.moveToFirst()) {
imageBytes = c.getBlob(0);
}
c.close();
}
if (imageBytes != null) {
return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
} else {
return null;
}
}
public void showResult(View v) {
// String result = "";
String result1="";
for (RowItems p : adapter.getBox()) {
if (p.chck){
// result += "\n" + p.getTitle();
result1 +="\n" +p.getDesc();
a[i]=p.getTitle();
i++;
count++;
}
count1=count;
}
Toast.makeText(this, result1+"\n", Toast.LENGTH_LONG).show();
}
public void send(View v) throws IOException {
int value=a.length-count1;
for(j=0;j<a.length-value;j++){
if(android.os.Build.MANUFACTURER.equalsIgnoreCase("Samsung")){
separator = ",";
} else
separator = ";";
number = a[j];
toNumbers= toNumbers +number +separator;
}
toNumbers = toNumbers.substring(0, toNumbers.length());
Uri sendSmsTo = Uri.parse("smsto:" + toNumbers);
String smsValue = "help iam in danger..i am presently at \n"+val2;
if(val2==null){
Toast.makeText(SendSms.this, "wait.....", Toast.LENGTH_LONG).show();
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("vnd.android-dir/mms-sms");
intent.putExtra("sms_body", smsValue);
intent.setData(sendSmsTo);
startActivity(intent);
}
Use startAtctivityForResult, and in onActivityResult check the resultCode. If it is Activity.RESULT_CANCELLED, the user 'backed out' of the SMS activity. Due to the implementation of the SMS activity being outside of your control, this might not be the only case when the result code says it has been cancelled.
I think you should, when the Activity picture is displayed, try to call the onBackPressed method.
// back button pressed method
#Override
public void onBackPressed() {
super.onBackPressed();
// new intent to call an activity that you choose
Intent intent = new Intent(this, NewActivity.class);
startActivity(intent);
// finish the activity picture
this.finish();
}
If you don't want to call an external Activity, you can hide the layout calling by the Intent as below:
// back button pressed method
#Override
public void onBackPressed() {
super.onBackPressed();
// your layout with the picture is displayed, hide it
if(MySecondView.getVisibility() == View.VISIBLE)
MySecondView.setVisibility(View.Gone);
// display the layout that you want
MyDefaultView.setVisibility(View.VISIBLE);
}
As I said below, try with a boolean that you initialize to false at the beginning of your Class. When you start the Intent.ACTION_VIEW, make this boolean to true:
public class Foo extends Activity {
private boolean isSms = false;
// some stuff
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("vnd.android-dir/mms-sms");
// ...
startActivity(intent);
// make your boolean to true
isSms = true;
// create the onBackPressed method
#Override
public void onBackPressed() {
// check if the user is on the sms layout
if(isSms)
// do something
else
// do something else like finish(); your activity
}
}
Or you can try to use the onKeyDown method (see here: onKeyDown (int keyCode, KeyEvent event)) as below:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_BACK && event.getRepeatCount()==0) {
// dome some stuff
return true;
}
return super.onKeyDown(keyCode, event);
}
You can see the diffence between these two methods here: onBackPressed() not working and on the website that I talk in the comments below.
Hope this will be useful.
UPDATE:
A better way should make an startActivityForResult to start the Intent.ACTION_VIEW:
startActivityForResult(intent, 1);
And then, you return the cancel code like this:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode != 1 && resultCode == RESULT_CANCELED) {
// do something
}
}
This is #FunkTheMonk, just above, who tells the good choice!
Add this method to the class to handle device back button.
#Override
public void onBackPressed() {
// do something
}
Please note that it requires API Level 5 or higher.
You have to overide go back behaviour of hardware back button by calling a method name onbackpressed();
#Override
public void onBackPressed() {
super.onBackPressed();
// set intent to activity where you want to move on after back press
Intent intent = new Intent(this, NewActivity.class);
startActivity(intent);
// also clean the current activity from stack.
youractivityname.this.finish();
}

Text to speech doesn't seem to be working and there is no error message in logCat

There appears to be something wrong with this code, each time its saying that I have not installed texttoSpeech on create and I have done, also when i click the start read button the application crashed with no error messages... So heres the code..
public class CBrecipeReader extends Activity{
public Cursor cursor;
CBDataBaseHelper data;
public static int ReadData = 1;
public TextToSpeech Speak = null;
public boolean SpeakInit = false;
public TextView Speech;
public TextView rowIDText2;
CBListAdapter adapter;
String RowID;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.texttospeech);
Bundle extras = getIntent().getExtras();
Button StartSpeech = (Button)findViewById(R.id.startSpeech);
rowIDText2 = (TextView)findViewById(R.id.rowID2);
Speech = (TextView) findViewById(R.id.sayThis);
if (extras != null) {
RowID = extras.getString("SELECTED3");
rowIDText2.setText(RowID);
}
if (rowIDText2.getText() != ""){
data = new CBDataBaseHelper(this);
String s = rowIDText2.getText().toString();
int ID = Integer.parseInt(s);
data.open();
Cursor cursor = data.fetchRow(ID);
if (cursor.moveToFirst()){ // data?
Speech.setText(cursor.getString(1) + " " + cursor.getString(2) + " " + cursor.getString(3));
}
data.close();
}
//+ " " + cursor.getString(2) + "" + cursor.getString(3)
initSpeak();
speakButtons(StartSpeech);
}
protected void initSpeak(){
Intent intent = new Intent(Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(intent, ReadData);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == ReadData){
if (resultCode == Engine.CHECK_VOICE_DATA_PASS){
Speak = new TextToSpeech(this, new OnInitListener() {
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS){
SpeakInit = true;
if(Speak.isLanguageAvailable(Locale.UK) >= 0){
Speak.setLanguage(Locale.UK);
Speak.setPitch(0.8f);
Speak.setSpeechRate(1.1f);
}
}
}
});
}else {
Intent installVoice = new Intent(Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installVoice);
}
}
}
protected void speakButtons(View view){
boolean diditwork;
try {
Speech = (TextView) findViewById(R.id.sayThis);
if (Speak != null && SpeakInit){
Speak.speak("test", TextToSpeech.QUEUE_ADD, null);
} else if (SpeakInit == false){
Toast.makeText(getApplicationContext(), "No Text to speech Installed ", Toast.LENGTH_SHORT).show();
}
}catch(Exception e){
diditwork = false;
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("darn");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}
}
}
Your code appears to be very similar to mine, the only difference I can see is
I call:
Speak.speak("test", TextToSpeech.QUEUE_FLUSH, null);
You call:
Speak.speak("test", TextToSpeech.QUEUE_ADD, null);

Categories

Resources