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();
}
});
}
});
}
}
'''
Related
when I press the Start button on the Night screen and return to it, the Night screen is not maintained. How can I maintain it?
enter image description here
enter image description here
when I press the "Start button" on the "Night screen" and come back, the "Morning screen" appears.
How do i make the "Night screen" appear even when I return after pressing the button?
package kr.ac.mjc.ict2018261001.airhockey;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.firestore.FirebaseFirestore;
import kr.ac.mjc.ict2018261001.airhockey.Themes.OnSwipeTouchListener;
import kr.ac.mjc.ict2018261001.airhockey.Themes.ThemeUtil;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
TextView textView;
int count = 0;
String themeColor;
FirebaseFirestore firestore = FirebaseFirestore.getInstance();
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
Button startBtn = findViewById(R.id.start_btn);
imageView = findViewById(R.id.imageView);
textView = findViewById(R.id.textView);
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,NumberActivity.class);
startActivity(intent);
}
});
imageView.setOnTouchListener(new OnSwipeTouchListener(getApplicationContext()) {
public void onSwipeTop() {
}
public void onSwipeRight() {
if (count == 0) {
imageView.setImageResource(R.drawable.good_night_img);
textView.setText("Night");
count = 1;
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,NumberActivity.class);
startActivity(intent);
themeColor = ThemeUtil.DARK_MODE;
ThemeUtil.applyTheme(themeColor);
ThemeUtil.modSave(getApplicationContext(),themeColor);
}
});
} else {
imageView.setImageResource(R.drawable.good_morning_img);
textView.setText("Morning");
count = 0;
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,NumberActivity.class);
startActivity(intent);
themeColor = ThemeUtil.LIGHT_MODE;
ThemeUtil.applyTheme(themeColor);
ThemeUtil.modSave(getApplicationContext(),themeColor);
}
});
}
}
public void onSwipeLeft() {
if (count == 0) {
imageView.setImageResource(R.drawable.good_night_img);
textView.setText("Night");
count = 1;
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,NumberActivity.class);
startActivity(intent);
themeColor = ThemeUtil.DARK_MODE;
ThemeUtil.applyTheme(themeColor);
ThemeUtil.modSave(getApplicationContext(),themeColor);
}
});
} else {
imageView.setImageResource(R.drawable.good_morning_img);
textView.setText("Morning");
count = 0;
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,NumberActivity.class);
startActivity(intent);
themeColor = ThemeUtil.LIGHT_MODE;
ThemeUtil.applyTheme(themeColor);
ThemeUtil.modSave(getApplicationContext(),themeColor);
}
});
}
}
public void onSwipeBottom() {
}
});
FirebaseDatabase database = FirebaseDatabase.getInstance();
}
}
package kr.ac.mjc.ict2018261001.airhockey.Themes;
import android.content.Context;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class OnSwipeTouchListener implements OnTouchListener {
private final GestureDetector gestureDetector;
public OnSwipeTouchListener(Context ctx){
gestureDetector = new GestureDetector(ctx, new GestureListener());
}
#Override
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
private final class GestureListener extends SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
#Override
public boolean onDown(MotionEvent e) {
return true;
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
boolean result = false;
try {
float diffY = e2.getY() - e1.getY();
float diffX = e2.getX() - e1.getX();
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
onSwipeRight();
} else {
onSwipeLeft();
}
result = true;
}
}
else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
if (diffY > 0) {
onSwipeBottom();
} else {
onSwipeTop();
}
result = true;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return result;
}
}
public void onSwipeRight() {
}
public void onSwipeLeft() {
}
public void onSwipeTop() {
}
public void onSwipeBottom() {
}
}
I would like to implement a new intent when my card from CardView is clicked. I have already implemented for one of the cards. Is there any other way in which the adapter is able to identify the position and bring to a new activity for each card? Like linking the each card to their individual activity with a template layout. (The new activity for each card will be of the same layout, just different texts and images).
I have added an ImageButton on my cards. However, when I click on the ImageButton, it does not bring me to the new activity. Clicking on the card edges/portion and not the image itself would work. Is there something I missed out on my code? I can't seem to get it.
Here are my codes:
MuaActivity.java
package android.com.example.weddingappfinale;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.inputmethod.EditorInfo;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import Adapters.MuaAdapter;
import CustomerActivities.ShimaMatinActivity;
public class MuaActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private MuaAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mua_list);
getSupportActionBar().setTitle("Make Up Artists");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final ArrayList<MuaView> muaView = new ArrayList<>();
muaView.add(new MuaView(R.drawable.mua_image, "Shima Matin Bridal Services"));
muaView.add(new MuaView(R.drawable.mua_image, "Aake Up Artist Pte Ltd"));
muaView.add(new MuaView(R.drawable.mua_image, "Lake Up Artist 3Pte Ltd"));
muaView.add(new MuaView(R.drawable.mua_image, "f Up Artist Pte Ltd"));
// ArrayList
mRecyclerView = findViewById(R.id.recycler_view_list);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new MuaAdapter(muaView);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new MuaAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
Intent i = new Intent (MuaActivity.this, ShimaMatinActivity.class);
startActivity(i);
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.search, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setImeOptions(EditorInfo.IME_ACTION_DONE);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
mAdapter.getFilter().filter(newText);
return false;
}
});
return true;
}
}
MuaAdapter.java
package Adapters;
import android.com.example.weddingappfinale.MuaView;
import android.com.example.weddingappfinale.R;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class MuaAdapter extends RecyclerView.Adapter<MuaAdapter.MuaViewHolder> implements Filterable {
private ArrayList<MuaView> mMuaView;
private ArrayList<MuaView> mMuaViewFull;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public static class MuaViewHolder extends RecyclerView.ViewHolder {
public ImageButton mImageButton;
public TextView mTextView1;
public MuaViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
mImageButton = itemView.findViewById(R.id.mua_imageButton);
mTextView1 = itemView.findViewById(R.id.mua_title);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
}
}
});
}
}
public MuaAdapter(ArrayList<MuaView> muaView) {
this.mMuaView = muaView;
mMuaViewFull = new ArrayList<>(muaView);
}
#NonNull
#Override
public MuaViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.mua_view, parent, false);
MuaViewHolder mvh = new MuaViewHolder(v, mListener);
return mvh;
}
#Override
public void onBindViewHolder(#NonNull MuaViewHolder holder, int position) {
MuaView currentView = mMuaView.get(position);
holder.mImageButton.setImageResource(currentView.getImageResource());
holder.mTextView1.setText(currentView.getText1());
}
#Override
public int getItemCount() {
return mMuaView.size();
}
public Filter getFilter() {
return MuaFilter;
}
private Filter MuaFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<MuaView> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(mMuaViewFull);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (MuaView item : mMuaViewFull) {
if (item.getText1().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mMuaView.clear();
mMuaView.addAll((ArrayList) results.values);
notifyDataSetChanged();
}
};
}
Answer for first question:
You could pass the position of the item to the new activity with intent.putExtra().
In the new activity you can read out the number with intent.getExtra() and setup your layout content as you want depending on the number you got.
This way you only have one Activity instead of many.
Activity 1
Intent intent = new Intent(this, Shima.class);
intent.putExtra("position_value", position);
startActivity(intent);
Activity 2
Intent intent = getIntent();
int position = intent.getIntExtra("position_value", 0); // 0 is the default value
// set a layout based on position with switch case or if...
switch (position){
case 1:
setContentView(R.layout.activity_card_one);
break;
case 2:
setContentView(R.layout.activity_card_two);
break;
....
Second question:
See here.
Basicaly the same way like
itemView.setOnClickListener(new View.OnClickListener() {...
You can set a image depending on what item has been clicked using something like this
private Integer images[] = {R.drawable.pic1, R.drawable.pic2, R.drawable.pic3}
and
imageView.setImageResource(images[position]);
(maybe position -1, not sure if first item in recyclerView is 1 or 0)
I'm trying to make a register screen with some text fields for the user to type a username and a password, and the button should save the data and go back to the login screen. But when I click the register button, it doesn't go back to login screen.
I have commented where I think the error is at:
package com.example.gerenciadorestoqueoficial;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Cadastro extends AppCompatActivity {
EditText cadastroNome;
EditText cadastroPassword;
EditText cnfCadastroPassword;
Button cadastrar;
Button voltar;
TextView verLogin;
DbHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tela_cadastro);
cadastroNome = (EditText)findViewById(R.id.etCadastroNome);
cadastroPassword = (EditText)findViewById(R.id.etCadastroPassword);
cnfCadastroPassword =(EditText)findViewById(R.id.etConfirmarPassword);
cadastrar = (Button)findViewById(R.id.btnCadastrar);
verLogin = (TextView)findViewById(R.id.tvLoginCadastro);
voltar = (Button)findViewById(R.id.btnVoltarCadastro);
final DbHelper db = new DbHelper (this);
verLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent loginIntent = new Intent(Cadastro.this,MainActivity.class);
startActivity(loginIntent);
}
});
voltar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Cadastro.this,MainActivity.class);
finish();
startActivity(intent);
}
});
// here is the button
cadastrar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String usuario = cadastroNome.getText().toString();
String password = cadastroPassword.getText().toString();
String cnfPassword = cnfCadastroPassword.getText().toString();
if(password.equals(cnfPassword)){
long val = db.adicionarUsuario(usuario, password);
if(val > 0){
Toast.makeText(Cadastro.this, "Usuário cadastrado", Toast.LENGTH_SHORT).show();
Intent irParaLogin = new Intent(Cadastro.this, MainActivity.class); // here is the intent that is not working
finish();
startActivity(irParaLogin);
}else if(cadastroNome.getText().toString().length() == 0 || cadastroPassword.getText().toString().length() == 0 || cnfCadastroPassword.getText().toString().length() == 0){
Toast.makeText(Cadastro.this, "Preencha todos os campos", Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
It should be saying "Usuário cadastrado" after saving data with the help of SQLite and then going back to login screen, unless the passwords do not match in both text fields.
Better u make your DBHelper Insert method like bool return type
public boolean InsertData(String name,int cost,int sell,int profit)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("Name",name);
contentValues.put("Cost_Price",cost);
contentValues.put("Selling_Price",sell);
contentValues.put("Profit",profit);
long result= db.insert("Table_B",null,contentValues);
if (result==-1)
return false;
else
return true;
}
after this send your Username and Password to this method and accept it in Boolean variable....as foolows
boolean isInserted = mdb.InsertData("Cake" "1kilo", 60, 50, 10);
if (isInserted == true)
//start your intent here
else
Toast.makeText(Register.this, "OOps Data Not Inserted", Toast.LENGTH_LONG).show();
`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
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)