Adding new object to custom array adapter with help of AlertDialog - java

I'm trying to add new Client with help of dialog, but it looks like my edit text does not exist.
It looks like all ids are right and all is good with activity live cycle, but I get:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference at dartdev.intent.MainActivity$3.onClick(MainActivity.java:122)
On the line:
String nameValue = clientName.getText().toString().trim();
Can anyone explain what went wrong?
MainActivity.java
public class MainActivity extends Activity{
ArrayList<Client> clientListItems = new ArrayList<Client>();
ClientAdapter clientAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
initClients();
clientAdapter = new ClientAdapter(this, clientListItems);
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(clientAdapter);
Button buttonView = (Button)findViewById(R.id.addListItem);
buttonView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setAddingDialog();
}
});
}
/*
#Override
protected void onStart() {
super.onStart();
Button buttonView = (Button)findViewById(R.id.addListItem);
buttonView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//listItems.add(0, Utils.hashGenerator(25));
//adapter.notifyDataSetChanged();
//DialogFragment newFragment = new AddingDialog();
//newFragment.show(getFragmentManager(), "adding");
setAddingDialog();
}
});
}
*/
void initClients(){
clientListItems.add(new Client("alex", 1265, new Wallet("151516456464564654", 4564.56), R.drawable.ic_launcher_foreground));
clientListItems.add(new Client("mike", 26, new Wallet("465456445644123231", 1645.2), R.drawable.ic_launcher_foreground));
clientListItems.add(new Client("tray", 145, new Wallet("12315465489789", 0.00), R.drawable.ic_launcher_foreground));
clientListItems.add(new Client("vincent", 999, new Wallet("3213546549789", 1000000.01), R.drawable.ic_launcher_foreground));
clientListItems.add(new Client("venom", 666, new Wallet("321154654654798", 145.6), R.drawable.ic_launcher_foreground));
}
void setAddingDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
Dialog alertDialog = builder.create();
final EditText clientName = (EditText) alertDialog.findViewById(R.id.newClientName);
final EditText clientId = (EditText) alertDialog.findViewById(R.id.newClientId);
final EditText clientWallet = (EditText) alertDialog.findViewById(R.id.newClientWallet);
final EditText clientBalance = (EditText) alertDialog.findViewById(R.id.newClientBalance);
builder.setView(inflater.inflate(R.layout.dialog_add_new_client, null))
.setPositiveButton("add", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String nameValue = clientName.getText().toString().trim();
int idValue = Integer.valueOf(clientId.getText().toString().trim());
String walletValue = clientWallet.getText().toString().trim();
double balanceValue = Double.valueOf(clientBalance.getText().toString().trim());
clientListItems.add(new Client(nameValue, idValue, new Wallet(walletValue, balanceValue), R.drawable.ic_launcher_foreground));
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
})
.show();
}
}
dialog_add_new_client.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/newClientName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginTop="16dp"
android:hint="name"
android:inputType="text" />
<EditText
android:id="#+id/newClientId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginTop="16dp"
android:hint="id"
android:inputType="number" />
<EditText
android:id="#+id/newClientWallet"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginTop="16dp"
android:hint="walletNumber"
android:inputType="text" />
<EditText
android:id="#+id/newClientBalance"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginTop="16dp"
android:hint="balance"
android:inputType="numberDecimal" />
</LinearLayout>

