Customizing Android BluetoothLeGatt example and send data via BLE - java

I have to say at first that i am new to android programming. I am trying to send simple data (a short string) to a BLE peripheral device via Android. Therefore i customized the BluetoothLeGatt example from
http://developer.android.com/samples/BluetoothLeGatt/project.html
I replaced the Gatt Services List in the gatt_services_characteristics.xml with a text field for incoming data and below a EditText and a "send" button. The code is the following:
<TextView android:id="#+id/gatt_services_list"
android:layout_width="match_parent"
android:layout_height="250dp" />
<EditText android:id="#+id/sendText"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_margin="10dp"
android:layout_below="#id/gatt_services_list"/>
<Button
android:id="#+id/sendButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="SEND"
android:onClick="sendData"/>
I also commented out the function displayGattServices(List gattServices) in DeviceControlActivity.java and wrote a function for the button click as below:
public void sendData(View v) {
value = textField.getText().toString();
byte [] strBytes = value.getBytes();
mGattServicesList.setText(text + "\n>" + value);
text = text + "\n>" + value;
clearUI();
}
I now want to implement a simple way to send the data typed in the EditText. The data just shall be shown in a terminal.
I searched for a solution, but i didn't fully understand the concept of the Gatt Characteristic which i am afraid i have to use for this. I am programming with Android Studio 1.4.1 and using API 18 and higher.
How can i send the data in an easy way?
Thanks in advance

Android BluetoothLeGatt example already customized to Send and Receive via UART. See
https://github.com/danasf/hm10-android-arduino

Related

How do I set videopath for UDP stream using vitamio?

I'm trying to get a UDP stream from a GoPro camera.
https://github.com/KonradIT/GoProStream
I'm redoing this python code in android studio using vitamio.
But for some reason, as soon as I set the path, it crashes
_myVideoView.setVideoPath("udp://#10.5.5.100:8554");
But if I remove it, the app can launch but of course there is no video.
If someone encountered the same issue and found a solution, that would help me.
_myVideoView.setVideoPath("udp://#10.5.5.100:8554");
_myVideoView.setVideoQuality(MediaPlayer.VIDEOQUALITY_HIGH);
_myVideoView.setBufferSize(2048);
_myVideoView.requestFocus();
_myVideoView.setMediaController(new MediaController(this));
_myVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
// optional need Vitamio 4.0
mediaPlayer.setPlaybackSpeed(1.0f);
}
});
_myVideoView.start();
I have done that for onCreate :
if(!io.vov.vitamio.LibsChecker.checkVitamioLibs(this)){
return;
}
Vitamio.initialize(this);
the videoview :
<io.vov.vitamio.widget.VideoView
android:id="#+id/VideoView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="50dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="50dp"
android:layout_marginBottom="50dp"
android:visibility="visible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/imageButtonLeft"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/WebView"
tools:visibility="visible" />
and the build graddle :
implementation project(path: ':vitamio')
ps : I've tried to put the compile line in graddle, but it can't find the method compile and the implement line seem to work just fine.
ps2 : I just tried but even http link from YouTube doesn't work, I've definitely made a mistake but dunno where
Found the solution...
I was just importing the project but I didn't build it beforehand
So there was no way it could work.
But I gave up later for other reasons and I would recommend lib vlc instead of vitamio for displaying video from udp streams.

creating android library from fragment [duplicate]

This question already has answers here:
how to get a fragment added in an XML layout
(5 answers)
Closed last year.
i'm having a fragment that i want to use it as a library in other projects.
i created a library module and copy-paste all my fragment code and resources to library mode and then to use that library module i'm writing the following code in activity's xml
<androidx.fragment.app.FragmentContainerView
android:id="#+id/fragmentContainerView"
android:name="com.dhirunand.meter.MeterFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
and in java file
MeterFragment meterFragment = new MeterFragment();
String selectedNumber = meterFragment.getSelectedNumber();
visually library mudule is working fine but i'm not able to fetch data from the library module
project github url https://github.com/dhirunand/meter--number-picker
when you are using new MeterFragment() line then you are creating NEW fragment, not using one attached to FragmentContainerView. this NEW one isn't visible on screen, its just created in memory, not shown (as you haven't posted attaching code), so getSelectedNumber() will return default value instead this set in MeterFragment attached to FragmentContainerView
you should obtain this "real" existing and visible instance from XML by
FragmentContainerView fcv = (FragmentContainerView) findViewById(R.id.fragmentContainerView);
MeterFragment meterFragment = (MeterFragment) fcv.getFragment();

How to get a list of addresses by a search without the map?

