Android searchview on fragment - search

I am developing an android app, which contains a Navigation Drawer Activity. This in turn contains two tabs "Alabanzas" and "Tema", both are accessed from the side menu.
The "Alabanzas" tab is a Fragment that contains a custom ArrayAdapter that contains a ListView.
In the ActionBar place a SearchView element for the searches within the ListView of "Alabanzas", however I can not link the search with the elements of the ListView
My Classes are the Following ...
Class MainActivity with Navigation Drawer
Error in the method onQueryTextChange of the method onCreateOptionsMenu generates the miadaptador.getFilter().Filter(s); because that adapter is different from the one installed in the Adapter class that has the search method
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.MenuInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
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.view.Menu;
import android.view.MenuItem;
import android.widget.SearchView;
import com.example.misael.corolldm.Fragmentos.Alabanza;
import com.example.misael.corolldm.Fragmentos.Temas;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
CargarFragmento(new Alabanza());
navigationView.getMenu().getItem(0).setChecked(true);
}
#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) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_search,menu);
MenuItem item = menu.findItem(R.id.menuSearch);
SearchView searchView= (SearchView)item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
// miadaptador.getFilter().filter(s);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
#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(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
CargarFragmento(new Alabanza());
} else if (id == R.id.nav_gallery) {
CargarFragmento(new Temas());
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void CargarFragmento(Fragment fragmento){
FragmentManager Manager = getSupportFragmentManager();
Manager.beginTransaction().replace(R.id.contenedorFragmento, fragmento).commit();
}
}
Xml Archive activity_main
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
Class Adaptador
public class Adaptador extends BaseAdapter implements Filterable {
Context contexto;
ArrayList<Datos> ListaObjetos;
ArrayList<Datos> mStringFilterList;
ValueFilter valueFilter;
public Adaptador(Context contexto, ArrayList<Datos> listaObjetos) {
this.contexto = contexto;
this.ListaObjetos = listaObjetos;
mStringFilterList=listaObjetos;
}
/*
Retorna cantidad de elementos de la vista
*/
#Override
public int getCount() {
return this.ListaObjetos.size();
}
/*
Retorna objeto puntual de la posicion que indico
*/
#Override
public Object getItem(int i) {
return this.ListaObjetos.get(i);
}
/*
Retorna Id del objeto puntual de la posicion que indico
*/
#Override
public long getItemId(int i) {
return this.ListaObjetos.get(i).getId();
}
/*
Se ejecuta en cada secuencia de cada hito de la listview
*/
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View vista = view;
//Inyectamos el layout definido dentro de la vista del ListView
LayoutInflater inflate = LayoutInflater.from(contexto);
vista = inflate.inflate(R.layout.itemlistview, null);
//Referenciamos el titulo
TextView titulo = (TextView) vista.findViewById(R.id.tw_titulo);
titulo.setText(ListaObjetos.get(i).getTitulo().toString());
return vista;
}
#Override
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
ArrayList<Datos> filterList = new ArrayList<Datos>();
for (int i = 0; i < mStringFilterList.size(); i++) {
if ((mStringFilterList.get(i).getTitulo().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
Datos data = new Datos(mStringFilterList.get(i)
.getId(), mStringFilterList.get(i)
.getTitulo());
filterList.add(data);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = mStringFilterList.size();
results.values = mStringFilterList;
}
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
ListaObjetos = (ArrayList<Datos>) filterResults.values;
notifyDataSetChanged();
}
}
}
Class Alabanza
public class Alabanza extends Fragment {
ListView listaDatos;
ArrayList<Datos> Lista= new ArrayList<>();
Adaptador miadaptador;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_alabanza, container, false);
listaDatos = (ListView)view.findViewById(R.id.lstDatos);
Lista.add(new Datos(1,"A la Diestra de Dios"));
Lista.add(new Datos(2,"A solas al Huerto"));
Lista.add(new Datos(3,"A ti Señor"));
Lista.add(new Datos(4,"A veces me pregunto"));
Lista.add(new Datos(5,"Al divino Salvador"));
Lista.add(new Datos(6,"Al Mundo Paz"));
Lista.add(new Datos(7,"Alabado el gran manantial"));
Lista.add(new Datos(8,"Alabanzas a Dios dad"));
Lista.add(new Datos(9,"Aleluya Amen"));
Lista.add(new Datos(10,"Aleluya oh Creador"));
Lista.add(new Datos(11,"Angeles cantando estan"));
Lista.add(new Datos(12,"Apocalipsis 14_6"));
Lista.add(new Datos(13,"Bendito Amor"));
Lista.add(new Datos(14,"Blancos Vestidos"));
Lista.add(new Datos(15,"Cantad a Jehova"));
Lista.add(new Datos(16,"Canten a Cristo Rey"));
Lista.add(new Datos(17,"Cerca de ti señor"));
Lista.add(new Datos(18,"Contigo estoy tan Feliz"));
Lista.add(new Datos(19,"Cuan Amables son tus Moradas"));
Lista.add(new Datos(20,"Cuando el Señor manifesto"));
Lista.add(new Datos(21,"Cuarenta Años de amor"));
Lista.add(new Datos(22,"Del Celeste Pais"));
Lista.add(new Datos(23,"Don Inefable"));
Lista.add(new Datos(24,"Dulce Oracion"));
Lista.add(new Datos(25,"El Amigo del Angel"));
Lista.add(new Datos(26,"El Apóstol de la Consolación"));
Lista.add(new Datos(27,"El Evangelio de Cristo"));
Lista.add(new Datos(28,"El Lema de la Iglesia"));
Lista.add(new Datos(29,"El Manto de la Eleccion"));
Lista.add(new Datos(30,"El mas bello amor"));
Lista.add(new Datos(31,"El Nuevo Israel"));
Lista.add(new Datos(32,"El Replicar del Campanal"));
Lista.add(new Datos(33,"El Resplandor de tu nacimiento"));
Lista.add(new Datos(33,"El vino a mi corazon"));
Lista.add(new Datos(34,"Elección de Dios"));
Lista.add(new Datos(35,"En la Judea"));
Lista.add(new Datos(36,"En las mañanas de bendicion"));
Lista.add(new Datos(37,"Engrandecido sea Dios"));
Lista.add(new Datos(38,"Eres el Angel"));
Lista.add(new Datos(39,"Estoy resuelto"));
miadaptador = new Adaptador(getActivity().getApplicationContext(),Lista);
listaDatos.setAdapter(miadaptador);
//Agregamos escuchador
listaDatos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Datos obj=(Datos) adapterView.getItemAtPosition(i);
//Creamos el paso hacia la nueva activity
Intent paso=new Intent(getActivity().getApplicationContext(), DetalleActivity.class);
paso.putExtra("objeto", (Serializable) obj); // Serializamos el traspaso del objeto
//Realiza el traspaso a la otra activity
startActivity(paso);
}
});
return view;
}
}
Xml Archive menu_search
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/menuSearch"
android:title="Search"
android:icon="#android:drawable/ic_menu_search"
app:actionViewClass="android.widget.SearchView"
app:showAsAction="always"></item>
</menu>
If anyone could help me perform searches in the listView of the fragment "Alabanzas", any idea will be very well received
Thank you