Move this code:
Dialog alertDialog = builder.create();
final EditText clientName = (EditText) alertDialog.findViewById(R.id.newClientName);
final EditText clientId = (EditText) alertDialog.findViewById(R.id.newClientId);
final EditText clientWallet = (EditText) alertDialog.findViewById(R.id.newClientWallet);
final EditText clientBalance = (EditText) alertDialog.findViewById(R.id.newClientBalance);
after
builder.setView(inflater.inflate(R.layout.dialog_add_new_client, null))
.setPositiveButton("add", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String nameValue = clientName.getText().toString().trim();
int idValue = Integer.valueOf(clientId.getText().toString().trim());
String walletValue = clientWallet.getText().toString().trim();
double balanceValue = Double.valueOf(clientBalance.getText().toString().trim());
clientListItems.add(new Client(nameValue, idValue, new Wallet(walletValue, balanceValue), R.drawable.ic_launcher_foreground));
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
When you assign your EditTexts, the dialog custom view is not yet inflated, so they are all null. And also you need to call findViewById on the inflated view and not on the alert dialog.
Don't call show() while you set your custom layout but only in the end, after your textviews initialization, by calling:
alertDialog.show();
EDIT
Declare your EditTexts as global fields of your activity, so they don't need to be final.
Summing up, change your setAddingDialog() this way:
private EditText clientName;
private EditText clientId;
private EditText clientWallet;
private EditText clientBalance;
void setAddingDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.dialog_add_new_client, null);
builder.setView(dialogView)
.setPositiveButton("add", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String nameValue = clientName.getText().toString().trim();
int idValue = Integer.valueOf(clientId.getText().toString().trim());
String walletValue = clientWallet.getText().toString().trim();
double balanceValue = Double.valueOf(clientBalance.getText().toString().trim());
clientListItems.add(new Client(nameValue, idValue, new Wallet(walletValue, balanceValue), R.drawable.ic_launcher_foreground));
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
Dialog alertDialog = builder.create();
clientName = (EditText) dialogView.findViewById(R.id.newClientName);
clientId = (EditText) dialogView.findViewById(R.id.newClientId);
clientWallet = (EditText) dialogView.findViewById(R.id.newClientWallet);
clientBalance = (EditText) dialogView.findViewById(R.id.newClientBalance);
alertDialog.show();
}
UPDATE
You need to call findViewById on the inflated view and not on the alert dialog. Check the code I updated.

Just add your dialog layout before this-:
builder.setContentView(R.layout.dialog_add_new_client);
final EditText clientName = (EditText) alertDialog.findViewById(R.id.newClientName);
final EditText clientId = (EditText) alertDialog.findViewById(R.id.newClientId);
final EditText clientWallet = (EditText) alertDialog.findViewById(R.id.newClientWallet);
final EditText clientBalance = (EditText) alertDialog.findViewById(R.id.newClientBalance);
builder.setPositiveButton("add", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String nameValue = clientName.getText().toString().trim();
int idValue = Integer.valueOf(clientId.getText().toString().trim());
String walletValue = clientWallet.getText().toString().trim();
double balanceValue = Double.valueOf(clientBalance.getText().toString().trim());
clientListItems.add(new Client(nameValue, idValue, new Wallet(walletValue, balanceValue), R.drawable.ic_launcher_foreground));
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
})
.show();
}
}
You need to add layout content first then initialize the edittexts.

Related

androidstudio recyclerview and custom dialog

