Dialogflow Fulfillment: Fixing Chatbot Response - dialogflow-es

I am creating a chatbot for my final year project. I am using Dialogflow for it. It's going pretty good but, my chatbot doesn't say the conv.ask statements which are in the Fulfillment. It just repeats the same entity that I have used it for. These same statements will display in the Web Demo and Test Console provided on the Dialogflow website, but not on my app.
This is the Fulfillment code
const functions = require('firebase-functions');
const {dialogflow} = require('actions-on-google')
const Minerals_INTENT ='Mineral'
const Minerals_ENTITY ='Minerals'
const app = dialogflow()
app.intent( Minerals_INTENT , (conv) => {
const mineral_type = conv.parameters[Minerals_ENTITY];
if(mineral_type == "Calcium")
{
conv.ask("Sources: Green leafy vegetables, legumes, tofu, molasses,
sardines, okra, perch, trout, Chinese cabbage, rhubarb, sesame seeds")
}
else if(mineral_type == "Phosphorus")
{
conv.ask("Toxicity: Very rare. May result in soft tissue
calcification. \n Sources: Legumes, nuts, seeds, whole grains, eggs,
fish,
buckwheat, seafood, corn, wild rice")
}
else if(mineral_type == "Potassium")
{
conv.ask("Sources: Sweet potato, tomato, green leafy vegetables,
carrots,
prunes, beans, molasses, squash, fish, bananas, peaches, apricots, melon,
potatoes, dates, raisins, mushrooms")
}
})
exports.dialogflowFirebaseFulfillment = functions.https.onRequest(app)
This is my 'Text or SSML Response'
$Minerals
This is the code on my Android Studio's chatbot page
package com.example.ft.aidt;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.nfc.Tag;
import android.speech.tts.TextToSpeech;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.JsonElement;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Map;
import ai.api.AIListener;
import ai.api.android.AIConfiguration;
import ai.api.android.AIService;
import ai.api.model.AIError;
import ai.api.model.AIResponse;
import ai.api.model.Result;
import ai.api.ui.AIDialog;
public class ai extends AppCompatActivity implements AIListener {
public static final String TAG = ai.class.getName();
private Button bu,nu;
private TextView resp;
private AIService aiService;
private TextView a;
private ImageView yu;
private TextToSpeech joi;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ai);
yu = (ImageView) findViewById(R.id.imageView20);
int permi =
ContextCompat.checkSelfPermission(this,Manifest.permission.RECORD_AUDIO);
if(permi != PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this, "Permission Denied",
Toast.LENGTH_SHORT).show();
MakeRequest();
}
final AIConfiguration config = new
AIConfiguration("b0369e8530c14cc0990cccab8b9f0289",
AIConfiguration.SupportedLanguages.English,
AIConfiguration.RecognitionEngine.System);
aiService = AIService.getService(this, config);
aiService.setListener(this);
bu =(Button) findViewById(R.id.button12);
resp=(TextView) findViewById(R.id.textView10);
a = (TextView) findViewById(R.id.textView12);
joi = new TextToSpeech(ai.this, new TextToSpeech.OnInitListener()
{
#Override
public void onInit(int status) {
}
});
yu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(ai.this,"Here you can talk to AIDT and converse
with it. If you fail to get a reply, please check your internet
connection.",Toast.LENGTH_LONG).show();
}
});
bu.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
resp.setText("ERROR");
return false;
}
});
bu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
aiService.startListening();
}
});
}
protected void MakeRequest() {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.RECORD_AUDIO},007);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[]
grantResults) {
switch (requestCode) {
case 007: {
if (grantResults.length == 0
|| grantResults[0] !=
PackageManager.PERMISSION_GRANTED) {
} else {
}
return;
}}}
#Override
public void onResult( final AIResponse response) {
Log.i("", response.toString());
ArrayList<String> ap = new ArrayList<>();
ArrayList<String> apk = new ArrayList<>();
final Result result1 = response.getResult();
String parameterString = "";
if (result1.getParameters() != null &&
!result1.getParameters().isEmpty()) {
for (final Map.Entry<String, JsonElement> entry :
result1.getParameters().entrySet()) {
parameterString += "(" + entry.getKey() + ", " +
entry.getValue() + ") ";
}
}
final String sppech = result1.getFulfillment().getSpeech();
String ae = result1.getResolvedQuery().toString();
a.setText("\n Baymax: " + result1.getFulfillment().getSpeech());
resp.setText("\n You: " + result1.getResolvedQuery());
// Show results in TextView.
joi.speak(result1.getFulfillment().getSpeech(),
TextToSpeech.QUEUE_FLUSH, null, null);
}
#Override
public void onError(AIError error)
{
resp.setText(error.toString());
}
#Override
public void onAudioLevel(float level) {
}
#Override
public void onListeningStarted() {
}
#Override
public void onListeningCanceled() {
}
#Override
public void onListeningFinished() {
}
}
[App Screenshot][1]
[Intent, Entity & Test Console Screenshot][1]
[1]: https://imgur.com/a/Qs0CWhK "App Screenshot"
[2]: https://imgur.com/a/v3dz2tI "Intent, Entity & Test Console Screenshot"