Related

Encrypted Bluetooth chat communication

Having issues with the app, shuts down any time I click on the chat button. I just submitted my manifest, gradle , xml, and the mainactivity to check what really went wrong. Thanks
I have an error from the logcat
GoldfishAddressSpaceHostMemoryAllocator: ioctl_ping failed for device_type=5, ret=-1.
2021-06-26 05:10:29.573 24952-24952/c.bawp.securemessenger D/AndroidRuntime: Shutting down VM
2021-06-26 05:10:29.587 24952-24952/c.bawp.securemessenger E/AndroidRuntime: FATAL EXCEPTION: main
Process: c.bawp.securemessenger, PID: 24952
android.content.ActivityNotFoundException: Unable to find explicit activity class {c.bawp.securemessenger/c.bawp.securemessenger.ChatController}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2005)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1673)
at android.app.Activity.startActivityForResult(Activity.java:4586)
at androidx.activity.ComponentActivity.startActivityForResult(ComponentActivity.java:574)
at android.app.Activity.startActivityForResult(Activity.java:4544)
at androidx.activity.ComponentActivity.startActivityForResult(ComponentActivity.java:560)
at android.app.Activity.startActivity(Activity.java:4905)
at android.app.Activity.startActivity(Activity.java:4873)
at c.bawp.securemessenger.ChooseActivity$1.onClick(ChooseActivity.java:26)
at android.view.View.performClick(View.java:6597)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25885)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
2021-06-26 05:10:29.657 24952-24952/c.bawp.securemessenger I/Process: Sending signal. PID: 24952 SIG: 9
So I don't know if this is the reason why it keeps shutting down any time I tap the button chat. The button chat is created in an activity.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="c.bawp.securemessenger">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="#style/Theme.SecureMessenger">
<activity android:name=".MainActivity" />
<activity android:name=".Main2Activity" />
<activity android:name=".ChooseActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".FileExchangeActivity"></activity>
</application>
</manifest>
package c.bawp.securemessenger;
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.textfield.TextInputLayout;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
private TextView status;
private Button btnConnect;
private ListView listView;
private Dialog dialog;
private TextInputLayout inputLayout;
private MessageAdapter messageAdapter;
private ArrayAdapter<String> chatAdapter;
private ArrayList<String> chatMessages;
private BluetoothAdapter bluetoothAdapter;
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_OBJECT = 4;
public static final int MESSAGE_TOAST = 5;
public static final String DEVICE_OBJECT = "device_name";
private static final int REQUEST_ENABLE_BLUETOOTH = 1;
private ChatController chatController;
private BluetoothDevice connectingDevice;
private ArrayAdapter<String> discoveredDevicesAdapter;
private Encrypt encrypt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewsByIds();
//check device support bluetooth or not
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available!", Toast.LENGTH_SHORT).show();
finish();
}
//show bluetooth devices dialog when click connect button
btnConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showPrinterPickDialog();
}
});
//set chat adapter
messageAdapter = new MessageAdapter(this);
listView.setAdapter(messageAdapter);
encrypt = new Encrypt();
}
private final Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case ChatController.STATE_CONNECTED:
setStatus("Connected to: " + connectingDevice.getName());
btnConnect.setVisibility(View.INVISIBLE);
break;
case ChatController.STATE_CONNECTING:
setStatus("Connecting...");
//btnConnect.setEnabled(false);
break;
case ChatController.STATE_LISTEN:
case ChatController.STATE_NONE:
setStatus("Not connected");
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
String writeMessage = new String(writeBuf);
writeMessage = encrypt.decrypt(writeMessage);
//check out
MemberData data1 = new MemberData("Me","#C62828");
c.bawp.securemessenger.Message message1 = new c.bawp.securemessenger.Message(writeMessage, data1, true);
messageAdapter.add(message1);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
readMessage = encrypt.decrypt(readMessage);
MemberData data2 = new MemberData(connectingDevice.getName(),"#C62828");
Log.d("Bug", "handleMessage: " + readMessage);
c.bawp.securemessenger.Message message2 = new c.bawp.securemessenger.Message(readMessage, data2, false);
messageAdapter.add(message2);
break;
case MESSAGE_DEVICE_OBJECT:
connectingDevice = msg.getData().getParcelable(DEVICE_OBJECT);
Toast.makeText(getApplicationContext(), "Connected to " + connectingDevice.getName(),
Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString("toast"),
Toast.LENGTH_SHORT).show();
break;
}
return false;
}
});
private void showPrinterPickDialog() {
dialog = new Dialog(this);
dialog.setContentView(R.layout.layout_bluetooth);
dialog.setTitle("Bluetooth Devices");
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
//Initializing bluetooth adapters
ArrayAdapter<String> pairedDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
discoveredDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
//locate listviews and attach the adapters
ListView listView = dialog.findViewById(R.id.pairedDeviceList);
ListView listView2 = dialog.findViewById(R.id.discoveredDeviceList);
listView.setAdapter(pairedDevicesAdapter);
listView2.setAdapter(discoveredDevicesAdapter);
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(discoveryFinishReceiver, filter);
// Register for broadcasts when discovery has finished
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
pairedDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
pairedDevicesAdapter.add(getString(R.string.none_paired));
}
//Handling listview item click event
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bluetoothAdapter.cancelDiscovery();
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
connectToDevice(address);
dialog.dismiss();
}
});
listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
bluetoothAdapter.cancelDiscovery();
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
connectToDevice(address);
dialog.dismiss();
}
});
dialog.findViewById(R.id.cancelButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.setCancelable(true);
dialog.show();
}
private void setStatus(String s) {
status.setText(s);
}
private void connectToDevice(String deviceAddress) {
bluetoothAdapter.cancelDiscovery();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
chatController.connect(device);
}
private void findViewsByIds() {
status = findViewById(R.id.status);
btnConnect = findViewById(R.id.btn_connect);
listView = findViewById(R.id.list);
inputLayout = findViewById(R.id.input_layout);
Button btnSend = findViewById(R.id.btn_send);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Objects.requireNonNull(inputLayout.getEditText()).getText().toString().equals("")) {
Toast.makeText(MainActivity.this, "Please input some texts", Toast.LENGTH_SHORT).show();
} else {
//TODO: here
sendMessage(inputLayout.getEditText().getText().toString());
inputLayout.getEditText().setText("");
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ENABLE_BLUETOOTH) {
if (resultCode == Activity.RESULT_OK) {
chatController = new ChatController(this, handler);
} else {
Toast.makeText(this, "Bluetooth still disabled, turn off application!", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void sendMessage(String message) {
if (chatController.getState() != ChatController.STATE_CONNECTED) {
Toast.makeText(this, "Connection was lost!", Toast.LENGTH_SHORT).show();
return;
}
if (message.length() > 0) {
message = encrypt.encrypt(message);
byte[] send = message.getBytes();
chatController.write(send);
}
}
#Override
public void onStart() {
super.onStart();
if (!bluetoothAdapter.isEnabled()) {
Intent dIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
dIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3000);
startActivity(dIntent);
} else {
chatController = new ChatController(this, handler);
}
}
#Override
public void onResume() {
super.onResume();
if (chatController != null) {
if (chatController.getState() == ChatController.STATE_NONE) {
chatController.start();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (chatController != null)
chatController.stop();
}
private final BroadcastReceiver discoveryFinishReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
discoveredDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
discoveredDevicesAdapter.clear();
//setProgressBarIndeterminateVisibility(false);
// setSupportProgressBarIndeterminateVisibility(true);
setTitle("Select a device to connect");
if (discoveredDevicesAdapter.getCount() == 0) {
discoveredDevicesAdapter.add("No devices found");
}
} else {
discoveredDevicesAdapter.add("Scanning Bluetooth Devices....");
}
}
};
}