I'm trying to get a list of addresses by searching an address in an editText, using Google Maps API.
For example, if I'm searching for an address in the editText at the top of the screen, below it, there will be a list of addresses that you can choose.
I don't need the map part of it, just the results, and the search box.
There is the option of using the PlaceAutocompleteFragment - when I first added it, I had no billing account so you should be good:
Add it on the XML
<fragment
android:id="#+id/place_autocomplete_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
/>
Use PlaceSelectionListener:
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
Log.i(TAG, "Place: " + place.getName());
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i(TAG, "An error occurred: " + status);
}
});
Note from the documentation:
The Google Places API requires API level 12 or higher for the support of PlaceAutocompleteFragment objects. If you are targeting an application earlier than API level 12, you can access the same functionality through the SupportPlaceAutocompleteFragment class. You must also include the Android v4 Support Library.
First you need a component, something like AutoCompleteTextView.
Second Google has a documentations about autosuggestion address. It is so simple, register, create an api key and so on. Here is a link to doc.
Logic: User press type a text, component fired a callback onTextChanged and you make a request to get suggestion list, after show a received list to user.

Why I can't enforce EditTextPreference to take just numbers?

GOAL: Use EditTextPreference to take a number input from an user.
PROBLEM: I'm using support.v7.preference and, from what I've understood, this library bring problems to creates a custom DialogPreference (HowTo use support.v7.preference with AppCompat and potential drawbacks). Anyway I tried to create a NumberPickerPreference extending DialogPreference but I got ClassCastException.
Also I found another approach: programmatically set the input type of an EditTextPreference object like below:
EditTextPreference pref = (EditTextPreference) findPreference("pref_edit_text");
if (pref != null) {
pref.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
}
No way, I always get a ClassCastException .
Last approach I tried : modify the xml
android:inputType="numberDecimal"
android:digits="0123456789"
or android:numeric="integer"
No way again, on the Dialog I get the full keyboard, so the user can write everything.
Is there a way to properly enforce EditTextReference to take just number input?
You can do it by adding android: inputType = "numberPassword" to your XML file
Then you can set your custom keyboard programmatically in your java like this:
yourEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
The next thing you could do is to create a custom class:
private class YourNumericKeyboardMethod extends PasswordTransformationMethod {
#Override
public CharSequence getTransformation(CharSequence source, View view) {
return source;
}
}
The last step is to implement it to your EditText in order to make it display only the numbers:
yourEditText.setTransformationMethod(new YourNumericKeyboardMethod());
After all this steps you should get a keyboard that has only numbers from 0 to 9 on it
Try one of these:
android:inputType="numberSigned"
android:inputType="phone"
EDIT:
android:inputType="numberDecimal|numberSigned"
android:digits="0123456789"
EDIT:
There´s this lib that is supposed to make it work, if you´re willing to try:
https://github.com/Gericop/Android-Support-Preference-V7-Fix
Reading their github page you can find examples of custom inputs and their example code that looks similar to what you are doing now:
"The sample app shows an example of setting (via XML) and querying (programmatically) the input type of the EditTextPreference:
<EditTextPreference
android:inputType="phone"
android:key="edit_text_test" />
EditTextPreference etPref = (EditTextPreference) findPreference("edit_text_test");
if (etPref != null) {
int inputType = etPref.getEditText().getInputType();
// do something with inputType
}
Try to set inputType as the number.
android:inputType="number"

Android - SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length

