How can I disable PICK_CONTACT_REQUEST - android-studio

I am working on branding a pre-packaged application, and it has a contact selector option that I need to disable since it serves no purpose for us. It's for a single user search using their personal address. I have found an article on how to add it here: http://apiminer.org/doc/guide/components/activities.html
They listed the code as this:
private void pickContact() {
// Create an intent to "pick" a contact, as defined by the content provider URI
Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// If the request went well (OK) and the request was PICK_CONTACT_REQUEST
if (resultCode == Activity.RESULT_OK && requestCode == PICK_CONTACT_REQUEST) {
// Perform a query to the contact's content provider for the contact's name
Cursor cursor = getContentResolver().query(data.getData(),
new String[] {Contacts.DISPLAY_NAME}, null, null, null);
if (cursor.moveToFirst()) { // True if the cursor is not empty
int columnIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME);
String name = cursor.getString(columnIndex);
// Do something with the selected contact's name...
}
}
}
I just want to disable this. I can remove the images from the folder that it is calling them from, but that still leaves an active corner. That would be poor usability to just leave it that way. I have tried just commenting and deleting these mentions from the code, and it just throws back 2-3 errors.
This is my HomeActivity.java file that displays the code:
package com.votinginfoproject.VotingInformationProject.activities;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.votinginfoproject.VotingInformationProject.R;
import com.votinginfoproject.VotingInformationProject.fragments.HomeFragment;
import com.votinginfoproject.VotingInformationProject.models.VIPApp;
import com.votinginfoproject.VotingInformationProject.models.VIPAppContext;
import com.votinginfoproject.VotingInformationProject.models.VoterInfo;
public class HomeActivity extends FragmentActivity implements HomeFragment.OnInteractionListener,
LoaderManager.LoaderCallbacks<Cursor> {
static final int PICK_CONTACT_REQUEST = 1;
VIPApp app;
Uri contactUri;
EditText addressView;
LoaderManager loaderManager;
public String getSelectedParty() {
return selectedParty;
}
public void setSelectedParty(String selectedParty) {
this.selectedParty = selectedParty;
app.setSelectedParty(selectedParty);
}
String selectedParty;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
app = new VIPAppContext((VIPApp) getApplicationContext()).getVIPApp();
loaderManager = getLoaderManager();
selectedParty = "";
contactUri = null;
addressView = (EditText)findViewById(R.id.home_edittext_address);
// Get analytics tracker (should auto-report)
app.getTracker(VIPApp.TrackerName.APP_TRACKER);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
protected void onStop() {
super.onStop();
//Stop analytics tracking
GoogleAnalytics.getInstance(this).reportActivityStop(this);
}
#Override
protected void onStart() {
super.onStart();
//Get an Analytics tracker to report app starts, uncaught exceptions, etc.
GoogleAnalytics.getInstance(this).reportActivityStart(this);
}
#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();
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
public void onGoButtonPressed(View view) {
Intent intent = new Intent(this, VIPTabBarActivity.class);
startActivity(intent);
}
public void onSelectContactButtonPressed(View view) {
// contact picker intent to return an address; will only show contacts that have an address
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// The user picked a contact.
// The Intent's data Uri identifies which contact was selected.
// Get the URI that points to the selected contact
contactUri = data.getData();
// restart loader, if a contact was already selected
loaderManager.destroyLoader(PICK_CONTACT_REQUEST);
// start async query to get contact info
loaderManager.initLoader(PICK_CONTACT_REQUEST, null, this);
} else {
// PASS (user didn't pick an address)
}
}
}
public void searchedAddress(VoterInfo voterInfo) {
// set VoterInfo object on app singleton
app.setVoterInfo(voterInfo, selectedParty);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
if (contactUri == null) {
return null;
}
String[] projection = { ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS };
return new CursorLoader(this, contactUri, projection, null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (data.getCount() > 0) {
data.moveToFirst();
// get result with single column, named data1
String address = data.getString(0);
Log.d("HomeActivity", "Got cursor result: " + address);
// set address found in view
addressView.setText(address);
// initate search with new address
HomeFragment myFragment = (HomeFragment)getSupportFragmentManager().findFragmentById(R.id.home_fragment);
myFragment.makeElectionQuery();
} else {
Log.e("HomeActivity", "Cursor got no results!");
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// PASS
}
}
Does anyone have a solution for this?

Related

Upload Text and Multiple Images to Firebase - Android Studio

How do you upload multiple images to firebase with a text file? I can upload the one image file find but once I add the second fileRef for the second image in the saveVehicle area it doesn't upload anything at all.
I have tried putting an if statement before the Storage Reference and still nothing.
EDIT: In the "private void saveVehicle()" section when I put in the code for "fileRef2" to save a secondary picture nothing happens. It does not upload to Firebase. Without "fileRef2" code the first image and texts saves fine.
How do I save multiple images into one file?
Here is my code:
'''
package com.example.a7kvehicleinventoryapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NavUtils;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.util.ArrayList;
import java.util.UUID;
public class EditorActivity extends AppCompatActivity {
/** EditText field to enter the vehicle attributes */
private EditText mNameEditText;
private ImageButton mPic1Image;
private ImageButton mPic2Image;
private ImageButton mPic3Image;
private ImageButton mPic4Image;
private Uri mImageUri1;
private Uri mImageUri2;
private Uri mImageUri3;
private Uri mImageUri4;
private FirebaseDatabase db = FirebaseDatabase.getInstance();
private DatabaseReference root = db.getReference("Vehicles");
private FirebaseStorage mStorage = FirebaseStorage.getInstance();
private StorageReference mStorageReference = mStorage.getReference();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editor);
// Find all relevant views that we will need to read user input from
mNameEditText = findViewById(R.id.edit_vehicle_customer_name);
mPic1Image = findViewById(R.id.edit_vehicle_pic_1);
mPic2Image = findViewById(R.id.edit_vehicle_pic_2);
mPic3Image = findViewById(R.id.edit_vehicle_pic_3);
mPic4Image = findViewById(R.id.edit_vehicle_pic_4);
mPic1Image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
choosePicture1();
}
});
mPic2Image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
choosePicture2();
}
});
mPic3Image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
choosePicture3();
}
});
mPic4Image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
choosePicture4();
}
});
}
private void choosePicture1() {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, 1);
}
private void choosePicture2() {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, 2);
}
private void choosePicture3() {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, 3);
}
private void choosePicture4() {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, 4);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
mImageUri1 = data.getData();
mPic1Image.setImageURI(mImageUri1);
}
if(requestCode == 2 && resultCode == RESULT_OK && data != null && data.getData() != null) {
mImageUri2 = data.getData();
mPic2Image.setImageURI(mImageUri2);
}
if(requestCode == 3 && resultCode == RESULT_OK && data != null && data.getData() != null) {
mImageUri3 = data.getData();
mPic3Image.setImageURI(mImageUri3);
}
if(requestCode == 4 && resultCode == RESULT_OK && data != null && data.getData() != null) {
mImageUri4 = data.getData();
mPic4Image.setImageURI(mImageUri4);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu options from the res/menu/menu_editor.xml file.
// This adds menu items to the app bar.
getMenuInflater().inflate(R.menu.menu_editor, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// User clicked on a menu option in the app bar overflow menu
switch (item.getItemId()) {
// Respond to a click on the "Save" menu option
case R.id.action_save:
// Save vehicle to database
saveVehicle();
// Exit activity start new
startActivity(new Intent(EditorActivity.this, InventoryActivity.class));
return true;
// Respond to a click on the "Delete" menu option
case R.id.action_delete:
// Pop up confirmation dialog for deletion
//showDeleteConfirmationDialog();
return true;
// Respond to a click on the "Delete" menu option
case R.id.action_email:
// Pop up confirmation dialog for deletion
//showEmailConfirmationDialog();
return true;
// Respond to a click on the "Up" arrow button in the app bar
case android.R.id.home:
NavUtils.navigateUpFromSameTask(EditorActivity.this);
return true;
}
return super.onOptionsItemSelected(item);
}
private void saveVehicle() {
final ProgressDialog pd = new ProgressDialog(this);
pd.setTitle("Uploading");
pd.show();
final String nameString = mNameEditText.getText().toString().trim();
final DatabaseReference db = root.push();
StorageReference fileRef1 = mStorageReference.child("Images").child(mImageUri1.getLastPathSegment());
StorageReference fileRef2 = mStorageReference.child("Images").child(mImageUri2.getLastPathSegment());
fileRef1.putFile(mImageUri1).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileRef1.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
db.child("name").setValue(nameString);
db.child("image1").setValue(uri.toString());
pd.dismiss();
Toast.makeText(EditorActivity.this, "Uploaded Successfully", Toast.LENGTH_SHORT).show();
}
});
}
});
fileRef2.putFile(mImageUri2).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileRef2.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
db.child("image2").setValue(uri.toString());
pd.dismiss();
Toast.makeText(EditorActivity.this, "Uploaded Successfully", Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
'''

How to store mac address

I'm writing an App with login and register, it works but I want to add something. Is it possible, when a user register his datas, to get directly from his phone the Mac Address and store it together the other datas?
For example, he has to insert name, user, password and email, when he clicks on register in the database there are all this datas and the macaddress of his phone too.
This is my RegisterActivity.java:
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
/**
* Created by amardeep on 10/26/2017.
*/
public class RegisterActivity extends AppCompatActivity {
//Declaration EditTexts
EditText editTextUserName;
EditText editTextEmail;
EditText editTextPassword;
//Declaration TextInputLayout
TextInputLayout textInputLayoutUserName;
TextInputLayout textInputLayoutEmail;
TextInputLayout textInputLayoutPassword;
//Declaration Button
Button buttonRegister;
//Declaration SqliteHelper
SqliteHelper sqliteHelper;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
sqliteHelper = new SqliteHelper(this);
initTextViewLogin();
initViews();
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (validate()) {
String UserName = editTextUserName.getText().toString();
String Email = editTextEmail.getText().toString();
String Password = editTextPassword.getText().toString();
//Check in the database is there any user associated with this email
if (!sqliteHelper.isEmailExists(Email)) {
//Email does not exist now add new user to database
sqliteHelper.addUser(new User(null, UserName, Email, Password));
Snackbar.make(buttonRegister, "User created successfully! Please Login ", Snackbar.LENGTH_LONG).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
finish();
}
}, Snackbar.LENGTH_LONG);
}else {
//Email exists with email input provided so show error user already exist
Snackbar.make(buttonRegister, "User already exists with same email ", Snackbar.LENGTH_LONG).show();
}
}
}
});
}
//this method used to set Login TextView click event
private void initTextViewLogin() {
TextView textViewLogin = (TextView) findViewById(R.id.textViewLogin);
textViewLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
//this method is used to connect XML views to its Objects
private void initViews() {
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
editTextUserName = (EditText) findViewById(R.id.editTextUserName);
textInputLayoutEmail = (TextInputLayout) findViewById(R.id.textInputLayoutEmail);
textInputLayoutPassword = (TextInputLayout) findViewById(R.id.textInputLayoutPassword);
textInputLayoutUserName = (TextInputLayout) findViewById(R.id.textInputLayoutUserName);
buttonRegister = (Button) findViewById(R.id.buttonRegister);
}
//This method is used to validate input given by user
public boolean validate() {
boolean valid = false;
//Get values from EditText fields
String UserName = editTextUserName.getText().toString();
String Email = editTextEmail.getText().toString();
String Password = editTextPassword.getText().toString();
//Handling validation for UserName field
if (UserName.isEmpty()) {
valid = false;
textInputLayoutUserName.setError("Please enter valid username!");
} else {
if (UserName.length() > 5) {
valid = true;
textInputLayoutUserName.setError(null);
} else {
valid = false;
textInputLayoutUserName.setError("Username is to short!");
}
}
//Handling validation for Email field
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
valid = false;
textInputLayoutEmail.setError("Please enter valid email!");
} else {
valid = true;
textInputLayoutEmail.setError(null);
}
//Handling validation for Password field
if (Password.isEmpty()) {
valid = false;
textInputLayoutPassword.setError("Please enter valid password!");
} else {
if (Password.length() > 5) {
valid = true;
textInputLayoutPassword.setError(null);
} else {
valid = false;
textInputLayoutPassword.setError("Password is to short!");
}
}
return valid;
}
}
Thank you very much!