Encrypt Bluetooth Chat

Having issues with the app, shuts down any time I click on the chat button. I just submitted my manifest, gradle , xml, and the mainactivity to check what really went wrong. Thanks
I have an error from the logcat
GoldfishAddressSpaceHostMemoryAllocator: ioctl_ping failed for device_type=5, ret=-1.
So I don't know if this is the reason why it keeps shutting down any time I tap the button chat. The button chat is created in an activity.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="c.bawp.securemessenger">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="#style/Theme.SecureMessenger">
<activity android:name=".MainActivity" />
<activity android:name=".Main2Activity" />
<activity android:name=".ChooseActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".FileExchangeActivity"></activity>
</application>
</manifest>
package c.bawp.securemessenger;
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.textfield.TextInputLayout;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
private TextView status;
private Button btnConnect;
private ListView listView;
private Dialog dialog;
private TextInputLayout inputLayout;
private MessageAdapter messageAdapter;
private ArrayAdapter<String> chatAdapter;
private ArrayList<String> chatMessages;
private BluetoothAdapter bluetoothAdapter;
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_OBJECT = 4;
public static final int MESSAGE_TOAST = 5;
public static final String DEVICE_OBJECT = "device_name";
private static final int REQUEST_ENABLE_BLUETOOTH = 1;
private ChatController chatController;
private BluetoothDevice connectingDevice;
private ArrayAdapter<String> discoveredDevicesAdapter;
private Encrypt encrypt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewsByIds();
//check device support bluetooth or not
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available!", Toast.LENGTH_SHORT).show();
finish();
}
//show bluetooth devices dialog when click connect button
btnConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showPrinterPickDialog();
}
});
//set chat adapter
messageAdapter = new MessageAdapter(this);
listView.setAdapter(messageAdapter);
encrypt = new Encrypt();
}
private final Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case ChatController.STATE_CONNECTED:
setStatus("Connected to: " + connectingDevice.getName());
btnConnect.setVisibility(View.INVISIBLE);
break;
case ChatController.STATE_CONNECTING:
setStatus("Connecting...");
//btnConnect.setEnabled(false);
break;
case ChatController.STATE_LISTEN:
case ChatController.STATE_NONE:
setStatus("Not connected");
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
String writeMessage = new String(writeBuf);
writeMessage = encrypt.decrypt(writeMessage);
//check out
MemberData data1 = new MemberData("Me","#C62828");
c.bawp.securemessenger.Message message1 = new c.bawp.securemessenger.Message(writeMessage, data1, true);
messageAdapter.add(message1);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
readMessage = encrypt.decrypt(readMessage);
MemberData data2 = new MemberData(connectingDevice.getName(),"#C62828");
Log.d("Bug", "handleMessage: " + readMessage);
c.bawp.securemessenger.Message message2 = new c.bawp.securemessenger.Message(readMessage, data2, false);
messageAdapter.add(message2);
break;
case MESSAGE_DEVICE_OBJECT:
connectingDevice = msg.getData().getParcelable(DEVICE_OBJECT);
Toast.makeText(getApplicationContext(), "Connected to " + connectingDevice.getName(),
Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString("toast"),
Toast.LENGTH_SHORT).show();
break;
}
return false;
}
});
private void showPrinterPickDialog() {
dialog = new Dialog(this);
dialog.setContentView(R.layout.layout_bluetooth);
dialog.setTitle("Bluetooth Devices");
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
//Initializing bluetooth adapters
ArrayAdapter<String> pairedDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
discoveredDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
//locate listviews and attach the adapters
ListView listView = dialog.findViewById(R.id.pairedDeviceList);
ListView listView2 = dialog.findViewById(R.id.discoveredDeviceList);
listView.setAdapter(pairedDevicesAdapter);
listView2.setAdapter(discoveredDevicesAdapter);
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(discoveryFinishReceiver, filter);
// Register for broadcasts when discovery has finished
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
pairedDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
pairedDevicesAdapter.add(getString(R.string.none_paired));
}
//Handling listview item click event
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bluetoothAdapter.cancelDiscovery();
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
connectToDevice(address);
dialog.dismiss();
}
});
listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
bluetoothAdapter.cancelDiscovery();
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
connectToDevice(address);
dialog.dismiss();
}
});
dialog.findViewById(R.id.cancelButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.setCancelable(true);
dialog.show();
}
private void setStatus(String s) {
status.setText(s);
}
private void connectToDevice(String deviceAddress) {
bluetoothAdapter.cancelDiscovery();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
chatController.connect(device);
}
private void findViewsByIds() {
status = findViewById(R.id.status);
btnConnect = findViewById(R.id.btn_connect);
listView = findViewById(R.id.list);
inputLayout = findViewById(R.id.input_layout);
Button btnSend = findViewById(R.id.btn_send);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Objects.requireNonNull(inputLayout.getEditText()).getText().toString().equals("")) {
Toast.makeText(MainActivity.this, "Please input some texts", Toast.LENGTH_SHORT).show();
} else {
//TODO: here
sendMessage(inputLayout.getEditText().getText().toString());
inputLayout.getEditText().setText("");
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ENABLE_BLUETOOTH) {
if (resultCode == Activity.RESULT_OK) {
chatController = new ChatController(this, handler);
} else {
Toast.makeText(this, "Bluetooth still disabled, turn off application!", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void sendMessage(String message) {
if (chatController.getState() != ChatController.STATE_CONNECTED) {
Toast.makeText(this, "Connection was lost!", Toast.LENGTH_SHORT).show();
return;
}
if (message.length() > 0) {
message = encrypt.encrypt(message);
byte[] send = message.getBytes();
chatController.write(send);
}
}
#Override
public void onStart() {
super.onStart();
if (!bluetoothAdapter.isEnabled()) {
Intent dIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
dIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3000);
startActivity(dIntent);
} else {
chatController = new ChatController(this, handler);
}
}
#Override
public void onResume() {
super.onResume();
if (chatController != null) {
if (chatController.getState() == ChatController.STATE_NONE) {
chatController.start();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (chatController != null)
chatController.stop();
}
private final BroadcastReceiver discoveryFinishReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
discoveredDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
discoveredDevicesAdapter.clear();
//setProgressBarIndeterminateVisibility(false);
// setSupportProgressBarIndeterminateVisibility(true);
setTitle("Select a device to connect");
if (discoveredDevicesAdapter.getCount() == 0) {
discoveredDevicesAdapter.add("No devices found");
}
} else {
discoveredDevicesAdapter.add("Scanning Bluetooth Devices....");
}
}
};
}

