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);
Related
I made an app in android and it is working fine but when I shifted my app to my main app it start showing error from that point package name is same as that of my previous app then also this is the error that i am getting .I followed many question but cant able to find any solution .
FATAL EXCEPTION: main
Process: unnion.neelay.beatbox, PID: 12739
java.lang.RuntimeException: Unable to start activity ComponentInfo{unnion.neelay.beatbox/unnion.neelay.beatbox.ringdroid.RingdroidSelectActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2423)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
at android.app.ActivityThread.access$900(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5441)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at unnion.neelay.beatbox.ringdroid.RingdroidSelectActivity.onCreate(RingdroidSelectActivity.java:123)
at android.app.Activity.performCreate(Activity.java:6303)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
at android.app.ActivityThread.access$900(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5441)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
it is showing null point exception but it was working properly when not added to the main app.
the ringdroid select activity
public class RingdroidSelectActivity
extends ListActivity
implements LoaderManager.LoaderCallbacks<Cursor> {
private SearchView mFilter;
private SimpleCursorAdapter mAdapter;
private boolean mWasGetContentIntent;
private boolean mShowAll;
private Cursor mExternalCursor;
// Result codes
private static final int EXT_STORAGE_PERMISSION_REQ_CODE = 2;
private static final int WRITE_EXTERNAL_STORAGE = 4;
private static final int READ_PHONE_STATE = 3;
private static final int WRITE_SETTINGS = 3;
private static final int CHANGE_CONFIGURATION = 1;
private static final int MODIFY_AUDIO_SETTINGS = 5;
private static final int INTERNET = 6;
private static final int REQUEST_CODE_EDIT = 1;
private static final int REQUEST_CODE_CHOOSE_CONTACT = 2;
// Context menu
private static final int CMD_EDIT = 4;
private static final int CMD_DELETE = 5;
private static final int CMD_SET_AS_DEFAULT = 6;
private static final int CMD_SET_AS_CONTACT = 7;
public RingdroidSelectActivity() {
}
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
checkReadStoragePermission();
mShowAll = false;
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
showFinalAlert(getResources().getText(R.string.sdcard_readonly));
return;
}
if (status.equals(Environment.MEDIA_SHARED)) {
showFinalAlert(getResources().getText(R.string.sdcard_shared));
return;
}
if (!status.equals(Environment.MEDIA_MOUNTED)) {
showFinalAlert(getResources().getText(R.string.no_sdcard));
return;
}
Intent intent = getIntent();
mWasGetContentIntent = intent.getAction().equals(
Intent.ACTION_GET_CONTENT);
// Inflate our UI from its XML layout description.
setContentView(R.layout.media_select);
getActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
getActionBar().setDisplayShowTitleEnabled(false);
try {
mAdapter = new SimpleCursorAdapter(
this,
// Use a template that displays a text view
R.layout.media_select_row,
null,
// Map from database columns...
new String[]{
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media._ID},
// To widget ids in the row layout...
new int[]{
R.id.row_artist,
R.id.row_title,
R.id.row_icon,
R.id.row_options_button},
0);
setListAdapter(mAdapter);
// Normal click - open the editor
getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view,
int position,
long id) {
startRingdroidEditor();
}
});
mExternalCursor = null;
getLoaderManager().initLoader(EXTERNAL_CURSOR_ID, null, this);
} catch (SecurityException e) {
// No permission to retrieve audio?
Log.e("Ringdroid", e.toString());
// TODO error 1
} catch (IllegalArgumentException e) {
// No permission to retrieve audio?
Log.e("Ringdroid", e.toString());
// TODO error 2
}
mAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if (view.getId() == R.id.row_options_button) {
// Get the arrow ImageView and set the onClickListener to open the context menu.
ImageView iv = (ImageView) view;
iv.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
openContextMenu(v);
}
});
return true;
} else if (view.getId() == R.id.row_icon) {
setSoundIconFromCursor((ImageView) view, cursor);
return true;
}
return false;
}
});
// Long-press opens a context menu
registerForContextMenu(getListView());
}
private void setSoundIconFromCursor(ImageView view, Cursor cursor) {
if (0 != cursor.getInt(cursor.getColumnIndexOrThrow(
MediaStore.Audio.Media.IS_MUSIC))) {
view.setImageResource(R.drawable.type_music);
((View) view.getParent()).setBackgroundColor(
getResources().getColor(R.color.type_bkgnd_music));
}
String filename = cursor.getString(cursor.getColumnIndexOrThrow(
MediaStore.Audio.Media.DATA));
}
/**
* Called with an Activity we started with an Intent returns.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent dataIntent) {
if (requestCode != REQUEST_CODE_EDIT) {
return;
}
if (resultCode != RESULT_OK) {
return;
}
setResult(RESULT_OK, dataIntent);
//finish(); // TODO(nfaralli): why would we want to quit the app here?
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.select_options, menu);
mFilter = (SearchView) menu.findItem(R.id.action_search_filter).getActionView();
if (mFilter != null) {
mFilter.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
public boolean onQueryTextChange(String newText) {
refreshListView();
return true;
}
public boolean onQueryTextSubmit(String query) {
refreshListView();
return true;
}
});
}
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.findItem(R.id.action_record).setVisible(true);
// TODO(nfaralli): do we really need a "Show all audio" item now?
menu.findItem(R.id.action_show_all_audio).setVisible(true);
menu.findItem(R.id.action_show_all_audio).setEnabled(!mShowAll);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_record:
onRecord();
return true;
case R.id.action_show_all_audio:
mShowAll = true;
refreshListView();
return true;
default:
return false;
}
}
#Override
public void onCreateContextMenu(ContextMenu menu,
View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
Cursor c = mAdapter.getCursor();
String title = c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
menu.setHeaderTitle(title);
menu.add(0, CMD_EDIT, 0, R.string.context_menu_edit);
menu.add(0, CMD_DELETE, 0, R.string.context_menu_delete);
// Add items to the context menu item based on file type
if (0 != c.getInt(c.getColumnIndexOrThrow(MediaStore.Audio.Media.IS_RINGTONE))) {
menu.add(0, CMD_SET_AS_DEFAULT, 0, R.string.context_menu_default_ringtone);
menu.add(0, CMD_SET_AS_CONTACT, 0, R.string.context_menu_contact);
} else if (0 != c.getInt(c.getColumnIndexOrThrow(MediaStore.Audio.Media.IS_NOTIFICATION))) {
menu.add(0, CMD_SET_AS_DEFAULT, 0, R.string.context_menu_default_notification);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case CMD_EDIT:
startRingdroidEditor();
return true;
case CMD_DELETE:
confirmDelete();
return true;
case CMD_SET_AS_DEFAULT:
setAsDefaultRingtoneOrNotification();
return true;
case CMD_SET_AS_CONTACT:
return chooseContactForRingtone(item);
default:
return super.onContextItemSelected(item);
}
}
private void setAsDefaultRingtoneOrNotification() {
Cursor c = mAdapter.getCursor();
// If the item is a ringtone then set the default ringtone,
// otherwise it has to be a notification so set the default notification sound
if (0 != c.getInt(c.getColumnIndexOrThrow(MediaStore.Audio.Media.IS_RINGTONE))) {
RingtoneManager.setActualDefaultRingtoneUri(
RingdroidSelectActivity.this,
RingtoneManager.TYPE_RINGTONE,
getUri());
Toast.makeText(
RingdroidSelectActivity.this,
R.string.default_ringtone_success_message,
Toast.LENGTH_SHORT)
.show();
} else {
RingtoneManager.setActualDefaultRingtoneUri(
RingdroidSelectActivity.this,
RingtoneManager.TYPE_NOTIFICATION,
getUri());
Toast.makeText(
RingdroidSelectActivity.this,
R.string.default_notification_success_message,
Toast.LENGTH_SHORT)
.show();
}
}
private int getUriIndex(Cursor c) {
int uriIndex;
String[] columnNames = {
MediaStore.Audio.Media.INTERNAL_CONTENT_URI.toString(),
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI.toString()
};
for (String columnName : Arrays.asList(columnNames)) {
uriIndex = c.getColumnIndex(columnName);
if (uriIndex >= 0) {
return uriIndex;
}
// On some phones and/or Android versions, the column name includes the double quotes.
uriIndex = c.getColumnIndex("\"" + columnName + "\"");
if (uriIndex >= 0) {
return uriIndex;
}
}
return -1;
}
private Uri getUri() {
//Get the uri of the item that is in the row
Cursor c = mAdapter.getCursor();
int uriIndex = getUriIndex(c);
if (uriIndex == -1) {
return null;
}
String itemUri = c.getString(uriIndex) + "/" +
c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
return (Uri.parse(itemUri));
}
private boolean chooseContactForRingtone(MenuItem item) {
try {
//Go to the choose contact activity
Intent intent = new Intent(Intent.ACTION_EDIT, getUri());
intent.setClassName(
"unnion.neelay.beatbox.ringdroid",
"unnion.neelay.beatbox.ringdroid.ChooseContactActivity");
startActivityForResult(intent, REQUEST_CODE_CHOOSE_CONTACT);
} catch (Exception e) {
Log.e("Ringdroid", "Couldn't open Choose Contact window");
}
return true;
}
private void confirmDelete() {
// See if the selected list item was created by Ringdroid to
// determine which alert message to show
Cursor c = mAdapter.getCursor();
String artist = c.getString(c.getColumnIndexOrThrow(
MediaStore.Audio.Media.ARTIST));
CharSequence ringdroidArtist =
getResources().getText(R.string.artist_name);
CharSequence message;
if (artist.equals(ringdroidArtist)) {
message = getResources().getText(
R.string.confirm_delete_ringdroid);
} else {
message = getResources().getText(
R.string.confirm_delete_non_ringdroid);
}
CharSequence title;
if (0 != c.getInt(c.getColumnIndexOrThrow(
MediaStore.Audio.Media.IS_RINGTONE))) {
title = getResources().getText(R.string.delete_ringtone);
} else if (0 != c.getInt(c.getColumnIndexOrThrow(
MediaStore.Audio.Media.IS_ALARM))) {
title = getResources().getText(R.string.delete_alarm);
} else if (0 != c.getInt(c.getColumnIndexOrThrow(
MediaStore.Audio.Media.IS_NOTIFICATION))) {
title = getResources().getText(R.string.delete_notification);
} else if (0 != c.getInt(c.getColumnIndexOrThrow(
MediaStore.Audio.Media.IS_MUSIC))) {
title = getResources().getText(R.string.delete_music);
} else {
title = getResources().getText(R.string.delete_audio);
}
new AlertDialog.Builder(RingdroidSelectActivity.this)
.setTitle(title)
.setMessage(message)
.setPositiveButton(
R.string.delete_ok_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
onDelete();
}
})
.setNegativeButton(
R.string.delete_cancel_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
})
.setCancelable(true)
.show();
}
private void onDelete() {
Cursor c = mAdapter.getCursor();
int dataIndex = c.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
String filename = c.getString(dataIndex);
int uriIndex = getUriIndex(c);
if (uriIndex == -1) {
showFinalAlert(getResources().getText(R.string.delete_failed));
return;
}
if (!new File(filename).delete()) {
showFinalAlert(getResources().getText(R.string.delete_failed));
}
String itemUri = c.getString(uriIndex) + "/" +
c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
getContentResolver().delete(Uri.parse(itemUri), null, null);
}
private void showFinalAlert(CharSequence message) {
new AlertDialog.Builder(RingdroidSelectActivity.this)
.setTitle(getResources().getText(R.string.alert_title_failure))
.setMessage(message)
.setPositiveButton(
R.string.alert_ok_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
finish();
}
})
.setCancelable(false)
.show();
}
private void onRecord() {
try {
Intent intent = new Intent(Intent.ACTION_EDIT, Uri.parse("record"));
intent.putExtra("was_get_content_intent", mWasGetContentIntent);
intent.setClassName("unnion.neelay.mediaplayer.ringdroid", "unnion.neelay.mediaplayer.ringdroid.RingdroidEditActivity");
startActivityForResult(intent, REQUEST_CODE_EDIT);
} catch (Exception e) {
Log.e("Ringdroid", "Couldn't start editor");
}
}
private void startRingdroidEditor() {
Cursor c = mAdapter.getCursor();
int dataIndex = c.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
String filename = c.getString(dataIndex);
try {
Intent intent = new Intent(Intent.ACTION_EDIT, Uri.parse(filename));
intent.putExtra("was_get_content_intent", mWasGetContentIntent);
intent.setClassName("unnion.neelay.mediaplayer.ringdroid", "unnion.neelay.mediaplayer.ringdroid.RingdroidEditActivity");
startActivityForResult(intent, REQUEST_CODE_EDIT);
} catch (Exception e) {
Log.e("Ringdroid", "Couldn't start editor");
}
}
private void refreshListView() {
mExternalCursor = null;
Bundle args = new Bundle();
args.putString("filter", mFilter.getQuery().toString());
getLoaderManager().restartLoader(EXTERNAL_CURSOR_ID, args, this);
}
private static final String[] EXTERNAL_COLUMNS = new String[]{
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.IS_RINGTONE,
MediaStore.Audio.Media.IS_ALARM,
MediaStore.Audio.Media.IS_NOTIFICATION,
MediaStore.Audio.Media.IS_MUSIC,
"\"" + MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "\""
};
private static final int EXTERNAL_CURSOR_ID = 1;
/* Implementation of LoaderCallbacks.onCreateLoader */
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
ArrayList<String> selectionArgsList = new ArrayList<String>();
String selection;
Uri baseUri;
String[] projection;
switch (id) {
case EXTERNAL_CURSOR_ID:
baseUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
projection = EXTERNAL_COLUMNS;
break;
default:
return null;
}
if (mShowAll) {
selection = "(_DATA LIKE ?)";
selectionArgsList.add("%");
} else {
selection = "(";
for (String extension : SoundFile.getSupportedExtensions()) {
selectionArgsList.add("%." + extension);
if (selection.length() > 1) {
selection += " OR ";
}
selection += "(_DATA LIKE ?)";
}
selection += ")";
selection = "(" + selection + ") AND (_DATA NOT LIKE ?)";
selectionArgsList.add("%espeak-data/scratch%");
}
String filter = args != null ? args.getString("filter") : null;
if (filter != null && filter.length() > 0) {
filter = "%" + filter + "%";
selection =
"(" + selection + " AND " +
"((TITLE LIKE ?) OR (ARTIST LIKE ?) OR (ALBUM LIKE ?)))";
selectionArgsList.add(filter);
selectionArgsList.add(filter);
selectionArgsList.add(filter);
}
String[] selectionArgs =
selectionArgsList.toArray(new String[selectionArgsList.size()]);
return new CursorLoader(
this,
baseUri,
projection,
selection,
selectionArgs,
MediaStore.Audio.Media.DEFAULT_SORT_ORDER
);
}
/* Implementation of LoaderCallbacks.onLoadFinished */
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
switch (loader.getId()) {
case EXTERNAL_CURSOR_ID:
mExternalCursor = data;
break;
default:
return;
}
// TODO: should I use a mutex/synchronized block here?
if (mExternalCursor != null) {
Cursor mergeCursor = new MergeCursor(new Cursor[]{mExternalCursor});
mAdapter.swapCursor(mergeCursor);
}
}
/* Implementation of LoaderCallbacks.onLoaderReset */
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
mAdapter.swapCursor(null);
}
#TargetApi(Build.VERSION_CODES.M)
private void checkReadStoragePermission() {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
ActivityCompat.requestPermissions(RingdroidSelectActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, EXT_STORAGE_PERMISSION_REQ_CODE);
} else if (which == DialogInterface.BUTTON_NEGATIVE) {
onPermissionsNotGranted();
}
dialog.dismiss();
finish();
startActivity(getIntent());
}
};
new android.support.v7.app.AlertDialog.Builder(this)
.setTitle(R.string.permissions_title)
.setMessage(R.string.read_ext_permissions_message)
.setPositiveButton(R.string.btn_continue, onClickListener)
.setNegativeButton(R.string.btn_cancel, onClickListener)
.setCancelable(false)
.show();
return;
}
ActivityCompat.requestPermissions(RingdroidSelectActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.READ_PHONE_STATE}, EXT_STORAGE_PERMISSION_REQ_CODE);
return;
}
}
private void onPermissionsNotGranted() {
Toast.makeText(this, R.string.toast_permissions_not_granted, Toast.LENGTH_SHORT).show();
Log.v("tom", "JERRY");
}
}
Looking at your callstack it should really help you narrow down your problem.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at unnion.neelay.beatbox.ringdroid.RingdroidSelectActivity.onCreate(RingdroidSelectActivity.java:123)
at android.app.Activity.performCreate(Activity.java:6303)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
For example, in your callstack, you first have the exception that's being thrown, NullPointerException, and it's telling you what is causing it.
java.lang.String.equals(java.lang.Object)
So, you have a String that you're attempting to call .equals on, but the String is null.
Now, a bit lower, it shows the line number of where this issue is happening.
unnion.neelay.beatbox.ringdroid.RingdroidSelectActivity.onCreate(RingdroidSelectActivity.java:123)
So, you're calling .equals within your RingdroidSelectActivity's onCreate at line 123.
However, perhaps your code has changed since you posted your error, there isn't a .equals around that line, but I'm thinking it may be your getExternalStroage().
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
showFinalAlert(getResources().getText(R.string.sdcard_readonly));
return;
}
Perhaps you don't have the permission for this or something else. Add in some checks for null, and that will help you debug the problem.
Hopefully that helps!
Edit:
The issue was this
so the answer is
mWasGetContentIntent = Intent.ACTION_GET_CONTENT.equals(intent.getAction());
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.
enter image description herehow can i add multiple TextView and their inside relative layout dynamically which is already created? Also I have to call the values of those text boxes from database sqlite.
public class DownloadPackagesActivity extends Activity implements AdapterView.OnItemSelectedListener{
private SQLiteDatabase db;
DBHelper dbHelper;
String newFolder = "";
int SId = 1;
TextView subjects;
List<String> categories = new ArrayList<String>();
String FilePart = "";
DownloadManager dManager;
long did;
// private static String file_url = "http://mobileteacher.in/audio/demo/2725.mp3";
String urlString ="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download_packages);
// Get DownloadManager instance
dManager = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
subjects = (TextView)findViewById(R.id.subjects);
// Spinner element
Spinner spinner = (Spinner) findViewById(R.id.spinnerPackage);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Add textview
dbHelper = new DBHelper(this);
try{
dbHelper.createDataBase();
}
catch(Exception ex)
{
ex.printStackTrace();
}
String myPath = dbHelper.DB_PATH + DBHelper.DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
Cursor c = db.rawQuery("select * from DownloadSubject", null);
while (c.moveToNext()) {
categories.add(c.getString(1));
}
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, categories);
dataAdapter1.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
spinner.setAdapter(dataAdapter1);
showPart();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
SId = position + 1;
showPart();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void showPart()
{
int j=1;
int ii=0;
dbHelper = new DBHelper(this);
try{
dbHelper.createDataBase();
}
catch(Exception ex)
{
ex.printStackTrace();
}
TableLayout stk = (TableLayout) findViewById(R.id.tbl);
stk.removeAllViews();
String myPath = dbHelper.DB_PATH + DBHelper.DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
Cursor c;
if (SId==8 || SId==9)
{
c = db.rawQuery("select * from DownloadSubject", null);
}
else
{
c = db.rawQuery("select * from DownloadSubject where Id = '"+ SId +"'", null);
}
while (c.moveToNext())
{
subjects.clearComposingText();
String[] part = c.getString(2).split(",");
for(int i = 0;i<part.length;i++)
{
TableRow tr1 = new TableRow(this);
Button button = new Button(this);
button.setBackgroundColor(Color.TRANSPARENT);
button.setText(part[i] +"\u00A0 \u00A0 \u00A0 \u00A0 Download");
button.setTextColor(Color.BLUE);
button.setPadding(20, 0, 0, 0);
button.setOnClickListener(downloads());
button.setId(i);
// button.setHint(part[i]);
tr1.addView(button);
stk.addView(tr1);
}
stk = (TableLayout) findViewById(R.id.tbl);
int N = 1;
TextView[] TextViews = new TextView[N]; // create an empty array;
// for (int i = 0; i < N; i++) {
//if(ii!=0) {
// subjects.setText(c.getString(j));
// Toast.makeText(this, c.getString(j), Toast.LENGTH_LONG).show();
// save a reference to the textview for later
// TextViews[j] = TextView;
//}
if(ii==0)
{
subjects.setText(c.getString(j));
ii=ii+1;
}
else
{
final TextView TextView = new TextView(this);
TextView.setText(c.getString(j));
TextView.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT,
TableLayout.LayoutParams.WRAP_CONTENT));
TextView.setPadding(0, 20, 0, 20);
TextView.setTextSize(getResources().getDimension(R.dimen.textsize));
TextView.setTextColor(Color.parseColor("#800080"));
// add the textview to the layout
stk.addView(TextView);
}
}
}
public String part;
View.OnClickListener downloads()
{
return new View.OnClickListener()
{
public void onClick(View v) {
//Button b1 = (Button)v;
//int i = b1.getId();
// Toast.makeText(getApplicationContext(),"Ide = " + i,Toast.LENGTH_LONG).show();
part ="";
TextView subjects = (TextView)findViewById(R.id.subjects);
if(subjects.getText().toString().equals("Modern History (500 MB)"))
{
part = "modern_history";
}
else if(subjects.getText().toString().equals("Polity (250 MB)"))
{
part = "polity";
}
else if(subjects.getText().toString().equals("Economy (100 MB)"))
{
part = "economy";
}
else if(subjects.getText().toString().equals("Ancient History (500 MB)"))
{
part = "ancient_history";
}
else if(subjects.getText().toString().equals("English Grammar (500 MB)"))
{
part = "english_grammar";
}
else if(subjects.getText().toString().equals("Vocabulary (560 MB)"))
{
part = "vocabulary";
}
else if(subjects.getText().toString().equals("Maths (100 MB)"))
{
part = "maths";
}
else if(subjects.getText().toString().equals("One Day Complete(Vol.1(2GB))"))
{
part = "oneday_complete";
}
else if(subjects.getText().toString().equals("Civil Complete (Vol.1 (2GB))"))
{
part = "civil_complete" ;
}
newFolder = "/voice";
subjects = (TextView)findViewById(R.id.subjects);
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File myNewFolder = new File(extStorageDirectory + newFolder);
//File f = new File(myNewFolder);
myNewFolder.mkdir();
Button b = (Button)v;
FilePart = b.getText().toString();
String RemoveSpace = FilePart.split("\u00A0")[0].replace(" ","");
try {
urlString = "http://mobileteacher.in/DealerPackage/" + part + "/" + RemoveSpace + ".zip";
downloadFile();
Toast.makeText(getApplicationContext(), "Download Started", Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Please Connect Internet", Toast.LENGTH_LONG).show();
}
}
};
}
public void downloadFile() {
// String urlString = "http://mobileteacher.in/audio/demo/2725.mp3";
if (!urlString.equals("")) {
try {
// Get file name from the url
String fileName = urlString.substring(urlString.lastIndexOf("/") + 1);
// Create Download Request object
DownloadManager.Request request = new DownloadManager.Request(Uri.parse((urlString)));
// Display download progress and status message in notification bar
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
// Set description to display in notification
// request.setDescription("Download " + fileName + " from " + urlString);
request.setDescription("Download " + fileName + " from mobileteacher.in");
// Set title
request.setTitle("Mobile Teacher");
// Set destination location for the downloaded file
request.setDestinationUri(Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/voice/"+fileName.split("\u00A0")[0].replace(" ","")));
// Download the file if the Download manager is ready
did = dManager.enqueue(request);
} catch (Exception e) {
}
}
}
// BroadcastReceiver to receive intent broadcast by DownloadManager
private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(did);
Cursor cursor = dManager.query(q);
if (cursor.moveToFirst()) {
String message = "";
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
message = "Download successful";
} else if (status == DownloadManager.STATUS_FAILED) {
message = "Download failed";
}
//query.setText(message);
}
}
};
protected void onResume() {
super.onResume();
// Register the receiver to receive an intent when download complete
IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(downloadReceiver, intentFilter);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
// Unregister the receiver
unregisterReceiver(downloadReceiver);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_download_packages, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void back(View view)
{
finish();
}
public void Create(View view)
{
String newFolder = "/voice";
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File myNewFolder = new File(ext[enter image description here][1]StorageDirectory + newFolder);
myNewFolder.mkdir();
}
}
this is the image
create relative layout object from it layout id, then you can add it as below
relativeLayout = findViewById(R.id.yourRelativeLayoutId);
relativeLayout.addView(yourView);
Listview or recyclerview is best for practice but as you want to use textview, you can use like this in your code:
RelativeLayout relativeLayout =
(RelativeLayout) findViewById(R.id.rootlayout);
TextView textView = new TextView(this);
textView.setText("Hey, I am TextView");
relativeLayout.addView(textView);
appending a textview to relativelayout is pretty simple.
just use
TextView textview = new TextView(this);
textview.setText("Text");
relativelayoutobject.addView(textview);
to setup the position use
textview.setLayoutParams(thelayoutparams)
But if you use big database, please, use 'TableLayout' instead of your method due to performance reasons.
Define relative layout in your xml layout. Add multiple textview programmatic ally like this-
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
//use a for loop to define multiple textView in RelativeLayout
//length is no. of textView you required
for (int i = 0; i < length; i++) {
TextView tv = new TextView(relativeLayout.getContext());
tv.setText("Text from sqlite database");
tv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
relativeLayout.addView(tv);
}
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();
}
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);