I have the following layout (virtually empty):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/set_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:contentDescription="content desc"
android:orientation="vertical" >
<TextView android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />
</LinearLayout>
The Activity class contains the following:
public class TestActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
}
}
When I run this on my mobile device I get the following error:
SpannableStringBuilder
SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
I have tried this with and without the TextView and the error still remains, I must be doing something fundamentally wrong for such a basic layout to cause this.
Does anyone have any ideas on how I can get this to load without the error?
I have run into the same error entries in LogCat. In my case it's caused by the 3rd party keyboard I am using. When I change it back to Android keyboard, the error entry does not show up any more.
Because the error you're getting is not related to an EditText, then it's not related to your keyboard.
The errors you are getting are not a result of your code; you probably are testing on a Samsung device that has Samsung's TouchWiz.
I had the same errors, then I tested on a Nexus S (also by Samsung, but pure Android OS without TouchWiz) and I didn't get this error.
So, in your case, just ignore these errors while testing on a device! :)
Looking at your code, I'm not sure why you're getting that error, but I had this same error but with EditText fields.
Changing android:inputType="text" (or any of the other inputType text variations) to android:inputType="textNoSuggestions" (or android:inputType="textEmailAddress|textNoSuggestions", for example) fixed it for me.
You can also set this in Code with something like
mInputField.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
Looks like Android assumes by default that EditText fields will have suggestions. When they don't, it errors. Not 100% confident in that explanation, but the above mentioned changes fixed it for me.
http://developer.android.com/reference/android/text/Spanned.html#SPAN_EXCLUSIVE_EXCLUSIVE
Hope this helps!
On your android phone go to:
settings -> application manager -> all -> samsung keyboard and then click on "clear cache"
(delete all data collected by this application).
Try using the default Android keyboard it will disappear
Make clear you have pass a value in your MainAcitivity for the following methods onCreateOptionsMenu and onCreate
In some cases, the developer deletes the "return super.onCreateOptionsMenu(menu)" statement and changed to "return true".
This worked for me...on every device
<EditText
android:maxLines="1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="15sp"
android:layout_centerVertical="true"
android:textColor="#000"
android:id="#+id/input_search"
android:background="#null"
android:inputType="text"
android:hint="Enter Address, City or Zip Code"
android:imeOptions="actionSearch"
/>
In Java code:
mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
if(actionId == EditorInfo.IME_ACTION_SEARCH
|| actionId == EditorInfo.IME_ACTION_DONE
|| keyEvent.getAction() == KeyEvent.ACTION_DOWN
|| keyEvent.getAction() == KeyEvent.KEYCODE_ENTER){
//execute our method for searching
}
return false;
}
});
I had the same warning and found that removing an unused #id got rid of the warning. For me it was obvious as the #id was associated with a growing list of textViews linked to a database, so there was a warning for each entry.
Masood Moshref is right, this error occur because the option menu of Menu is not well prepared by lacking "return super.onCreateOptionsMenu(menu)" in onCreate() method.
To try to debug this error, first go to your android terminal / console and execute this command:
ps | grep THE_ERROR_PID_YOU_GET_(IT_IS_A_NUMBER)
then if the output comes out as your app... it is your app causing the error. Try to look for empty Strings that you pass into the layout.
I had this exact same problem and it was my fault as I was passing an empty String into my layout. After changing the "" to " " this error went away.
If you don't get your app from the console output, then it is something else causing it (probably, as others said, the android keyboard)
I have faced the same issue. I almost wasted almost couple of weeks to resolved this issue.
Finally I had on doubt on myself and tried to create another project by copy and paste some startup files like SplashScreen & LoginScreen.
But with the same code still i was getting SPAN_EXCLUSIVE_EXCLUSIVE.
Then i have removed the handler code from splash screen and tried again and Wow its working.
I am not getting SPAN_EXCLUSIVE_EXCLUSIVE issue in logcat.
I wondering, why it is? till the time did not get any other solution but by removing handler from splash screen it is working.
Try and update here if it is resolved or not.
Check if you have any element such as button or text view duplicated (copied twice) in the screen where this encounters. I did this unnoticed and had to face the same issue.
I ran into this problem too when I copied some text from the Internet. My solution is to trim the text/remove formatting before doing any further processing.
I had the same problem but with a listView.... i solved it because i was using a wrong R.id.listView that list View needed to have a value, in my case it was strings that i saved on listView2... so the right code was R.id.listView2
I had the same problem then i fixed it by following code!
text = (EditText)findViewById(R.id.TextVoiceeditText);
text.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
this error also occurs due to changed API URL. try hitting the URL you are using in postman and c if it's working properly.
rechecking the APIs solved my problem
try avoiding use of view in xml design.I too had the same probem but when I removed the view. its worked perfectly.
like example:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username"
android:inputType="number"
android:textColor="#fff" />
<view
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#f9d7db" />
also check and try changing by trial and error android:inputType="number" to android:inputType="text" or better not using it if not required .Sometimes keyboard stuck and gets error in some of the devices.
In my case, the EditText fields with inputType as text / textCapCharacters were casing this error. I noticed this in my logcat whenever I used backspace to completely remove the text typed in any of these fields.
The solution which worked for me was to change the inputType of those fields to textNoSuggestions as this was the most suited type and didn't give me any unwanted errors anymore.
in my case i click on recent apps shortcut on my cell phone and close all apps. This solution always work for me, because this error not related to code.
**DONT PUT SET TEXT IN TEXT WATCHER**etSearch.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable) {
visibleResultList = false
if (s.toString().length != 0) {
getSearchSuggetion(no_of_rec, 0, s.toString())
} else {
// etSearch.setText("")
}
Log.e("text_change","============"+s.toString())
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
}
})
To solve this problem just add android:usesCleartextTraffic="true" in your AndroidManifest.xml file which is at ..\app\src\main\AndroidManifest.xml just like bellow...

Categories

Resources