how to add images to dialog flow chat bot in android studio

`I'm using dialog flow for chat bot in my app. I've tried to put some images for chat bot to send it to user. It works fine and appears in dialog flow simulator but it doesn't work and nothing appear in my app. Any help? I'm using android studio. I've tried to change the code so many time the app works but the same problem
The image shows the result in my app and the result in dialog flow simulator
image to understand
package com.example.lmdinalarbi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.github.bassaer.chatmessageview.model.Message;
import com.github.bassaer.chatmessageview.view.ChatView;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import ai.api.AIServiceException;
import ai.api.RequestExtras;
import ai.api.android.AIConfiguration;
import ai.api.android.AIDataService;
import ai.api.android.GsonFactory;
import ai.api.model.AIContext;
import ai.api.model.AIError;
import ai.api.model.AIEvent;
import ai.api.model.AIRequest;
import ai.api.model.AIResponse;
import ai.api.model.Metadata;
import ai.api.model.Result;
import ai.api.model.Status;
public class chatbotamali extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,View.OnClickListener
{
public static final String TAG = MainActivity.class.getName();
private Gson gson = GsonFactory.getGson();
private AIDataService aiDataService;
private ChatView chatView;
private User myAccount;
private User amali;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chatbotamali);
initChatView();
//Language, Dialogflow Client access token
final LanguageConfig config = new LanguageConfig("JavaScript", "239001d3094444b390e30d3e3ea6832bwwww"
,
AIConfiguration.SupportedLanguages.English,
AIConfiguration.RecognitionEngine.System
);
initService(config);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
getSupportActionBar().setTitle("AM ALI");
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onClick(View v) {
//new message
final Message message = new Message.Builder()
.setUser(myAccount)
.setRight(true)
.setText(chatView.getInputText())
.hideIcon(true)
.build();
//Set to chat view
chatView.send(message);
sendRequest(chatView.getInputText());
//Reset edit text
chatView.setInputText("");
}
private void sendRequest(String text) {
Log.d(TAG, text);
final String queryString = String.valueOf(text);
final String eventString = null;
final String contextString = null;
if (TextUtils.isEmpty(queryString) && TextUtils.isEmpty(eventString)) {
onError(new AIError(getString(R.string.non_empty_query)));
return;
}
new AiTask().execute(queryString, eventString, contextString);
}
public class AiTask extends AsyncTask<String, Void, AIResponse> {
private AIError aiError;
#Override
protected AIResponse doInBackground(final String... params) {
final AIRequest request = new AIRequest();
String query = params[0];
String event = params[1];
String context = params[2];
if (!TextUtils.isEmpty(query)){
request.setQuery(query);
}
if (!TextUtils.isEmpty(event)){
request.setEvent(new AIEvent(event));
}
RequestExtras requestExtras = null;
if (!TextUtils.isEmpty(context)) {
final List<AIContext> contexts = Collections.singletonList(new AIContext(context));
requestExtras = new RequestExtras(contexts, null);
}
try {
return aiDataService.request(request, requestExtras);
} catch (final AIServiceException e) {
aiError = new AIError(e);
return null;
}
}
#Override
protected void onPostExecute(final AIResponse response) {
if (response != null) {
onResult(response);
} else {
onError(aiError);
}
}
}
private void onResult(final AIResponse response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// Variables
gson.toJson(response);
final Status status = response.getStatus();
final Result result = response.getResult();
final String speech = result.getFulfillment().getSpeech();
final Metadata metadata = result.getMetadata();
final HashMap<String, JsonElement> params = result.getParameters();
// Logging
Log.d(TAG, "onResult");
Log.i(TAG, "Received success response");
Log.i(TAG, "Status code: " + status.getCode());
Log.i(TAG, "Status type: " + status.getErrorType());
Log.i(TAG, "Resolved query: " + result.getResolvedQuery());
Log.i(TAG, "Action: " + result.getAction());
Log.i(TAG, "Speech: " + speech);
if (metadata != null) {
Log.i(TAG, "Intent id: " + metadata.getIntentId());
Log.i(TAG, "Intent name: " + metadata.getIntentName());
}
if (params != null && !params.isEmpty()) {
Log.i(TAG, "Parameters: ");
for (final Map.Entry<String, JsonElement> entry : params.entrySet()) {
Log.i(TAG, String.format("%s: %s",
entry.getKey(), entry.getValue().toString()));
}
}
//Update view to bot says
final Message receivedMessage = new Message.Builder()
.setUser(amali)
.setRight(false)
.setText(speech)
.build();
chatView.receive(receivedMessage);
}
});
}
private void onError(final AIError error) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e(TAG,error.toString());
}
});
}
private void initChatView() {
int myId = 0;
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.tunis);
String myName = "wledelmdina";
myAccount = new User(myId, myName, icon);
int botId = 1;
String botName = "amali";
amali = new User(botId, botName, icon);
chatView = findViewById(R.id.chat_view);
chatView.setRightBubbleColor(ContextCompat.getColor(this, R.color.green500));
chatView.setLeftBubbleColor(Color.RED);
chatView.setBackgroundColor(ContextCompat.getColor(this, R.color.aidialog_background));
chatView.setSendButtonColor(ContextCompat.getColor(this, R.color.lightBlue500));
chatView.setSendIcon(R.drawable.ic_action_send);
chatView.setRightMessageTextColor(Color.WHITE);
chatView.setLeftMessageTextColor(Color.WHITE);
chatView.setUsernameTextColor(Color.BLACK);
chatView.setSendTimeTextColor(Color.GRAY);
chatView.setDateSeparatorColor(Color.GRAY);
chatView.setInputTextHint("new message...");
chatView.setMessageMarginTop(5);
chatView.setMessageMarginBottom(5);
chatView.setOnClickSendButtonListener(this);
}
private void initService(final LanguageConfig languageConfig) {
final AIConfiguration.SupportedLanguages lang =
AIConfiguration.SupportedLanguages.fromLanguageTag(languageConfig.getLanguageCode());
final AIConfiguration config = new AIConfiguration(languageConfig.getAccessToken(),
lang,
AIConfiguration.RecognitionEngine.System);
aiDataService = new AIDataService(this, config);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
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
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(#NotNull MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.Eldmina) {
Intent intent=new Intent(this,MainActivity.class);
Bundle bundle=new Bundle();
bundle.putString("VALUE_SEND","this data Send");
startActivity(intent);
// Handle the camera action
} else if (id == R.id.souk) {
Intent intent=new Intent(this,elsoukmenu.class);
Bundle bundle=new Bundle();
bundle.putString("VALUE_SEND","this data Send");
startActivity(intent);
} else if (id == R.id.wled) {
Intent intent=new Intent(this,wledelmdina.class);
Bundle bundle=new Bundle();
bundle.putString("VALUE_SEND","this data Send");
startActivity(intent);
} else if (id == R.id.profile) {
}
else if (id == R.id.about) {
Intent intent=new Intent(this,aboutuss.class);
Bundle bundle=new Bundle();
bundle.putString("VALUE_SEND","this data Send");
startActivity(intent);
}
else if (id == R.id.report) {
Intent intent=new Intent(this,wledelmdinamenu.class);
Bundle bundle=new Bundle();
bundle.putString("VALUE_SEND","this data Send");
startActivity(intent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
build

startLeScan and stopLeScan is depreciated in API level 24? How to scan a BLE device?

I'm developing a project with a BLE device(RN-4871 - Bluetooth 4.2 Low-Energy module) connected to the target board.
RN-4871 device is visible and connected to BLE scanner App downloaded from Play Store.
I'm using the snippet downloaded from https://developer.android.com/samples/BluetoothLeGatt/project.html.
I just configured the project to Android Marshmallow(API>21) and used the above downloaded code.
I am using moto c plus(Nougat).
private LeDeviceListAdapter mLeDeviceListAdapter;
private BluetoothAdapter mBluetoothAdapter;
private void scanLeDevice(final boolean enable) {
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
invalidateOptionsMenu();
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
invalidateOptionsMenu();
}
But it shows startLeScan and stopLeScan are depreciated. So I am unable to scan the available devices.
Also I just used the below snippet used to connect exact device with UUID.
public static final ParcelUuid MY_UUID =
ParcelUuid.fromString("00002A05-0000-1000-8000-00805F9B34FB");
private void scanLeDevice(final boolean enable) {
if(enable){
ScanFilter aFilter = new ScanFilter.Builder()
.setServiceUuid(BluetoothLeService.MY_UUID).build();
ArrayList<ScanFilter> filters = new ArrayList<>();
filters.add(aFilter);
ScanSettings settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build();
mBluetoothLeScanner.startScan(filters, settings, (ScanCallback) mLeScanCallback);
}
}
this closes the app.
DeviceScanActivity.java
import android.app.Activity;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class DeviceScanActivity extends ListActivity {
private LeDeviceListAdapter mLeDeviceListAdapter;
private BluetoothAdapter mBluetoothAdapter;
private BluetoothLeScanner mBluetoothLeScanner;
private boolean mScanning;
private Handler mHandler;
private static final int REQUEST_ENABLE_BT = 1;
// Stops scanning after 10 seconds.
private static final long SCAN_PERIOD = 10000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setTitle(R.string.title_devices);
mHandler = new Handler();
// Use this check to determine whether BLE is supported on the device. Then you can
// selectively disable BLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
}
// Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
// Checks if Bluetooth is supported on the device.
if (mBluetoothAdapter == null) {
Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
finish();
return;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
if (!mScanning) {
menu.findItem(R.id.menu_stop).setVisible(false);
menu.findItem(R.id.menu_scan).setVisible(true);
menu.findItem(R.id.menu_refresh).setActionView(null);
} else {
menu.findItem(R.id.menu_stop).setVisible(true);
menu.findItem(R.id.menu_scan).setVisible(false);
menu.findItem(R.id.menu_refresh).setActionView(
R.layout.actionbar_indeterminate_progress);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_scan:
mLeDeviceListAdapter.clear();
scanLeDevice(true);
break;
case R.id.menu_stop:
scanLeDevice(false);
break;
}
return true;
}
#Override
protected void onResume() {
super.onResume();
// Ensures Bluetooth is enabled on the device. If Bluetooth is not currently enabled,
// fire an intent to display a dialog asking the user to grant permission to enable it.
if (!mBluetoothAdapter.isEnabled()) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
// Initializes list view adapter.
mLeDeviceListAdapter = new LeDeviceListAdapter();
setListAdapter(mLeDeviceListAdapter);
scanLeDevice(true);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// User chose not to enable Bluetooth.
if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
finish();
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onPause() {
super.onPause();
scanLeDevice(false);
mLeDeviceListAdapter.clear();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
if (device == null) return;
final Intent intent = new Intent(this, DeviceControlActivity.class);
intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME, device.getName());
intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
if (mScanning) {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
mScanning = false;
}
startActivity(intent);
}
private void scanLeDevice(final boolean enable) {
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
invalidateOptionsMenu();
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
invalidateOptionsMenu();
}
// Adapter for holding devices found through scanning.
private class LeDeviceListAdapter extends BaseAdapter {
private ArrayList<BluetoothDevice> mLeDevices;
private LayoutInflater mInflator;
public LeDeviceListAdapter() {
super();
mLeDevices = new ArrayList<BluetoothDevice>();
mInflator = DeviceScanActivity.this.getLayoutInflater();
}
public void addDevice(BluetoothDevice device) {
if(!mLeDevices.contains(device)) {
mLeDevices.add(device);
}
}
public BluetoothDevice getDevice(int position) {
return mLeDevices.get(position);
}
public void clear() {
mLeDevices.clear();
}
#Override
public int getCount() {
return mLeDevices.size();
}
#Override
public Object getItem(int i) {
return mLeDevices.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
// General ListView optimization code.
if (view == null) {
view = mInflator.inflate(R.layout.listitem_device, null);
viewHolder = new ViewHolder();
viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address);
viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
BluetoothDevice device = mLeDevices.get(i);
final String deviceName = device.getName();
if (deviceName != null && deviceName.length() > 0)
viewHolder.deviceName.setText(deviceName);
else
viewHolder.deviceName.setText(R.string.unknown_device);
viewHolder.deviceAddress.setText(device.getAddress());
return view;
}
}
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mLeDeviceListAdapter.addDevice(device);
mLeDeviceListAdapter.notifyDataSetChanged();
}
});
}
};
static class ViewHolder {
TextView deviceName;
TextView deviceAddress;
}
}
How to connect RN-4871 ??
The code examples makes your question confusing.
In the last shown code example you already have a field mBluetoothLeScanner,
but you do not use it.
Just do:
// Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
mBluetoothLeScanner = mBluetoothAdapter.BluetoothLeScanner;
And int the rest of your code replace
mBluetoothAdapter.stopLeScan(mLeScanCallback)
and
mBluetoothAdapter.startLeScan(mLeScanCallback)
with
mBluetoothLeScanner.stopScan( mLeScanCallback)
and
mBluetoothLeScanner.startScan( mLeScanCallback)

JavaFX 2 TableView how to update cell when object is changed

I'm creating a TableView to show information regarding a list of custom objects (EntityEvents).
The table view must have 2 columns.
First column to show the corresponding EntityEvent's name.
The second column would display a button. The button text deppends on a property of the EntityEvent. If the property is ZERO, it would be "Create", otherwise "Edit".
I managed to do it all just fine, except that I can't find a way to update the TableView line when the corresponding EntityEvent object is changed.
Very Important: I can't change the EntityEvent class to use JavaFX properties, since they are not under my control. This class uses PropertyChangeSupport to notify listeners when the monitored property is changed.
Note:
I realize that adding new elements to the List would PROBABLY cause the TableView to repaint itself, but that is not what I need. I say PROBABLY because I've read about some bugs that affect this behavior.
I tried using this approach to force the repaint, by I couldn't make it work.
Does anyone knows how to do it?
Thanks very much.
Here is a reduced code example that illustrates the scenario:
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import javafx.application.Application;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.control.TableView;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Callback;
public class Main extends Application {
//=============================================================================================
public class EntityEvent {
private String m_Name;
private PropertyChangeSupport m_NamePCS = new PropertyChangeSupport(this);
private int m_ActionCounter;
private PropertyChangeSupport m_ActionCounterPCS = new PropertyChangeSupport(this);
public EntityEvent(String name, int actionCounter) {
m_Name = name;
m_ActionCounter = actionCounter;
}
public String getName() {
return m_Name;
}
public void setName(String name) {
String lastName = m_Name;
m_Name = name;
System.out.println("Name changed: " + lastName + " -> " + m_Name);
m_NamePCS.firePropertyChange("Name", lastName, m_Name);
}
public void addNameChangeListener(PropertyChangeListener listener) {
m_NamePCS.addPropertyChangeListener(listener);
}
public int getActionCounter() {
return m_ActionCounter;
}
public void setActionCounter(int actionCounter) {
int lastActionCounter = m_ActionCounter;
m_ActionCounter = actionCounter;
System.out.println(m_Name + ": ActionCounter changed: " + lastActionCounter + " -> " + m_ActionCounter);
m_ActionCounterPCS.firePropertyChange("ActionCounter", lastActionCounter, m_ActionCounter);
}
public void addActionCounterChangeListener(PropertyChangeListener listener) {
m_ActionCounterPCS.addPropertyChangeListener(listener);
}
}
//=============================================================================================
private class AddPersonCell extends TableCell<EntityEvent, String> {
Button m_Button = new Button("Undefined");
StackPane m_Padded = new StackPane();
AddPersonCell(final TableView<EntityEvent> table) {
m_Padded.setPadding(new Insets(3));
m_Padded.getChildren().add(m_Button);
m_Button.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent actionEvent) {
// Do something
}
});
}
#Override protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
setGraphic(m_Padded);
m_Button.setText(item);
}
}
}
//=============================================================================================
private ObservableList<EntityEvent> m_EventList;
//=============================================================================================
#SuppressWarnings("unchecked")
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Table View test.");
VBox container = new VBox();
m_EventList = FXCollections.observableArrayList(
new EntityEvent("Event 1", -1),
new EntityEvent("Event 2", 0),
new EntityEvent("Event 3", 1)
);
final TableView<EntityEvent> table = new TableView<EntityEvent>();
table.setItems(m_EventList);
TableColumn<EntityEvent, String> eventsColumn = new TableColumn<>("Events");
TableColumn<EntityEvent, String> actionCol = new TableColumn<>("Actions");
actionCol.setSortable(false);
eventsColumn.setCellValueFactory(new Callback<CellDataFeatures<EntityEvent, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<EntityEvent, String> p) {
EntityEvent event = p.getValue();
event.addActionCounterChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent event) {
// TODO: I'd like to update the table cell information.
}
});
return new ReadOnlyStringWrapper(event.getName());
}
});
actionCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<EntityEvent, String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(TableColumn.CellDataFeatures<EntityEvent, String> ev) {
String text = "NONE";
if(ev.getValue() != null) {
text = (ev.getValue().getActionCounter() != 0) ? "Edit" : "Create";
}
return new ReadOnlyStringWrapper(text);
}
});
// create a cell value factory with an add button for each row in the table.
actionCol.setCellFactory(new Callback<TableColumn<EntityEvent, String>, TableCell<EntityEvent, String>>() {
#Override
public TableCell<EntityEvent, String> call(TableColumn<EntityEvent, String> personBooleanTableColumn) {
return new AddPersonCell(table);
}
});
table.getColumns().setAll(eventsColumn, actionCol);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
// Add Resources Button
Button btnInc = new Button("+");
btnInc.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent ev) {
System.out.println("+ clicked.");
EntityEvent entityEvent = table.getSelectionModel().getSelectedItem();
if (entityEvent == null) {
System.out.println("No Event selected.");
return;
}
entityEvent.setActionCounter(entityEvent.getActionCounter() + 1);
// TODO: I expected the TableView to be updated since I modified the object.
}
});
// Add Resources Button
Button btnDec = new Button("-");
btnDec.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent ev) {
System.out.println("- clicked.");
EntityEvent entityEvent = table.getSelectionModel().getSelectedItem();
if (entityEvent == null) {
System.out.println("No Event selected.");
return;
}
entityEvent.setActionCounter(entityEvent.getActionCounter() - 1);
// TODO: I expected the TableView to be updated since I modified the object.
}
});
container.getChildren().add(table);
container.getChildren().add(btnInc);
container.getChildren().add(btnDec);
Scene scene = new Scene(container, 300, 600, Color.WHITE);
primaryStage.setScene(scene);
primaryStage.show();
}
//=============================================================================================
public Main() {
}
//=============================================================================================
public static void main(String[] args) {
launch(Main.class, args);
}
}
Try the javafx.beans.property.adapter classes, particularly JavaBeanStringProperty and JavaBeanIntegerProperty. I haven't used these, but I think you can do something like
TableColumn<EntityEvent, Integer> actionCol = new TableColumn<>("Actions");
actionCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<EntityEvent, Integer> ev) {
return new JavaBeanIntegerPropertyBuilder().bean(ev.getValue()).name("actionCounter").build();
});
// ...
public class AddPersonCell extends TableCell<EntityEvent, Integer>() {
final Button button = new Button();
public AddPersonCell() {
setPadding(new Insets(3));
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
button.setOnAction(...);
}
#Override
public void updateItem(Integer actionCounter, boolean empty) {
if (empty) {
setGraphic(null);
} else {
if (actionCounter.intValue()==0) {
button.setText("Create");
} else {
button.setText("Add");
}
setGraphic(button);
}
}
}
As I said, I haven't used the Java bean property adapter classes, but the idea is that they "translate" property change events to JavaFX change events. I just typed this in here without testing, but it should at least give you something to start with.
UPDATE: After a little experimenting, I don't think this approach will work if your EntityEvent is really set up the way you showed it in your code example. The standard Java beans bound properties pattern (which the JavaFX property adapters rely on) has a single property change listener and an addPropertyChangeListener(...) method. (The listeners can query the event to see which property changed.)
I think if you do
public class EntityEvent {
private String m_Name;
private PropertyChangeSupport pcs = new PropertyChangeSupport(this);
private int m_ActionCounter;
public EntityEvent(String name, int actionCounter) {
m_Name = name;
m_ActionCounter = actionCounter;
}
public String getName() {
return m_Name;
}
public void setName(String name) {
String lastName = m_Name;
m_Name = name;
System.out.println("Name changed: " + lastName + " -> " + m_Name);
pcs.firePropertyChange("name", lastName, m_Name);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
pcs.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
pcs.removePropertyChangeListener(listener);
}
public int getActionCounter() {
return m_ActionCounter;
}
public void setActionCounter(int actionCounter) {
int lastActionCounter = m_ActionCounter;
m_ActionCounter = actionCounter;
System.out.println(m_Name + ": ActionCounter changed: " + lastActionCounter + " -> " + m_ActionCounter);
pcs.firePropertyChange("ActionCounter", lastActionCounter, m_ActionCounter);
}
}
it will work with the adapter classes above. Obviously, if you have existing code calling the addActionChangeListener and addNameChangeListener methods you would want to keep those existing methods and the existing property change listeners, but I see no reason you can't have both.

Resources