How do I implement multiple intent from each Card from CardView with RecyclerView?

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)

Why does the array appear empty when I start the activity despite having objects?

I am working with a BD rom or DAo everyone calls her in a way. It is a shopping list with 2 activity 1 a recycleView and another to add. When you start the app, the idea is to verify if there is something in the database or in the array of the recycler, if there is, then start it and if not, then go to the activity to add. The problem is that even having products, it tells me that there are none. I leave the code. This is the Main
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE = 10;
private RecyclerView rv1;
private AdaptadorProducto adaptador;
private List<Producto> datos = new ArrayList<>();
private Context contexto;
private ListaCompraViewModel listaCompraViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
contexto = this;
setContentView(R.layout.activity_main);
listaCompraViewModel =
ViewModelProviders.of(this).get(ListaCompraViewModel.class);
rv1 = findViewById(R.id.rv1);
adaptador = new AdaptadorProducto(this, datos);
rv1.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
rv1.setHasFixedSize(true);
rv1.setAdapter(adaptador);
registerForContextMenu(rv1);
listaCompraViewModel.getProductos().observe(this, adaptador::setDatos);
if (datos.isEmpty()) {
Toast.makeText(this, "La lista de la compra esta vacia le enviamos a la opcion de añadir",
Toast.LENGTH_SHORT).show();
Intent i = new Intent(this, NuevoProductoActivity.class);
startActivityForResult(i, REQUEST_CODE);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
int posicion = -1;
try {
posicion = adaptador.getPosicion();
} catch (Exception e) {
return super.onContextItemSelected(item);
}
switch (item.getItemId()) {
case R.id.mi1:
Snackbar.make(this.rv1, "Se ha elegido borrar el elemento " + posicion, Snackbar.LENGTH_LONG)
.show();
Producto p = adaptador.getDatos().get(posicion);
new borrarProducto(BaseDatosApp.getInstance(contexto)).execute(p);
adaptador.notifyDataSetChanged();
if (datos.isEmpty()) {
AlertDialog.Builder dialogo1 = new AlertDialog.Builder(this);
dialogo1.setTitle("Infornacion");
dialogo1.setMessage("La lista de la compra esta vacia añada un producto o salga de la aplicacion");
dialogo1.setCancelable(false);
dialogo1.setPositiveButton("Añadir", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogo1, int id) {
añadir();
}
});
dialogo1.setNegativeButton("Salir", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogo1, int id) {
finish();
}
});
dialogo1.show();
}
break;
case R.id.mi2:
añadir();
}
return super.onContextItemSelected(item);
}
public void añadir() {
Intent i = new Intent(this, NuevoProductoActivity.class);
startActivityForResult(i, REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
Producto nProducto = (Producto) data.getExtras().getSerializable("Producto");
new insertarProducto(BaseDatosApp.getInstance(contexto)).execute(nProducto);
View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
adaptador.notifyDataSetChanged();
Snackbar snackbar = Snackbar.make(rootView, "Se ha insertado un nuevo registro.", Snackbar.LENGTH_LONG);
Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout) snackbar.getView();
snackbar.show();
}
}
class borrarProducto extends AsyncTask { private final BaseDatosApp database;
public borrarProducto(BaseDatosApp database) {
this.database = database;
}
#Override
protected Void doInBackground(final Producto... params) {
database.productoDAO().delete(params[0]);
return null;
}
}
class insertarProducto extends AsyncTask { private final BaseDatosApp database;
public insertarProducto(BaseDatosApp database) {
this.database = database;
}
#Override
protected Void doInBackground(final Producto... params) {
database.productoDAO().insertAll(params);
return null;
}
DB
#Database(entities = {Producto.class}, version = 1, exportSchema = false)
public abstract class BaseDatosApp extends RoomDatabase { private static BaseDatosApp INSTANCIA;
public static BaseDatosApp getInstance(Context context) {
if (INSTANCIA == null) {
INSTANCIA = Room.databaseBuilder(
context.getApplicationContext(),
BaseDatosApp.class,
"dbCompra")
.build();
}
return INSTANCIA;
}
public static void destroyInstance() {
INSTANCIA = null;
}
other class
ListaCompraViewModel extends AndroidViewModel {
private final LiveData<List<Producto>> productos;
public ListaCompraViewModel(#NonNull Application application) {
super(application);
productos = BaseDatosApp
.getInstance(application)
.productoDAO().getAll();
}
public LiveData<List<Producto>> getProductos() {
return productos;
}
public abstract ProductoDAO productoDAO();

Why are JavaFX2.2 buttons in my table view code not visible?

The JavaFX2 tutorial has an Addressbook example which is a table view.
tutorial:
http://docs.oracle.com/javafx/2/fxml_get_started/fxml_tutorial_intermediate.htm#CACFEHBI
enhancement to edit cells:
http://docs.oracle.com/javafx/2/ui_controls/table-view.htm
modification to add checkbox:
http://download.oracle.com/otndocs/products/javafx/2.2/samples/Ensemble/index.html#SAMPLES/Controls/Table/Table Cell Factory
Entering data in the text boxes and Clicking the Add button adds a row to the table.
However, rows cannot be deleted.
I was trying to see if I can add a Delete button in each cell - clicking it will delete the row.
I modified the existing sample code.
Somehow, the buttons are not visible. Any pointers appreciated.
//FXML_tableview.fxml file
<?import javafx.collections.*?>
<?import javafx.geometry.Insets?>
<?import java.lang.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.control.cell.*?>
<?import javafx.scene.layout.*?>
<?import fxmltableview.*?>
<Scene fx:id="root" width="550" height="550"
fx:controller="fxmltableview.FXMLTableViewController"
xmlns:fx="http://javafx.com/fxml">
<GridPane alignment="center" hgap="10" vgap="10">
<padding>
<Insets top="10" right="10" bottom="10" left="10"/>
</padding>
<TableView fx:id="tableView" GridPane.columnIndex="0"
GridPane.rowIndex="1">
</TableView>
<HBox spacing="10" alignment="bottom_right" GridPane.columnIndex="0"
GridPane.rowIndex="2">
<TextField fx:id="firstNameField" promptText="First Name"
prefWidth="90"/>
<TextField fx:id="lastNameField" promptText="Last Name"
prefWidth="90"/>
<TextField fx:id="emailField" promptText="Email"
prefWidth="150"/>
<Button text="Add" onAction="#addPerson"/>
</HBox>
</GridPane>
</Scene>
// FXMLTableView.java
package fxmltableview;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.stage.Stage;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.util.Callback;
public class FXMLTableView extends Application {
static public ObservableList<Person> data;
#FXML Scene root;
#FXML TableView tableView;
#Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("FXML TableView Example");
root = (Scene)FXMLLoader.load(getClass().getResource("fxml_tableview.fxml"));
primaryStage.setScene(root);
data = FXCollections.observableArrayList(
new Person(true, "Jacob", "Smith", "jacob.smith#example.com"),
new Person(false, "Isabella", "Johnson", "isabella.johnson#example.com"),
new Person(true, "Ethan", "Williams", "ethan.williams#example.com"),
new Person(true, "Emma", "Jones", "emma.jones#example.com"),
new Person(false, "Michael", "Brown", "michael.brown#example.com"));
tableView = (TableView) root.lookup("#tableView");
TableColumn delCol = new TableColumn<Person, Boolean>();
delCol.setMinWidth(50);
delCol.setCellFactory(new Callback<TableColumn<Person, Boolean>, TableCell<Person, Boolean>>() {
public TableCell<Person, Boolean> call(TableColumn<Person, Boolean> p) {
return new DeleteTableCell<Person, Boolean>();
}
});
//"Invited" column
TableColumn invitedCol = new TableColumn<Person, Boolean>();
invitedCol.setText("Invited");
invitedCol.setMinWidth(50);
invitedCol.setCellValueFactory(new PropertyValueFactory("invited"));
invitedCol.setCellFactory(new Callback<TableColumn<Person, Boolean>, TableCell<Person, Boolean>>() {
public TableCell<Person, Boolean> call(TableColumn<Person, Boolean> p) {
return new CheckBoxTableCell<Person, Boolean>();
}
});
//"First Name" column
TableColumn firstNameCol = new TableColumn();
firstNameCol.setText("First");
firstNameCol.setCellValueFactory(new PropertyValueFactory("firstName"));
//"Last Name" column
TableColumn lastNameCol = new TableColumn();
lastNameCol.setText("Last");
lastNameCol.setCellValueFactory(new PropertyValueFactory("lastName"));
//"Email" column
TableColumn emailCol = new TableColumn();
emailCol.setText("Email");
emailCol.setMinWidth(200);
emailCol.setCellValueFactory(new PropertyValueFactory("email"));
//Set cell factory for cells that allow editing
Callback<TableColumn, TableCell> cellFactory =
new Callback<TableColumn, TableCell>() {
public TableCell call(TableColumn p) {
return new EditingCell();
}
};
emailCol.setCellFactory(cellFactory);
firstNameCol.setCellFactory(cellFactory);
lastNameCol.setCellFactory(cellFactory);
//Set handler to update ObservableList properties. Applicable if cell is edited
updateObservableListProperties(emailCol, firstNameCol, lastNameCol);
tableView.setItems(data);
//Enabling editing
tableView.setEditable(true);
tableView.getColumns().addAll(invitedCol, firstNameCol, lastNameCol, emailCol, delCol);
// root.getChildren().add(tableView);
primaryStage.show();
}
private void updateObservableListProperties(TableColumn emailCol, TableColumn firstNameCol,
TableColumn lastNameCol) {
//Modifying the email property in the ObservableList
emailCol.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<Person, String>>() {
#Override public void handle(TableColumn.CellEditEvent<Person, String> t) {
((Person) t.getTableView().getItems().get(
t.getTablePosition().getRow())).setEmail(t.getNewValue());
}
});
//Modifying the firstName property in the ObservableList
firstNameCol.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<Person, String>>() {
#Override public void handle(TableColumn.CellEditEvent<Person, String> t) {
((Person) t.getTableView().getItems().get(
t.getTablePosition().getRow())).setFirstName(t.getNewValue());
}
});
//Modifying the lastName property in the ObservableList
lastNameCol.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<Person, String>>() {
#Override public void handle(TableColumn.CellEditEvent<Person, String> t) {
((Person) t.getTableView().getItems().get(
t.getTablePosition().getRow())).setLastName(t.getNewValue());
}
});
}
//CheckBoxTableCell for creating a CheckBox in a table cell
public static class CheckBoxTableCell<S, T> extends TableCell<S, T> {
private final CheckBox checkBox;
private ObservableValue<T> ov;
public CheckBoxTableCell() {
this.checkBox = new CheckBox();
this.checkBox.setAlignment(Pos.CENTER);
setAlignment(Pos.CENTER);
setGraphic(checkBox);
}
#Override public void updateItem(T item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
setGraphic(checkBox);
if (ov instanceof BooleanProperty) {
checkBox.selectedProperty().unbindBidirectional((BooleanProperty) ov);
}
ov = getTableColumn().getCellObservableValue(getIndex());
if (ov instanceof BooleanProperty) {
checkBox.selectedProperty().bindBidirectional((BooleanProperty) ov);
}
}
}
}
public static class DeleteTableCell<S, T> extends TableCell<S, T> {
private final Button del;
private ObservableValue<T> ov;
public DeleteTableCell() {
this.del = new Button("X");
del.setStyle("-fx-base: red;");
this.del.setAlignment(Pos.CENTER);
setAlignment(Pos.CENTER);
setGraphic(del);
del.setOnAction(new EventHandler<ActionEvent> () {
#Override
public void handle(ActionEvent t) {
int i= getIndex();
FXMLTableView.data.remove(i);
}
});
}
#Override public void updateItem(T item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
setGraphic(del);
}
}
}
// EditingCell - for editing capability in a TableCell
public static class EditingCell extends TableCell<Person, String> {
private TextField textField;
public EditingCell() {
}
#Override public void startEdit() {
super.startEdit();
if (textField == null) {
createTextField();
}
setText(null);
setGraphic(textField);
textField.selectAll();
}
#Override public void cancelEdit() {
super.cancelEdit();
setText((String) getItem());
setGraphic(null);
}
#Override public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
} else {
setText(getString());
setGraphic(null);
}
}
}
private void createTextField() {
textField = new TextField(getString());
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
textField.setOnKeyReleased(new EventHandler<KeyEvent>() {
#Override public void handle(KeyEvent t) {
if (t.getCode() == KeyCode.ENTER) {
commitEdit(textField.getText());
} else if (t.getCode() == KeyCode.ESCAPE) {
cancelEdit();
}
}
});
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
}
public static void main(String[] args) {
launch(args);
}
}
// FXMLTableViewController.java
package fxmltableview;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
public class FXMLTableViewController {
#FXML private TableView<Person> tableView;
#FXML private TextField firstNameField;
#FXML private TextField lastNameField;
#FXML private TextField emailField;
#FXML
protected void addPerson(ActionEvent event) {
ObservableList<Person> data = tableView.getItems();
data.add(new Person(false, firstNameField.getText(),
lastNameField.getText(),
emailField.getText()
));
firstNameField.setText("");
lastNameField.setText("");
emailField.setText("");
}
}
// Person.java
package fxmltableview;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
//Person object
public class Person {
private BooleanProperty invited;
private StringProperty firstName;
private StringProperty lastName;
private StringProperty email;
Person(boolean invited, String fName, String lName, String email) {
this.invited = new SimpleBooleanProperty(invited);
this.firstName = new SimpleStringProperty(fName);
this.lastName = new SimpleStringProperty(lName);
this.email = new SimpleStringProperty(email);
this.invited = new SimpleBooleanProperty(invited);
this.invited.addListener(new ChangeListener<Boolean>() {
public void changed(ObservableValue<? extends Boolean> ov, Boolean t, Boolean t1) {
System.out.println(firstNameProperty().get() + " invited: " + t1);
}
});
}
public BooleanProperty invitedProperty() { return invited; }
public StringProperty firstNameProperty() { return firstName; }
public StringProperty lastNameProperty() { return lastName; }
public StringProperty emailProperty() { return email; }
public void setLastName(String lastName) { this.lastName.set(lastName); }
public void setFirstName(String firstName) { this.firstName.set(firstName); }
public void setEmail(String email) { this.email.set(email); }
}
The delCol's cell value factory is missing. Add
delCol.setCellValueFactory(new PropertyValueFactory("invited"));
PropertyValueFactory's parameter is not important here.

Resources