I want to create a custom dialog with a recycler view on it. If I choose the recycler view cell and press ok button in dialog, then the textview will change. I created recycler view adapter, custom dialog, but I don't know how to connect dialog and adapter and what to put in onClick function..help me please..
custom_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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/writing_dialog"
android:layout_width="match_parent"
android:layout_height="400dp">
<TextView
android:id="#+id/textView8"
android:layout_width="0dp"
android:layout_height="50dp"
android:fontFamily="#font/nexon"
android:text="choose!"
android:textAlignment="center"
android:gravity="center"
android:textColor="#341867"
android:textSize="20dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/writing_dialog_ok"
android:layout_width="65dp"
android:layout_height="39dp"
android:layout_marginEnd="20dp"
android:background="#00FFFFFF"
android:fontFamily="#font/nexon"
android:text="ok"
android:textColor="#341867"
android:textSize="15dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="#+id/guideline6" />
<Button
android:id="#+id/writing_dialog_cancel"
android:layout_width="65dp"
android:layout_height="39dp"
android:layout_marginEnd="30dp"
android:background="#00FFFFFF"
android:text="cancel"
android:textColor="#341867"
android:textSize="15dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/writing_dialog_ok"
app:layout_constraintTop_toTopOf="#+id/guideline6" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_begin="355dp" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/writing_dialog_recy"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="20dp"
app:layout_constraintBottom_toTopOf="#+id/guideline6"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView8" />
</androidx.constraintlayout.widget.ConstraintLayout>
recyclerview cell
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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/dialog_container"
android:layout_width="match_parent"
android:layout_height="45dp">
<RadioButton
android:id="#+id/dialog_radio"
android:layout_width="0dp"
android:layout_height="45dp"
android:fontFamily="#font/nexon"
android:text="시리즈 1"
android:textSize="18dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
recycler view adapter
public class WritingNovelAdapter extends RecyclerView.Adapter<WritingNovelAdapter.Holder>{
private Context context;
private ArrayList<WritingNovel_data> dataList;
public WritingNovelAdapter(Context context, ArrayList<WritingNovel_data> dataList){
this.context = context;
this.dataList = dataList;
}
public static class Holder extends RecyclerView.ViewHolder{
protected ConstraintLayout dialog_container;
protected RadioButton dialog_radio;
public Holder(View view){
super(view);
this.dialog_container = view.findViewById(R.id.dialog_container);
this.dialog_radio = view.findViewById(R.id.dialog_radio);
}
}
#Override
public WritingNovelAdapter.Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.writing_dialog_cell, parent, false);
Holder holder = new WritingNovelAdapter.Holder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull WritingNovelAdapter.Holder holder, final int position) {
String title = dataList.get(position).title;
if(title.length() > 16){
title = title.substring(0, 15) + "…";
}
holder.dialog_radio.setText(title);
holder.dialog_container.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
//????????????????????????????
}
});
}
#Override
public int getItemCount() {
if(dataList == null){
return 0;
}
else{
return dataList.size();
}
}
}
custom dialog class
class CustomDialog {
private Context context;
public CustomDialog(Context context)
{
this.context = context;
}
public void callDialog()
{
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.writing_novel_series_dialog);
dialog.show();
final RecyclerView writing_dialog_recy = dialog.findViewById(R.id.writing_dialog_recy);
final Button writing_dialog_ok = dialog.findViewById(R.id.writing_dialog_ok);
final Button writing_dialog_cancel = dialog.findViewById(R.id.writing_dialog_cancel);
writing_dialog_ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
writing_dialog_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
}
====EDIT-1====
I call my dialog in here!
public class writing_novel extends AppCompatActivity {
private static final int GALLERY_REQUEST = 979;
private RichEditor mEditor;
private ColorPicker colorPicker;
androidx.appcompat.app.AlertDialog.Builder textSizeDialogBuilder;
private NumberPicker textPicker;
androidx.appcompat.app.AlertDialog.Builder youtubeDialogBuilder;
private EditText etYoutubeUrl;
private Button writing_novel_btn_series;
private ImageButton writing_novel_novel_ibtn_next;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:{
finish();
return true;
}
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_writing_novel);
Toolbar toolbar = findViewById(R.id.writing_novel_main_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
writing_novel_novel_ibtn_next = findViewById(R.id.writing_novel_novel_ibtn_next);
writing_novel_novel_ibtn_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(writing_novel.this);
builder.setTitle("정말 다음으로 넘어가시겠습니까?").setMessage("다음으로 넘어가기전, 한번 더 검토해주세요.");
builder.setPositiveButton("넘어가기", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int id)
{
Toast.makeText(getApplicationContext(), "OK Click", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(writing_novel.this, decide_novel_title.class);
startActivity(intent);
}
});
builder.setNegativeButton("취소", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int id)
{
Toast.makeText(getApplicationContext(), "Cancel Click", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
builder.setCancelable(false);
builder.create().show();
}
});
writing_novel_btn_series = findViewById(R.id.writing_novel_btn_series);
writing_novel_btn_series.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle args = new Bundle();
args.putString("id", "");
DialogFragment dialogFragment = new DialogFragment();
dialogFragment.setArguments(args);
dialogFragment.show(getFragmentManager(), "id");
CustomDialog dialog = new CustomDialog(writing_novel.this);
dialog.show(getSupportFragmentManager(), "CustomDialog");
}
});
If I understand correctly, you are trying to figure out how to display the RecyclerView list of items, and when an item is clicked, show its data in a TextView below. Please correct me if I am wrong.
For the first step, you are close. All you need to do is instantiate a new layout manager and an instance of your adapter class, and pass them to your RecyclerView.
Add this to your CustomDialog class:
public void callDialog() {
...
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context);
writing_dialog_recy.setLayoutManager(layoutManager);
// I'm assumming you are passing a list of data here
WritingNovelAdapter adapter = new WritingNovelAdapter(context, dataList);
writing_dialog_recy.setAdapter(adapter);
...
As for showing the text in the textView, you have a few different ways to implement this. Its hard to say without seeing the rest of the related code, but I would recommend implementing a callback interface and calling the method from your ViewHolder, like so:
Define the interface in your Adapter class
public interface CallbackInterface {
void showText(String text);
}
Implement a callback interface in your CustomDialog class and implement the setText method, which is where you will set the text in the TextView. This will require that you have an instance of the TextView that you want to show that text in, meaning you must call this somewhere: TextView textView = findViewById(R.id.textView8);
class CustomDialog implements CallbackInterface {
...
public void showText(String text) {
textView.setText(text);
}
}
Pass an instance of your CustomDialog to the adapter (make sure to redefine adapter constructor to accept an instance of CustomDialog
public void callDialog() {
...
// I'm assumming you are passing a list of data here
WritingNovelAdapter adapter = new WritingNovelAdapter(context, dataList, this);
writing_dialog_recy.setAdapter(adapter);
...
}
Call the callback method from the adapter class when the recyclerview cell is clicked
public class WritingNovelAdapter extends RecyclerView.Adapter<WritingNovelAdapter.Holder> {
private Context context;
private ArrayList<WritingNovel_data> dataList;
private CallbackInterface callbackInterface;
public WritingNovelAdapter(Context context, ArrayList<WritingNovel_data>
dataList, CallbackInterface callbackInterface){
this.context = context;
this.dataList = dataList;
this.callbackInterface = callbackInterface;
}
...
holder.dialog_container.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
callbackInterface.showText(title);
}
});
}
Edit #1
Your comment stated that your dialog is not showing up. Unless you left some code out of your CustomDialog class, this is because all your CustomDialog class is, is a Java class. You need to extend a superclass such as AlertDialog or DialogFragment. I'll do my best to summarize how to do this, but you should take a look at the android docs -> https://developer.android.com/guide/topics/ui/dialogs
Here is an example of a DialogFragment you could try creating:
public class CustomDialog extends DialogFragment implements CallbackInterface {
private Context context;
private TextView textView;
private RecyclerView writing_dialog_recy;
public CustomDialog(Context context) {
this.context = context;
}
/* This is the method which builds and essentially shows the dialog */
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate your view that contains the recyclerview
View view = inflater.inflate(R.layout.custom_dialog);
// Your text view where you want to show the text after an item is clicked
textView = view.findViewById(R.id.textView8);
// Your recyclerview in your custom_dialog.xml
writing_dialog_recy = view.findViewById(R.id.writing_dialog_recy);
// Create the layout manager
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context);
writing_dialog_recy.setLayoutManager(layoutManager);
// Create and set the adapter
WritingNovelAdapter adapter = new WritingNovelAdapter(context, dataList, this);
writing_dialog_recy.setAdapter(adapter);
builder.setView(view);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// do whatever you want when user clicks the positive button
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create(); // return the dialog builder
}
public void showText(String text) {
textView.setText(text);
}
}
Then in whatever activity you are creating this dialog from, you show the DialogFragment and pass it the activity's FragmentManager and a tag
CustomDialog dialog = new CustomDialog(this);
dialog.show(getSupportFragmentManager(), "CustomDialog");

