I am creating searchable dictionary and I want to display the most recent queries that user does in SearchView to other activity. just Like Recent option in android dictionaries.
private void handleIntent(Intent inent) {
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
// handles a click on a search suggestion; launches activity to show word
Intent wordIntent = new Intent(this, WordActivity.class);
wordIntent.setData(intent.getData());
startActivity(wordIntent);
finish();
} else if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
// handles a search query
String query = intent.getStringExtra(SearchManager.QUERY);
SearchRecentSuggestions suggestions=new SearchRecentSuggestions(this, MySuggestionProvider.AUTHORITY, MySuggestionProvider.MODE);
suggestions.saveRecentQuery(query, null);
showResults(query);
}
}
The ShowResult shows the query suggestions in the search activity, i want to show the recent queries into an other activity, how can i do this?
May be this code will help you with Shared Preference .
SharedPreferences sPreferences = getSharedPreferences("tushar", Context.MODE_PRIVATE);
Editor sEditor = sPreferences.edit();
Set<String> setName = new HashSet<String>();
setName.add("tushar");
setName.add("pandey");
setName.add("Ram");
setName.add("Shiva");
sEditor.putStringSet("ko", setName);
sEditor.commit() ;
Log.i("hello","tushar:pandey") ;
Set<String> setName_ = sPreferences.getStringSet("tushar", setName);
Log.i(setName_.toString(),"tushar:pandey") ;
Is possible to access saved queries through ContentResolver:
ContentResolver contentResolver = getApplicationContext().getContentResolver();
String contentUri = "content://" + MySuggestionProvider.AUTHORITY + '/' + SearchManager.SUGGEST_URI_PATH_QUERY;
Uri uri = Uri.parse(uriStr);
Cursor cursor = contentResolver.query(uri, null, null, new String[] { null }, null);
Now with received cursor populate a ListView. Create another activity using showResults() code.
Related
I have some string that i write into the Edittext on my first activity and im trying to send it to the Edittext on the other activity by pressing Button, but my code does not work, nothing happen and i dont know what else can i do here maybe somebody could help me out
My onClick method at 1st activity:
public void calendarOR(View v, AdapterView<?> parent, int position, long id) {
String data = cala.getText().toString();
Intent intent = new Intent(getApplicationContext(), calendar.class);
intent.putExtra("id",data);
startActivity(intent);
My second activity code:
Bundle extras = getIntent().getExtras();
if (extras != null) {
userId = extras.getLong("id");
}
if (userId > 0) {
userCursor = db.rawQuery("select * from " + dbelper.TABLE + " where " + dbelper.COLUMN_ID + "=?", new String[]{String.valueOf(userId)});
userCursor.moveToFirst();
date.setText(userCursor.getString(1));
userCursor.close();
}
You are putting a String data type and trying to get a long. Change the second activity to get the "id" as a string.
userId = extras.getString("id");
then
if (userId != null) {
userCursor = db.rawQuery("select * from " + dbelper.TABLE + " where " + dbelper.COLUMN_ID + "=?", new String[]{userId});
userCursor.moveToFirst();
date.setText(userCursor.getString(1));
userCursor.close();
}
You may also want to print log messages if userId is null or the data is not in the database to help with debugging.
Unrelated, but you may want to change your intent to not use the application context, like this, to launch the calendar activity.
Intent intent = new Intent(this, calendar.class);
do this in second activity code:
String data =getIntent().getStringExtra("id");
I tried this code.
public static void openGallery(Context context) {
String bucketId = "";
final String[] projection = new String[] {"DISTINCT " + MediaStore.Images.Media.BUCKET_DISPLAY_NAME + ", " + MediaStore.Images.Media.BUCKET_ID};
final Cursor cur = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, null);
while (cur != null && cur.moveToNext()) {
final String bucketName = cur.getString((cur.getColumnIndex(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME)));
if (bucketName.equals("Your_dir_name")) {
bucketId = cur.getString((cur.getColumnIndex(MediaStore.Images.ImageColumns.BUCKET_ID)));
break;
}
}
Uri mediaUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
if (bucketId.length() > 0) {
mediaUri = mediaUri.buildUpon()
.authority("media")
.appendQueryParameter("bucketId", bucketId)
.build();
}
if(cur != null){
cur.close();
}
Intent intent = new Intent(Intent.ACTION_VIEW, mediaUri);
context.startActivity(intent);
}
But I failed to open the gallery specific folder, but the gallery home screen appears with 'file not supported' Toast.
Is there any way I can solve this problem?
You can't set initial path to specific folder when working with files stored in MediaStore.
However, you can use DocumentsContract.EXTRA_INITIAL_URI when working with DocumentFile, so you can set initial path when user wants to select files from Storage Access Framework (SAF):
Uri initialUri = DocumentFileCompat.createDocumentUri(DocumentFileCompat.PRIMARY, "DCIM")
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
.putExtra(DocumentsContract.EXTRA_INITIAL_URI, initialUri)
DocumentFileCompat.createDocumentUri() helps you constructing the initial URI. You can get DocumentFileCompat from SimpleStorage.
I have to just transfer save file path from one activity to another activity but when it comes to show the data it display null value.
Following is the code to store data in SharedPreference:-
SharedPreferences pref= getApplicationContext().getSharedPreferences("Recorder",0);
SharedPreferences.Editor editor = pref.edit();
editor.putString("file_name",DateFormat.format("yyyy-MM-dd_kk-mm-ss", new Date().getTime())+".mp4");
editor.putString("file_path",Environment.getExternalStorageDirectory()+"/"+DateFormat.format("yyyy-MM-dd_kk-mm-ss", new Date().getTime())+".mp4");
Retrieving data from sharedPreference:-
file_name = (TextView) findViewById(R.id.file_name);
file_path = (TextView) findViewById(R.id.file_path);
pref = getApplicationContext().getSharedPreferences("Recorder",0);
editor = pref.edit();
String fileName = pref.getString("file_name",null);
String filePath = pref.getString("file_path",null);
if(fileName != null){
file_name.setText(fileName);
}else{
file_name.append("");
}
if (filePath != null){
file_path.setText(filePath);
}else{
file_path.append("");
}
You have to apply the editor by
editor.commit():
or
editor.apply();
editor.apply() is missing. You are not committing the save.
Why do you need to overload the system ? you have a mechanism for passing data between activities, just send the path of the file within the intent.
In ActivityA :
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putExtra("filePath", "...");
startActivity(intent);
In ActivityB :
String filePath = getIntent().getExtras().getString("filePath");
Yeah you can make use of SharedPreference to Store the information.
To pass the data from one activity to another its better to use intent.
Intent intent = new Intent(CurrentActivity.this, AnotherActivity.class);
intent.putExtra("file_name","name");
intent.putExtra("file_path","path");
startActivity(intent)
In another Activity,
String fileName = getIntent().getStringExtra("file_name");
String filePath = getIntent().getStringExtra("file_path");
If you are using SharedPreffernces just to share data between activities, then it's overkill.
In case data should be available after app restart your solutions is good. But if you need it only at runtime, it's better to use Intent as mentioned in other answers.
Personally, I would prefer to store it in some static variable.
editor.commit() is missing.
Better way is to use bundle that could be set in intent and use this intent to start another activity and then fetch values from intent's bundle.
Yes you can make use of SharedPrefernces. try below code
public static final String MYPREFERNCES_Example = "mysharedpref";
SharedPreferences.Editor editor ;
SharedPreferences sp;
sp = getSharedPreferences(MYPREFERNCES_Example Context.MODE_PRIVATE);
editor=sp.edit();
Intent i_login = new Intent(LoginActivity.this, HomeActivity.class);
editor.putString("yourownkey1", yourvalue);
editor.putString("yourownkey2", yourvalue);
editor.putString("yourownkey3", yourvalue);
startActivity(intent)
and in next activity
sp = getSharedPreferences(MYPREFERNCES_Example, 0);
editor = sp.edit();
String fn = sp.getString("yourownkey1", "");
String ln = sp.getString("yourownkey2", "");
String fbemail = sp.getString("yourownkey3", "");
This question already has answers here:
Android: Make phone call from service
(2 answers)
Closed 6 months ago.
i'm trying to make a phone call, when a specific notification arrive,
i use Notification Service Listener to read incoming notificaion,
public void onNotificationPosted(StatusBarNotification sbn) {
// if(if this is my notificaion..){
String name = sbn.getNotification().extras.getCharSequence(Notification.EXTRA_TITLE));
List<String> numbers = getPhoneNumbers(name);
Log.d(TAG, "i have all this numbers - " + numbers.toString());
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + numbers.get(1)));
startActivity(intent);
}
the "getPhoneNumbers" method is this one
public List<String> getPhoneNumbers(String name) {
List<String> numbers = new ArrayList<String>();
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
"DISPLAY_NAME = '" + name + "'", null, null);
if (cursor.moveToFirst()) {
String contactId =
cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
// Get all phone numbers.
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
while (phones.moveToNext()) {
String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
numbers.add(number);
}
phones.close();
}
cursor.close();
return numbers;
}
all work fine, ( i used break points to cheak everything...)
the "if this is my notification" work perfect, i get the name from the sbn extras, the 'numbers' arraylist include all the contact numbers after the "getPhoneNumbers" method used, but when i start the intent nathing happend..
what is my problem? :/
Let's clarify:
Problem
Your onNotificationPosted method does not launch a phone call when calling startActivity(intent);.
Why
NotificationListenerService is not an activity.
Solution
Make your MainActivity call the startActivity(intent);.
How
Define an attribute activity in NotificationListenerService and define a constructor that accepts an activity:
NotificationListenerService.java
// define attribute activity:
MainActivity activity;
public NotificationListenerService(MainActivity activity) {
this.activity = activity;
}
MainActivity.java
// create a NotificationListenerService sending itself as reference
NotificationListenerService nls = new NotificationListenerService(this);
Then inside the onNotificationPosted you will see the attribute, so you can:
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+ numbers.get(1)));
activity.startActivity(intent);
On my on create function I give the location an ID. However my issue is when I go to add a photo to that page before I've saved it. I need to save the photo with the same ID as the page. So I create the ID on the on create then when i add a picture and come back as it's loaded the other intent it runs the code again and creates a new ID. How can I pass the ID through the photo and back.
The variable checkStationObjectID is set at the top of the file.
Heres my on create:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_asset);
Bundle extras = getIntent().getExtras();
Log.e("CamDebug", "Loading extras");
if (extras != null) {
PreviousStationObjectID = extras.getString("StationObjectID");
editMode = extras.getBoolean("editMode");
editAreaObjectID = extras.getString("editAreaObjectID");
}
if(editMode){
checkStationObjectID = editAreaObjectID;
Log.e("CHECK ID - Edit mode", checkStationObjectID);
} else {
if(checkStationObjectID == null){
checkStationObjectID = NewAssetStationObjectID;
Log.e("CHECK ID = NEW ID", checkStationObjectID);
}
}
//Other items taken out
}
I launch the camera with:
public void startCamera()
{
File photo = null;
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
{
photo = new File(Global.Pictures + timestamp +".png");
}
else
{
photo = new File(getCacheDir(), FOLDER_NAME+File.separator+timestamp+".png");
}
if (photo != null)
{
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
selectedImageUri = Uri.fromFile(photo);
startActivityForResult(intent, CAPTURE_IMAGE_CALLBACK);
}
}
onCreate is called whenever your application is started. If you are calling another app like a camera, then the OS can kill your own Activity at any time while the camera Activity is running. This could be to recover memory or resources that the running app needs. Then when you exit the camera the OS will restart your Activity, which will call onCreate again.
I would suggest that you save the ID that you have generated into SharedPreferences just before you start the camera app. Then check for a saved ID in onActivityResult.
If you don't need to persist it you can create a Singleton object to act as a session and store the variable in there.. But I don't get why onCreate is executed again.. I thought the sub camera activity should return in onActivityResult? I pardon me if I misunderstood.
Or you can pass the var to the camera activity and pass it back when you are done with it.