The issue is that you're using the actions-on-google library to send information back, but your Android App is not an Action. So it is reading the standard Dialogflow fields from a response, rather than looking in the "google" payload section.
In general, if you're planning to develop for platforms other than the Assistant, you should be using the dialogflow-fulfillment library, rather than actions-on-google, since it lets you specify custom payloads for your platform.

Related

Activity not moving to another activty in android studio

package com.example.bookapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.bookapp.databinding.ActivityLoginBinding;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class LoginActivity extends AppCompatActivity {
private ActivityLoginBinding binding;
private FirebaseAuth firebaseAuth;
private ProgressDialog progressDialog;
private Button BtnLogin;
private EditText TxtEmail;
private EditText TxtPassword;
private TextView singUp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
firebaseAuth = firebaseAuth.getInstance();
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Please wait");
progressDialog.setCanceledOnTouchOutside(false);
BtnLogin =(Button) findViewById(R.id.loginBtn);
singUp =(TextView) findViewById(R.id.noAccountTv);
singUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Intent i = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(i);
}
});
BtnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
validateData();
}
});
}
private String email = "", password = "";
private void validateData() {
TxtEmail =(EditText) findViewById(R.id.emailet);
email =TxtEmail.getText().toString().trim();
TxtPassword = (EditText) findViewById(R.id.passwordet);
password = TxtPassword.getText().toString().trim();
if(!Patterns.EMAIL_ADDRESS.matcher(email).matches())
{
Toast.makeText(this, "Invalid Email Pattern..!", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(password))
{
Toast.makeText(this,"Please enter password",Toast.LENGTH_SHORT).show();
}
else
{
loginUser();
}
}
private void loginUser()
{
progressDialog.setMessage("Logging In");
progressDialog.show();
firebaseAuth.signInWithEmailAndPassword(email,password)
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
checkUser();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure( Exception e) {
progressDialog.dismiss();
Toast.makeText(LoginActivity.this,""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
private void checkUser()
{
progressDialog.setMessage("Checking User..");
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");
ref.child(firebaseUser.getUid())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot)
{
progressDialog.dismiss();
String userType = ""+snapshot.child("userType").getValue();
if(userType.equals("user"))
{
Intent i = new Intent(LoginActivity.this,DashboardUserActivity.class);
startActivity(i);
finish();
}
else if(userType.equals("admin"))
{
Intent i = new Intent(LoginActivity.this,DashboardAdminActivity.class);
startActivity(i);
finish();
}
}
#Override
public void onCancelled(DatabaseError error) {
}
});
}
}
Application is unable to move to the DashboardAdminActivity/DashboardUserActivity while progressbar is showing & email and password validation is also working, but it's not going to the next activities according to the "usertype".
I also tried intent another way, but it's not working, if you guys can find any error/correction in my code, it would be appreciated.

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();
}
});
}
});
}
}
'''

[Android App]Screen flickers when I switch dark mode

I'm currently creating my own application with Android Studio. In this app, I want to create a switch, that changes to dark mode and back.
In the MainActivity.java I'm using the following code
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
public class MainActivity extends AppCompatActivity {
private Button button;
private Switch aSwitch;
public static final String MyPREFERENCES = "nightModePrefs";
public static final String KEY_ISNIGHTMODE = "isNightMode";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button feed = findViewById(R.id.feed);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
aSwitch = findViewById(R.id.day_night);
checkNightModeActivated();
aSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
saveNightModeState(true);
recreate();
}else{
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
saveNightModeState(true);
recreate();
}
});
feed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Newsfeed.class));
}
});
}
private void saveNightModeState(boolean nightMode) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(KEY_ISNIGHTMODE, nightMode);
editor.apply();
}
private void checkNightModeActivated() {
if(sharedpreferences.getBoolean(KEY_ISNIGHTMODE, false)) {
aSwitch.setChecked(true);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}else{
aSwitch.setChecked(false);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
}
The problem is, that the switch will change the mode to dark when I've started the app. But then, the app beginns to flicker and does not longer responds.
Can soneone please tell me, what I'm doing wrong?
Kind regards
Kai
I've found a solution for my problem.
private Switch day_night;
day_night=findViewById(R.id.day_night);
day_night.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
else {
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
}
});

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

OnDataChanged is not called

I have a problem with comunication between my phone and wear device. I decided to add wear module to my app. Wear app has just one class (MainActivity)
package cz.johrusk.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.wearable.view.WatchViewStub;
import android.util.Log;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.DataEventBuffer;
import com.google.android.gms.wearable.PutDataMapRequest;
import com.google.android.gms.wearable.PutDataRequest;
import com.google.android.gms.wearable.Wearable;
public class MainActivity extends Activity implements GoogleApiClient.OnConnectionFailedListener,DataApi.DataListener {
GoogleApiClient mGoogleApiClient;
private TextView mTextView;
static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
mTextView = (TextView) stub.findViewById(R.id.text);
}
});
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle connectionHint) {
Log.d(TAG, "onConnected: " + connectionHint);
sendNumber(1);
Log.d(TAG,"BBBBBBBB");
}
#Override
public void onConnectionSuspended(int cause) {
Log.d(TAG, "onConnectionSuspended: " + cause);
}
})
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
Log.d(TAG,"mGoogleApiClient connected;");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG,"FAILE" + connectionResult);
}
public void sendNumber(int number) {
PutDataMapRequest putDataMapRequest = PutDataMapRequest.create("/number");
putDataMapRequest.getDataMap().putInt("number",number);
putDataMapRequest.getDataMap().putLong("Time",System.currentTimeMillis());
PutDataRequest putDataReq = putDataMapRequest.asPutDataRequest();
putDataReq.setUrgent();
Wearable.DataApi.putDataItem(mGoogleApiClient, putDataReq)
.setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
#Override
public void onResult(#NonNull DataApi.DataItemResult dataItemResult) {
if (!dataItemResult.getStatus().isSuccess()) {
Log.d(TAG,"Fail");
}
else{
Log.d(TAG,"Succes");
}
}
});
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onDataChanged(DataEventBuffer dataEventBuffer) {
Log.d(TAG,"TEST");
}
}
I quess that "Wearable.DataApi.putDataItem" should call WearableListenerService in my phone app. Here is that service:
package cz.johrusk.showsmscode.service;
import android.util.Log;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.wearable.DataEvent;
import com.google.android.gms.wearable.DataEventBuffer;
import com.google.android.gms.wearable.DataMap;
import com.google.android.gms.wearable.DataMapItem;
import com.google.android.gms.wearable.Wearable;
import com.google.android.gms.wearable.WearableListenerService;
public class WatchListener_service extends WearableListenerService {
#Override
public void onCreate() {
super.onCreate();
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onDataChanged(DataEventBuffer dataEventBuffer) {
Log.d("prijato","number is: ");
for (DataEvent dataEvent : dataEventBuffer) {
if (dataEvent.getType() == DataEvent.TYPE_CHANGED) {
DataMap dataMap = DataMapItem.fromDataItem(dataEvent.getDataItem()).getDataMap();
String path = dataEvent.getDataItem().getUri().getPath();
if (path.equals("/number")){
int number = dataMap.getInt("numa");
long time = dataMap.getInt("timestamp");
Log.d("received","number is: " + number);
}
}
}
}
}
However, onDataChanged method in WatchListener_service isn't called. onResult method inside ResultCallbacks print "Succes" so it seems that DataItem is send correctly.
I already find many similar problems on Stackoverlflow so I checked all these things:
Both modules has same applicationId
Both modules use 'com.google.android.gms:play-services-wearable:9.0.0'
SetUrgent is used to putDataRequest so there shouldnt be any delay.
WearableListenerService has declared correct intent filter in Manifest :
action android:name="com.google.android.gms.wearable.DATA_CHANGED"
data android:scheme="wear" android:host="*"
Both phone and Wear app run on physical device. My question is... What should I do to fix this issue?
Thanks
Check if both apps have the same debug key. I had some problems with that and problem was different keys for both apps (wear and mobile).
PS: The Android Wear API is ridiculous. I quit developing for Wear because of how terrible is that API that doest not work as they say this should.

Resources