Seekbar is null, even though it exists

My goal is to access a seekbar. I tried many things, even pulling the Seekbar seekingbar before the override, but I get always the null toast. R.layout.firstLayout, R.layout.secondLayout, R.id.seekingbar, they all exist.
This is my abbreviated code
public class MainActivity extends AppCompatActivity {
SeekBar seekingbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekingbar = (SeekBar) findViewById(R.id.seekingbar);
LayoutInflater inflater = getLayoutInflater();
final View firstLayout = inflater.inflate(R.layout.firstLayout, null);
final View secondLayout = inflater.inflate(R.layout.secondLayout, null);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog dialog = new AlertDialog.Builder(MainActivity.this)
.setPositiveButton("Forward", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
AlertDialog dialog2 = new AlertDialog.Builder(MainActivity.this)
.setView(secondLayout)
.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (seekingbar == null)
{
Toast.makeText(MainActivity.this,"Null",Toast.LENGTH_LONG).show();
}
}
}).create();
dialog2.show();
}
}).create();
dialog.show();
}
});
}
}
firstLayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/seekbarll"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
tools:context=".MainActivity">
<SeekBar
android:id="#+id/seekingbar"
style="#style/Widget.AppCompat.SeekBar.Discrete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="10"
android:min="0"
android:progress="3" />
</LinearLayout>
Try to find the seekBar in the firstLayout after declaring it:
"firstLayout.findViewById(R.id.seekbar)"

How to call android:onClick on xml button under another xml listview using fragment?

