In my application i need to search the phone contact numbers and I want to select a number and I want to save that number and after that once I click, send button message should go to that number. Here am using more than two activities and am searching a contacts inside of one such activity..
please any one can help me..thanks in advance..
Here is my code.
public class SearchNum extends Activity {
private TextView resultText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchnum);
resultText = (TextView)findViewById(R.id.searchViewResult);
setupSearchView();
}
private void setupSearchView() {
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
final SearchView searchView = (SearchView) findViewById(R.id.searchView);
SearchableInfo searchableInfo = searchManager.getSearchableInfo(getComponentName());
searchView.setSearchableInfo(searchableInfo);
}
#Override
protected void onNewIntent(Intent intent) {
if (ContactsContract.Intents.SEARCH_SUGGESTION_CLICKED.equals(intent.getAction())) {
//handles suggestion clicked query
String displayName = getDisplayNameForContact(intent);
resultText.setText(displayName);
} else if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
// handles a search query
String query = intent.getStringExtra(SearchManager.QUERY);
resultText.setText("should search for query: '" + query + "'...");
}
}
private String getDisplayNameForContact(Intent intent) {
Cursor phoneCursor = getContentResolver().query(intent.getData(), null, null, null, null);
phoneCursor.moveToFirst();
int idDisplayName = phoneCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
String name = phoneCursor.getString(idDisplayName);
phoneCursor.close();
return name;
}
}
and my xml file for search view is
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SearchNum" >
<SearchView
android:id="#+id/searchView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" >
</SearchView>
<TextView
android:id="#+id/searchViewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/searchView"
android:layout_centerHorizontal="true"
android:text="#string/hello_world" />
</RelativeLayout>
Then my searchable file in xml folder is
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="#string/findContact"
android:hint="#string/findContact"
android:includeInGlobalSearch="true"
android:queryAfterZeroResults="true"
android:searchMode="queryRewriteFromText"
android:searchSettingsDescription="#string/findContact"
android:searchSuggestAuthority="com.android.contacts"
android:searchSuggestIntentAction="android.provider.Contacts.SEARCH_SUGGESTION_CLICKED"
android:searchSuggestIntentData="content://com.android.contacts/contacts/lookup" >
<!-- allow green action key for search-bar and per-suggestion clicks -->
<actionkey
android:keycode="KEYCODE_CALL"
android:queryActionMsg="call"
android:suggestActionMsg="call" />
</searchable>
and also i have taken permission in my manifest file
<uses-permission android:name="android.permission.READ_CONTACTS" />
in activity i put
<action android:name="android.intent.action.SEARCH" />
and also here is my metadata
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
You also need to add to your manifest file:
android:launchMode="singleTop"
Link: http://looksok.wordpress.com/2013/06/15/android-searchview-tutorial-edittext-with-phone-contacts-search-and-autosuggestion/
Related
I find this more difficult than working on an XML file. How do I block spaces in the text input of an alert dialog? For example, how does it work because I didn't find much information about this on the internet. Thank you
private void RequestNewGroup()
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.AlertDialog);
builder.setTitle("Enter Group Name ");
final EditText groupNameField = new EditText(MainActivity.this);
groupNameField.setHint("");
groupNameField.setFilters(new InputFilter[]{new InputFilter.LengthFilter(25)});
builder.setView(groupNameField);
builder.setPositiveButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i)
{
String groupName = groupNameField.getText().toString();
if (TextUtils.isEmpty(groupName))
{
Toast.makeText(MainActivity.this, "Please write Group Name...", Toast.LENGTH_SHORT).show();
}
else
{
CreateNewGroup(groupName);
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i)
{
dialogInterface.cancel();
}
});
builder.show();
}
I find this more difficult than working on an XML file.
You could (and probably should) create custom dialogs that have their own view/XML file.
To do this, extend DialogFragment:
public class MyDialog extends DialogFragment {
EditText editText;
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// get your custom layout
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.my_custom_layout, null);
builder.setView(view).setCancelable(false);
editText = view.findViewById(R.id.editText);
// add your code here
}
}
XML (R.layout.my_custom_layout):
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="foo"
android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"
android:inputType="textFilter" />
</androidx.constraintlayout.widget.ConstraintLayout>
and in MainActivity:
public void openDialog(Context context) {
MyDialog dialog = new MyDialog();
dialog.show(getSupportFragmentManager(), "myDialog");
}
also check Android disable space only for Edittext to disable space from XML and
https://www.youtube.com/watch?v=ARezg1D9Zd0&t=446s&ab_channel=CodinginFlow for a more in depth tutorial on custom dialogs and how to send and recieve info from them.
I am trying to use the MVC unobstrusive validation with jquery globalize plugin in MVC5 (in conjunction with the package jquery-validate-globalize). For learning purposes I started a demo project as per here, but it fails to run with globalize (it works on default Microsoft unobstrusive validation). The model is very simple:
public class GlobalizeModel
{
[Range(10.5D, 20.3D)]
public decimal Double { get; set; }
[Required]
public DateTime? DateTime { get; set; }
}
I try to initiate Globalize as follows at the bottom of the _Layout page (the view is minimal with 2 input only): (I get list of necessary files from https://johnnyreilly.github.io/globalize-so-what-cha-want/)
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<!--cldr scripts-->
<script src="~/Scripts/cldr.js"></script>
<script src="~/Scripts/cldr/event.js"></script>
<script src="~/Scripts/cldr/supplemental.js"></script>
<!--globalize scripts-->
<script src="~/Scripts/globalize.js"></script>
<script src="~/Scripts/globalize/number.js"></script>
<script src="~/Scripts/globalize/date.js"></script>
<!--jquery globalize-->
<script src="~/Scripts/jquery.validate.globalize.js"></script>
<script>
$.when(
$.getJSON("/Scripts/cldr/supplemental/likelySubtags.json"),
$.getJSON("/Scripts/cldr/main/en/numbers.json"),
$.getJSON("/Scripts/cldr/supplemental/numberingSystems.json"),
$.getJSON("/Scripts/cldr/main/en/ca-gregorian.json"),
$.getJSON("/Scripts/cldr/main/en/timeZoneNames.json"),
$.getJSON("/Scripts/cldr/supplemental/timeData.json"),
$.getJSON("/Scripts/cldr/supplemental/weekData.json"),
$.getJSON("/Scripts/cldr/main/tr/numbers.json"),
$.getJSON("/Scripts/cldr/main/tr/ca-gregorian.json"),
$.getJSON("/Scripts/cldr/main/tr/timeZoneNames.json"),
console.log("JSONs loaded")
).then(function () {
console.log("start slicing");
return [].slice.apply(arguments, [0]).map(function (result) {
console.log("slicing done");
return result[0];
});
}).then(Globalize.load).then(function () {
Globalize.locale("en");
console.log("Locale set to en");
}).then(console.log("LOADED EVERYTHING"));
</script>
But when I run the page, I only see the console logs JSOns loaded and LOADED EVERYTHING. Moreover, when I try a client side validation by typing anything in the number textbox (and of course when the focus is lost), I get the following error in the console:
Uncaught Error: E_DEFAULT_LOCALE_NOT_DEFINED: Default locale has not been defined.
This post here is similar, and I tried to check the things listed there. I think my JSON objects are not fetched, but I am not good aj JS so I am not sure on that. I added the following items to web.config to see if this is something related with file serving, with no avail:
<system.webServer>
<staticContent>
<remove fileExtension=".json"/>
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
</system.webServer>
The culture is set to auto in web.config as follows:
<system.web>
<globalization culture="auto" uiCulture="auto" />
<compilation debug="true" targetFramework="4.5.2"/>
<httpRuntime targetFramework="4.5.2"/>
</system.web>
You can see Scripts folder structure in here:
So, what is the problem here? How can I make this thing work?
I recently ran into the same problem, trying to add I18n to an MVC5 web app. After several days of research and partly using your code as base, I found some things that helped me implement it.
My Solution:
In a separate project, I added decimal and DateTime properties to the ApplicationUser class:
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
public DateTime birthdate { get; set; }
public decimal balance { get; set; }
}
I also modified the RegisterViewModel to accept those properties, as follows:
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Required]
[DataType(DataType.DateTime)]
public DateTime birthdate { get; set; }
[Required]
[DataType(DataType.Currency)]
public decimal balance { get; set; }
}
Then, I set the culture in a base controller, from which other controllers inherit:
public class BaseController : Controller
{
protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
{
string[] cultures = { "es-CL", "es-GT", "en-US" };
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cultures[1]);
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
return base.BeginExecuteCore(callback, state);
}
}
That's just for testing purposes, not the way I fetch culture in the real app.
My file structure is the same as yours and I didn't modify the web.config file.
I also used this link for dependencies. But then I modified a few things in the scripts section of Register.cshtml:
<!-- CLDR -->
<script src="~/Scripts/cldr.js"></script>
<script src="~/Scripts/cldr/event.js"></script>
<script src="~/Scripts/cldr/supplemental.js"></script>
<!-- Globalize -->
<script src="~/Scripts/globalize.js"></script>
<script src="~/Scripts/globalize/number.js"></script>
<script src="~/Scripts/globalize/date.js"></script>
<!-- $ validate -->
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.globalize.js"></script>
<!-- fetch files -->
<script>
$.when(
$.getJSON("/Scripts/cldr/supplemental/likelySubtags.json"),
$.getJSON("/Scripts/cldr/main/en/numbers.json"),
$.getJSON("/Scripts/cldr/supplemental/numberingSystems.json"),
$.getJSON("/Scripts/cldr/main/en/ca-gregorian.json"),
$.getJSON("/Scripts/cldr/main/en/timeZoneNames.json"),
$.getJSON("/Scripts/cldr/supplemental/timeData.json"),
$.getJSON("/Scripts/cldr/supplemental/weekData.json"),
$.getJSON("/Scripts/cldr/main/tr/numbers.json"),
$.getJSON("/Scripts/cldr/main/tr/ca-gregorian.json"),
$.getJSON("/Scripts/cldr/main/tr/timeZoneNames.json"),
).then(function () {
console.log("start slicing");
return [].slice.apply(arguments, [0]).map(function (result) {
console.log("slicing done");
return result[0];
});
}).then(Globalize.load).then(function () {
Globalize.locale("en");
console.log("Locale set to en");
}).then(console.log("LOADED EVERYTHING"));
</script>
The _Layout view scripts weren't modified at all, and I had no problem with the console logs.
That's all, it worked out for me, and as it's a very similar case, I hope it works for you too.
I wanna use appsettings value from web.config file on html page in javascript or jquery. The content from my web.config file is:
<configuration>
<appSettings>
<add key="ServiceURL" value="http://localhost:16917/Service1.svc"></add>
</appSettings>
</configuration>
I have tried with
var serviceUrl='<%=ConfigurationManager.AppSettings["ServiceURL"].ToString() %>'
alert(serviceUrl);
Instead of showing value from webconfig it is showing <%=ConfigurationManager.AppSettings["ServiceURL"].ToString() %> on alert.
Can anybody help me please.
I think you are missing closing tag '>'
<configuration>
<appSettings>
<add key="ServiceURL" value="http://localhost:16917/Service1.svc"> </add>
</appSettings>
</configuration>
1. Change WebConfig UI
<pages pageBaseType="Main.Web.ViewPage">
Create an abstract class that implement from the WebViewPage.
public abstract class ViewPage<T> : WebViewPage<T>
{
public ViewPage()
{
}
public JSSettings UISession
{
get
{
var appSettingsFileBasedSettings = new JSSettings()
{
SessionTimeoutMinutes = ConfigurationManager.AppSettings["SessionTimeoutMinutes"]
};
return appSettingsFileBasedSettings;
}
}
}
In the html page just do something like.
<script type="text/javascript">
var show = {
Settings : #Html.Raw(Json.Encode(this.UISession))
};
console.log(show);
</script>
Hope it help.
This should work:
var test = {
ServiceURL: <%=ConfigurationManager.AppSettings["ServiceURL"] %>
}
You can't do that with static HTML file, at least not in any good way.
Instead, use the power of ASP.NET and work with a Web Form, where you have Code Behind.
In the code behind, send the value from the server to the client as JS variable:
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "ServiceURL_JS",
string.Format("var serviceUrl = \"{0}\"; ",
ConfigurationManager.AppSettings["ServiceURL"]), true
);
}
Now you can access the variable serviceUrl in the client side JS.
I want to show WebView in Android on which I want to play video from html video tag.
I write the code for doing this and video is played automatically i.e. without press any button video is automatically started.
But, I want WebView is only shown when video is ready to play.
Please see my code and tell me what piece of code I have to write so that when video buffers completes then WebView will become visible and video started automatically.
I added a button on GUI when click on that button this method will be called.
public void onShowInlineVideoButton(View view) {
//webView.setVisibility(View.VISIBLE);
webView.setWebChromeClient(new WebChromeClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
int SDK_INT = android.os.Build.VERSION.SDK_INT;
System.out.println("!!!!!!! SDK_INT is: " + SDK_INT);
if (SDK_INT > 16) {
webView.getSettings().setMediaPlaybackRequiresUserGesture(false);
}
webView.setWebViewClient(new WebViewClient() {
// autoplay when finished loading via javascript injection
#Override public void onPageFinished(WebView view, String url) {
System.out.println("!!!!!!!!!! In onPageFinished method...");
webView.loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })");
webView.setVisibility(View.VISIBLE);
}
// #Override public void onLoadResource(WebView view, String url) { System.out.println("!!!!!!!onLoadResource" + webView.getProgress()); if(webView.getProgress() == 100 ) webView.setVisibility(View.VISIBLE);}
});
//webView.setWebChromeClient(new WebChromeClient());
// load the customURL with the URL of the page you want to display
String pageURL = "file:///android_asset/videotag.html";
webView.loadUrl(pageURL);
//webView.setVisibility(View.VISIBLE);
//webView.setPublicationId(publisherIdForNativeAds);
//webView.loadAd();
}
Here is an xml file for activity.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<Button
android:id="#+id/showInlineVideo"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_centerHorizontal="true"
android:onClick="onShowInlineVideoButton"
android:text="#string/showInlineVideoButtonLabel"
android:textSize="14sp" />
<WebView
android:id="#+id/inlineVideo"
android:layout_width="300dp"
android:layout_height="250dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
</RelativeLayout>
Here is an html file for video named as "videotag.html"
<!DOCTYPE html>
<html>
<body>
<a href="http://www.globe.com.ph/mylifestyleplan" target="_bla">
<video id="video" controls preload="metadata" autoplay buffered height="245" width="335" webkit-playsinline="webkit-playsinline" class="videoPlayer">
<source src="https://s3.amazonaws.com/silverpushcdn/debTest/videoplayback.mp4" type='video/mp4' />
</video>
</a>
</body>
</html>
Now please help me that what should I do so that WebView only visible when video is ready to start, until it will be remain invisible.
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
public class Settings_Menu extends Activity {
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_menu);
TurnSoundOff();
}
private void TurnSoundOff() {
final CheckBox TurnSoundOff= (CheckBox) findViewById(R.id.StartupsoundoffBox);
TurnSoundOff.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (TurnSoundOff.isChecked()){
mp = MediaPlayer.create(MainActivity.class, R.raw.soundfile); //errors at .create since I can't use a class
mp.stop();
}else{
mp = MediaPlayer.create(MainActivity.class, R.raw.soundfile);
mp.start();
}
}});
}
}
Here is my code, i'm just trying to shutoff or turn on a designated audio file from when the app opens. I have the Checkbox or toggle button in another activity. I'm using media player and some what new to android coding thanks for reading. I setup a settings action from tapping overflow then the settings button to go to activity and I want the audio shutoff or back on in the MainActivity.xml when the check is click from the settings activity. thanks again for reading and help in advance. It errors at .create since I can't use a class
You have to do this using shared preferences . It is very simple.. Instead of making an activity make a preference screen.. Follow these steps..:-
1) Go to resource folder.
2) make a new folder called 'xml'.
3) In xml folder you created make a xml file called 'prefs.xml'.
in that sdd the following code..:-
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<CheckBoxPreference
android:defaultValue="false"
android:key="music"
android:summary="Tick to listen the music"
android:title="Intro Music" >
</CheckBoxPreference>
</PreferenceScreen>
now go to ur activity that plays the song..
ourSong = MediaPlayer.create(Splash.this, R.raw.splash_sound);
SharedPreferences getPrefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
boolean music = getPrefs.getBoolean("music", true);
if (music == true)
ourSong.start();
Thread timer = new Thread() {
public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
}
}
};
timer.start();
this thread is used for the timer of your activity.. if u dnt want any timer delete the thread.. the value in the sleep(****) is the time in miliseconds.
add this function also to stop the song after the activity is changed..
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
ourSong.release();
}
To get the overflow menu :-
1)make a new folder called menu
2)make a xml file.. add the following code.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:title="Preferences"
android:id="#+id/preferences" />
<item android:title="Exit"
android:id="#+id/exit" />
</menu>
In you actvity add the following code..So that prefernece could be called
#Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
MenuInflater blowUp = getMenuInflater();
blowUp.inflate(R.menu.cool_menu, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.preferences:
Intent b = new Intent("com.example.code.PREFS");
//instead of 'com.example.code' write your package name
startActivity(b);
break;
case R.id.exit:
finish();
break;
}
return false;
}
And in the end make a class called Prefs and add the following code..
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class Prefs extends PreferenceActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
}
}
Finally add the class in the manifest.. code for that..
<activity
android:name="com.example.code.Prefs"
android:label="Preferences" >
<intent-filter>
<action android:name="com.example.code.PREFS" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
your action name should be same as u mentioned in the intent in onMenuItemSelected()...
This would do the trick... :) Peace...