I tried this method and inflate home.xml in my HomeFragment.java:
public View onCreateView(#NonNull LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.home, container, false);
return root;
}
public void OnClickOnTransit(View v){
final Button n = (Button) v;
final String id = n.getTag().toString();
AlertDialog.Builder builderSingle = new AlertDialog.Builder(getContext());
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1);
arrayAdapter.add("Tag as On Transit");
arrayAdapter.add("Cancel");
builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String strOption = arrayAdapter.getItem(which);
if(strOption.equalsIgnoreCase("Tag as On Transit"))
{
Tag_as_on_transit(id);
}
else if(strOption.equalsIgnoreCase("Cancel"))
{
//confirmViewLeveling(emp_tag[1],emp_name.getText().toString());
}
else
{
}
}
});
builderSingle.show();
}
Here is my home.xml where i put my listview.
<ListView
android:id="#+id/lv_customer"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
And this is my nested_listview.xml where my button was placed.
<Button
android:id="#+id/btn_ontransit"
android:layout_width="40dip"
android:layout_height="40dip"
android:background = "#drawable/ic_local_shipping_orange_24dp"
android:textColor="#ff4500"
android:textStyle="bold"
android:text=""
android:textSize="25sp"
android:onClick="OnClickOnTransit"/>
What i want is to call OnClickOnTransit from nested_listview.xml. Thanks in advance!
In that case your parentActivity must have this method
public void OnClickOnTransit(View v){
}
However if you don't want that, You can implement like this in your fragment's onViewcreated method.
Button btn_conferma = (Button) view.findViewById(R.id.btn_conferma);
btn_conferma.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// do something
}
});

Prevent User from closing alert Dialog if EditText is empty

I'm using AlertDialog Box with EditText where user input his name. I would like to prevent the alertDialog from closing when EditText is Empty.
Below is my code
private void request_user_name() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Enter name:");
final EditText input_field = new EditText(this);
input_field.setText(sharedpreferences.getString("username",""));
final SharedPreferences.Editor editor = sharedpreferences.edit();
builder.setCancelable(false);
builder.setView(input_field);
String savedName = sharedpreferences.getString(username,"");
input_field.setText(savedName);
input_field.setSelection(input_field.getText().length());
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
name = input_field.getText().toString();
editor.putString(username, name);
editor.apply();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
request_user_name();
}
});
builder.show();
}
I tried to insert
if(TextUtils.isEmpty(name)) {
input_field.setError("Your message");
return;
}
Inside the AlertDialog Box like this, but it didn't work
private void request_user_name() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Enter name:");
final EditText input_field = new EditText(this);
input_field.setText(sharedpreferences.getString("username",""));
final SharedPreferences.Editor editor = sharedpreferences.edit();
builder.setCancelable(false);
builder.setView(input_field);
String savedName = sharedpreferences.getString(username,"");
input_field.setText(savedName);
input_field.setSelection(input_field.getText().length());
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
name = input_field.getText().toString();
if(TextUtils.isEmpty(name)) {
input_field.setError("Your message");
return;
}
editor.putString(username, name);
editor.apply();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
request_user_name();
}
});
builder.show();
}
Below is the image file, I have
and the image what I would like to get
Thanks in advance.
Use setCancelable(false).
Just set this
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Enter name:");
builder.setCancelable(false);
You see the AlertDialog use a default click listener which after forwarding the click call dismiss by default.
In your case you have to override the default click listener from dialog itself to define your custom behavior for dialog:
//Create the AlertDialog with a reference to edit it later
final AlertDialog dialog = new AlertDialog.Builder(context)
.setView(v)
.setTitle(R.string.my_title)
.setCancelable(false)
.setPositiveButton(android.R.string.ok, null) //Set to null. We override the onclick
.setNegativeButton(android.R.string.cancel, null)
.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialogInterface) {
Button button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Check if your condition is met, Dismiss once everything is OK.
dialog.dismiss();
}
});
}
});
dialog.show();
Try this sample i made. First you have to create a layout for your dialog, just customize it according to your needs.
//R.layout.new_message_dialog
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/checker_txt_frame"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/pin_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send message to?"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<EditText
android:id="#+id/pin_txt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="Name"
android:inputType="text"
android:padding="10dp"
android:layout_marginTop="10dp"
android:cursorVisible="false"
android:singleLine="true" />
<TextView
android:id="#+id/pin_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:padding="10dp"
android:text="Confirm"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/colorAccent" />
</LinearLayout>
Then inflate the view and set it to your builder.
View view = getLayoutInflater().inflate(R.layout.new_message_dialog, null, false);
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setView(view);
TextView tvConfirmBtn = view.findViewById(R.id.pin_btn);
final EditText txtName = view.findViewById(R.id.pin_txt);
final AlertDialog dialog = builder.create();
dialog.show();
tvConfirmBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = txtName.getText().toString().trim();
if (name.isEmpty()) {
txtName.setError("Please provide a name.");
txtName.requestFocus();
} else {
//do something here
dialog.dismiss();
}
}
});

AlertDialog Builder OnItemSelectedListener

I have a tyny, but annoying problem with the AlertDialog Builder.
I want to handle an item select in a custom made AlertDialog, but OnItemSelectedListener doesn't seem to pick my clicks.
Custom Dialog:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="200dp"
android:layout_height="120dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="60dp"
android:background="#AAFFFFFF"
android:orientation="vertical">
<TextView
android:text="English"
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="#+id/lang_english"
android:gravity="center_vertical"
android:background="#color/borders"
android:paddingLeft="10dp"
android:onClick="onLanguageButtonClicked" />
<View
android:layout_height="1dp"
android:layout_width="match_parent"
android:background="#000000" />
<TextView
android:text="عربى"
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="#+id/lang_arabic"
android:gravity="center_vertical"
android:background="#color/borders"
android:paddingRight="10dp"
android:onClick="onLanguageButtonClicked" />
<View
android:layout_height="1dp"
android:layout_width="match_parent"
android:background="#2e2e2e"/>
<TextView
android:text="کوردی "
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="#+id/lang_kurdish"
android:gravity="center_vertical"
android:background="#color/borders"
android:paddingRight="10dp"
android:onClick="onLanguageButtonClicked" />
</LinearLayout>
On button click I open the dialog and handle it:
public void onClickDrawer(View view) {
switch (view.getId()) {
case R.id.button_account_language:
handleLanguageDialog();
break;
case R.id.button_account_currency:
handleCurrencyDialog();
break;
default:
break;
}
}
And the handler:
private void handleLanguageDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(R.layout.dialog_language);
builder.setOnItemSelectedListener(new AdapterView.
OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
Log.i("info", "pressed" + Integer.toString(position));
restartInLocale(new Locale(preferences.getString("locale","")));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
builder.setNegativeButton("CANCEL", new DialogInterface
.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.create().show();
}
Is this the correct approach or am I missing something?
Thank you in advance!
I don't this is correct Approach, you are making it very much complex. If I am not wrong then you are trying to show Language selection dialog for that you should follow the below given steps.
Create string-array inside strings.xml resource file
<string-array name="lang">
<item>English</item>
<item>عربى</item>
</string-array>
When you want to show alert dialog write down below code
private void handleLanguageDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.pick_color)
.setItems(R.array.lang, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch(which)
{
case 0:// English
break;
case 1:// عربى
break;
}
}
});
return builder.create();
}
This is the simplest way to show list of languages in alert dialog and without any positive or negative button .
It looks a bit off. It should look like this:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog_signin, null))
// Add action buttons
.setPositiveButton(R.string.signin, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// sign in the user ...
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
LoginDialogFragment.this.getDialog().cancel();
}
});
return builder.create();
}
https://developer.android.com/guide/topics/ui/dialogs.html
private void handleLanguageDialog() {
ArrayList<String> listItems = new ArrayList<>();
listItems.add("English");
listItems.add("Arabic");
new AlertDialog.Builder(this)
.setTitle("title")
.setCancelable(false)
.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// sign in the user ...
}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
}).show();
}
Try to use setOnItemClick listener on the list/spinner view whichever you are using to display the list instead of builder itself. Like if you are using spinner to show the list use-
final Spinner spinner = (Spinner) layout.findViewById(R.id.spinner); spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
int item = spinner.getSelectedItemPosition();
commandWriter(item);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Try this: add click listener to the language item in your Dialog
onItemSelected() is applied for listview or spinner items your Dialog layout dialog_language does not have those.
Try this code:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Get the layout inflater
LayoutInflater inflater =getLayoutInflater();
View myview = inflater.inflate(R.layout.dialog_language, null);
// Inflate and set the layout for the dialog
builder.setView(myview);
TextView english = (TextView) myview.findViewById (R.id.lang_english);
english.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//do some stuff
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Log.i("info", "pressed" + Integer.toString(position));
restartInLocale(new Locale(preferences.getString("locale","")));
}
});
TextView arabic = (TextView) myview.findViewById (R.id.lang_arabic);
arabic.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//do other stuff
}
});
// Add action buttons
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.show();

Categories