Android SetText while using Try Statement - java

So I have been researching for about 4 hours now on how I can fix this issue I am having.
Basically I am trying to create a Alert box and use data from a cursor to set the text of a TextView and the data is there but once i try to set it i get a null object reference everytime and I refuse to move past it :(
Here is the code in question:
public void InputManual(long id) {
#SuppressLint("AndroidLintInflateParams")
final SQLite db = new SQLite(this);
SQLiteDatabase X = db.getReadableDatabase();
Cursor c;
try {
c = X.rawQuery("SELECT Product FROM Inventory WHERE _id =" + id, null);
c.moveToNext();
CreatePopup();
Y = (TextView) findViewById(R.id.product);
Log.v(TAG, "DATA: " + c.getString(c.getColumnIndexOrThrow("Product")).toString());
Y.setText(c.getString(c.getColumnIndexOrThrow("Product")));
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
The data is there when i use Log.v to display it and it is gone when i try to setText.
Here is CreatePopup():
private void CreatePopup() {
LayoutInflater Manual = LayoutInflater.from(this);
final View textEntryView = Manual.inflate(R.layout.update, null);
final EditText infoData = (EditText) textEntryView.findViewById(R.id.InfoData);
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Update Quantity").setView(textEntryView).setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
String Result = infoData.getText().toString();
String Done = "";
if (Result.length() == 0) {
}
}
}).setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
});
alert.show();
}
The XML File:
<?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">
<TextView
android:id="#+id/Information"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:paddingLeft="5dp"
android:text="#string/Product"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/product"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:inputType="none"
android:text="" />
<EditText
android:id="#+id/InfoData"
style="#android:style/TextAppearance.Small"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:hint="#string/hint_data"
android:inputType="number" />
</LinearLayout>
And I have a listView onItemClickListerner that just passes InputManual(id) which would just be the id of the item in the database.
I'm at the point where I want to throw my keyboard because I can't figure out why it becomes null every time I try anything.
Any help would be appreciated even a different approach would be helpful.
My goal is to click on a item in the ListView and generate the Alert box with the item from the list so I can change the quantity to a different value but im just trying to set the TextView to whats in the ListView which is getting data from a database.
I probably didn't explain it correctly but I am willing to give any information that could help me solve this!
Long time browser of stackoverflow and I finally got to the point where I needed help because I can't google anymore :(
The actual error:
inventory W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
inventory V/MyActivity: DATA: CokeD
inventory W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
Thanks!

This error:
inventory W/System.err: java.lang.NullPointerException: Attempt to
invoke virtual method 'void
android.widget.TextView.setText(java.lang.CharSequence)' on a null
object reference
means that the TextView object is null, not the string value that you get from the database.
This means
Y = (TextView) findViewById(R.id.product);
is returning null, possibly because that view is owned by the dialog, not by the activity.
Try passing the string value to the CreatePopup() method as an argument, then you can call setText from there. Like this:
private void CreatePopup(String product) {
LayoutInflater Manual = LayoutInflater.from(this);
final View textEntryView = Manual.inflate(R.layout.update, null);
final EditText infoData = (EditText) textEntryView.findViewById(R.id.InfoData);
//Add these lines
final TextView productText = (TextView) textEntryView.findViewById(R.id.product);
productText.setText(product);
...
}

Got it to work by doing this
private void CreatePopup(Long id) {
LayoutInflater Manual = LayoutInflater.from(this);
final View textEntryView = Manual.inflate(R.layout.update, null);
final EditText infoData = (EditText) textEntryView.findViewById(R.id.InfoData);
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
final TextView TextSet = (TextView) textEntryView.findViewById(R.id.product);
final SQLite db = new SQLite(this);
SQLiteDatabase X = db.getReadableDatabase();
Cursor c;
c = X.rawQuery("SELECT Product FROM Inventory WHERE _id =" + id, null);
c.moveToFirst();
final String Data = c.getString(c.getColumnIndexOrThrow("Product"));
TextSet.setText(Data);
c.close();
alert.setTitle("Update Quantity").setView(textEntryView).setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
String Result = infoData.getText().toString();
if (Result.length() == 0) {
}
}
}).setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
// ScanDataEmpty();
}
});
alert.show();
}
Now I feel dumb.

Related

Null pointer exception on button inside fragment layout android 9 [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I have a button placed inside a layout frag_contacts.xml that is intended for a fragment which is FragmentContacts.java . There is also row layout for the recyclerview which is items_contacts.xml . The button allows a user to save stuff after they are done picking recyclerview items. The app works without any errors on android Nougat .
However When I run the app on android 9 it crushes giving exception java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference.
The line throwing exceptions is the one below
buttonCreateGroup.setOnClickListener(this);
the error message
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ex_contactapp, PID: 3931
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.ex_contactapp.fragments.FragmentContacts.onCreateView(FragmentContacts.java:99)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2439)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:802)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
at androidx.fragment.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:2243)
at androidx.fragment.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:654)
at androidx.fragment.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:146)
at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1244)
at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1092)
at androidx.viewpager.widget.ViewPager.onMeasure(ViewPager.java:1622)
at android.view.View.measure(View.java:25056)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:7745)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1535)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:825)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:704)
at android.view.View.measure(View.java:25056)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:7745)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
at android.view.View.measure(View.java:25056)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:7745)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1535)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:825)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:704)
at android.view.View.measure(View.java:25056)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:7745)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:25056)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:7745)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1535)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:825)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:704)
at android.view.View.measure(View.java:25056)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:7745)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at com.android.internal.policy.DecorView.onMeasure(DecorView.java:1051)
at android.view.View.measure(View.java:25056)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:3382)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:2104)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2403)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1964)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8721)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:988)
at android.view.Choreographer.doCallbacks(Choreographer.java:765)
at android.view.Choreographer.doFrame(Choreographer.java:700)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:967)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7285)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
layout for fragment - frag_contacts.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimaryDark">
<GridLayout
android:layout_width="wrap_content"
android:layout_height="100dp">
<EditText
android:id="#+id/group_name"
android:layout_width="263dp"
android:layout_height="70dp"/>
<Button
android:id="#+id/buttonCreateGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/create_group"/>
</GridLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rv_contacts"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
Row layout -> items_contacts.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:layout_margin="10dp"
android:weightSum="10">
<Button
android:layout_gravity="center"
android:background="#drawable/ic_person"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="32dp"/>
<LinearLayout
android:padding="10dp"
android:layout_width="0dp"
android:layout_weight="8"
android:orientation="vertical"
android:layout_height="wrap_content">
<TextView
android:id="#+id/contact_name"
android:text="name"
android:textSize="20sp"
android:textColor="#android:color/white"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/contact_number"
android:text="number"
android:textSize="16sp"
android:textColor="#android:color/white"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<CheckBox
android:id="#+id/contact_checkbox"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:layout_height="32dp"
android:layout_weight="1"/>
</LinearLayout>
Recycler View Adapter class -ContactsRvAdapter.java
public class ContactsRvAdapter extends RecyclerView.Adapter<ContactsRvAdapter.ViewHolder> {
private Context mContext;
private LayoutInflater inflater;
private List<ModelContacts> mlistContacts;
private CheckedStatusListener mcheckedStatusListener;
public interface CheckedStatusListener{
//String firstName, String lastName, String middleName, #NonNull String phoneNumber,#NonNull int groupid
void onItemChecked(String name, String phonenumber);
void onItemUnchecked(String name, String phonenumber);
}
public ContactsRvAdapter(Context context, List<ModelContacts> listContacts,CheckedStatusListener checkedStatusListener){
mlistContacts = listContacts;
mContext = context;
mcheckedStatusListener = checkedStatusListener;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.items_contacts,parent,false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
final TextView contact_name,contact_number;
final CheckBox contact_checkbox;
contact_name = holder.contact_name;
contact_number = holder.contact_number;
contact_name.setText(mlistContacts.get(position).getName());
contact_number.setText(mlistContacts.get(position).getNumber());
contact_checkbox = holder.contactSelectedCheckBox;
contact_checkbox.setOnClickListener(v -> {
if (contact_checkbox.isChecked()){
mcheckedStatusListener.onItemChecked(mlistContacts.get(position).getName(),mlistContacts.get(position).getNumber());
}else{
mcheckedStatusListener.onItemUnchecked(mlistContacts.get(position).getName(),mlistContacts.get(position).getNumber());
}
});
}
#Override
public int getItemCount() {
return mlistContacts.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView contact_name,contact_number;
CheckBox contactSelectedCheckBox;
public ViewHolder(View itemView){
super(itemView);
contact_name = itemView.findViewById(R.id.contact_name);
contact_number = itemView.findViewById(R.id.contact_number);
contactSelectedCheckBox = itemView.findViewById(R.id.contact_checkbox);
}
}
}
Fragment class - FragmentContacts.java
public class FragmentContacts extends Fragment implements ContactsRvAdapter.CheckedStatusListener, View.OnClickListener{
private View v;
private RecyclerView recyclerView;
private List<ModelContactsBuffer> currentSelectedContacts = new ArrayList<>();
ContactsRvAdapter adapter;
private EditText editTextGroupName;
private ContactGroupViewModel contactGroupViewModel;
private ModelContactsBuffer modelContactsBuffer;
private GroupListViewModel groupListViewModel;
public FragmentContacts() {
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.frag_contacts,container,false);
recyclerView = v.findViewById(R.id.rv_contacts);
editTextGroupName = v.findViewById(R.id.group_name);
Button buttonCreateGroup = v.findViewById(R.id.buttonCreateGroup);
buttonCreateGroup.setOnClickListener(this);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
RecyclerView.LayoutManager layoutManager= linearLayoutManager;
recyclerView.setLayoutManager(layoutManager);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M &&
ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.READ_CONTACTS},1);
}else {
adapter = new ContactsRvAdapter(getContext(), getContacts(),this);
recyclerView.setItemViewCacheSize(getContacts().size());
recyclerView.setAdapter(adapter);
// adapter.notifyDataSetChanged();
}
contactGroupViewModel = ViewModelProviders.of(this, new ContactGroupViewModel.Factory(Objects.requireNonNull(getActivity()).getApplicationContext())).get(ContactGroupViewModel.class);
groupListViewModel = ViewModelProviders.of(this,new GroupListViewModel.Factory(getActivity().getApplicationContext())).get(GroupListViewModel.class);
return v;
}
#Override
public void onClick(View v) {
Log.i("editTextGroupNamelength", String.valueOf(editTextGroupName.getText().toString().length()));
if (editTextGroupName.getText().toString().length() > 2) {
if(currentSelectedContacts.size() > 4){
contactGroupViewModel.createGroup(editTextGroupName.getText().toString(),String.valueOf(currentSelectedContacts.size()));
Integer groupId = contactGroupViewModel.readGroupId(editTextGroupName.getText().toString());
insertGrouplist(groupId);
//clearFields();
}else{
new AlertDialog.Builder(Objects.requireNonNull(this.getActivity()))
.setIcon(R.drawable.ic_error)
.setTitle("Insufficient group members")
.setMessage("A group should have at least 5 members")
.setNeutralButton("Ok",null)
.show();
}
}else{
new AlertDialog.Builder(Objects.requireNonNull(this.getActivity()))
.setIcon(R.drawable.ic_error)
.setTitle("Group name is too short")
.setMessage("A group should have atleast be 3 characters long")
.setNeutralButton("Ok",null)
.show();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == 1){
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
//now permission is granted call function again
adapter = new ContactsRvAdapter(getContext(), getContacts(),this);
recyclerView.setItemViewCacheSize(getContacts().size());
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
}
private List<ModelContacts> getContacts(){
List<ModelContacts> list = new ArrayList<>();
try{
String[] PROJECTION = new String[] {
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Photo.CONTACT_ID };
String selectionFields = ""+ ContactsContract.Contacts.HAS_PHONE_NUMBER + " > 0 and " + ContactsContract.CommonDataKinds.Phone.TYPE +"=" + ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;
String[] selectionArgs = new String[]{"com.google"};
Cursor cursor = getContext().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
PROJECTION,selectionFields,null,ContactsContract.Contacts.DISPLAY_NAME + " ASC");
cursor.moveToFirst();
while(cursor.moveToNext()){
list.add(new ModelContacts(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID)),
cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)),
cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))));
}
}catch (Exception e){
Toast.makeText(getContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
return list;
}
#Override
public void onItemChecked(String name, String phonenumber) {
String firstName = " ";
String lastName = " ";
if(name.split("\\w+").length>1){
lastName = name.substring(name.lastIndexOf(" ")+1);
firstName = name.substring(0,name.lastIndexOf(' '));
}else{
firstName = name;
lastName = " ";
}
modelContactsBuffer = new ModelContactsBuffer(firstName,lastName,phonenumber);
currentSelectedContacts.add(modelContactsBuffer);
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onItemUnchecked(String name, String phonenumber) {
String firstName = " ";
String lastName = " ";
if(name.split("\\w+").length>1){
lastName = name.substring(name.lastIndexOf(" ")+1);
firstName = name.substring(0,name.lastIndexOf(' '));
}else{
firstName = name;
lastName = " ";
}
currentSelectedContacts.removeIf( currentSelectedContact -> currentSelectedContact.getPhoneNumber().equals(phonenumber));
}
public void insertGrouplist(int groupId){
for (ModelContactsBuffer currentSelectedContact : currentSelectedContacts) {
groupListViewModel.createGroupList(currentSelectedContact.getFirstName(), currentSelectedContact.getLastName(), " ", currentSelectedContact.getPhoneNumber(), groupId);
}
clearFields();
}
}
I commented the line throwing an exception and the app runs pretty well. Hence the problem is from buttonCreateGroup.setOnClickListener(this);
I have tried many solutions here in stack overflow which didnt work.
I have checked the id of the button and it is correct
I don't think it is possible initializing the onclicklistener inside ContactsRvAdapter because its not even in the row layout. It is in the other layout wwhich is intended for the fragment
I tried passing the normal new OnViewClicklistener to the button instead of passing the whole activity but nothong changed. Still getting an error
I later on moved the clicklistener call from public View onCreateView() to public void onViewCreated() but there was no change. I am stil getting the same error.
I tried removing #RequiresApi(api = Build.VERSION_CODES.N) Nothing changed
Kindly note I am not a professional on android. I added some things like #RequiresApi(api = Build.VERSION_CODES.N) because android lint would show an error and that was the only way I could deal with it at that time. I apprectiate any help offered on solving this
You probably get this error(null object reference) because you didn't define the button. You have to define like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_contacts, container, false);
Button buttonCreateGroup = view.findViewById(R.id.buttonCreateGroup);
buttonCreateGroup.setOnClickListener(this);
return view;
}
Or this func:
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button buttonCreateGroup = view.findViewById(R.id.buttonCreateGroup);
buttonCreateGroup.setOnClickListener(this);
}
edit func.
So for some apparent reason I didn't think about the fact that I had two xml files for frag_contacts, one in res/layouts and another in res/layout-v26
I admit I am not a pro on android and I kinda auto generated the latter xml file without knowing its use but I still continued working on the on in res/layouts & fully abandoned the one in res/layout-v26 because I didn't know it's use.
However it did have a button and a couple of other widgets but with no ID. Since it was in res/layout-v26 meaning it would show for devices compatible with v-26 and totally ignore the one on res/layouts, that's the layout file that would show on android 9 device. & since the button didn't have an ID, a null pointer exception would be thrown.
I have deleted the layout-v-26 file so that devices will fallback to the default layout. The app now works fine.

Inflated layout to alertdialog doesn't work

I have the following method where I must confirm the user's password before he is allowed to access the Setup menu. To do so, I make him login again because Parse (my cloud storage) doesn't allow me to confirm passwords. So far so good. The problem is when I inflate the view to my AlertDialog to use a custom button and EditText. You can see in my code below that I have commented the Button section, because when I try to get the onClickListener it doesn't work. It just does nothing. So I'm currently using the alertDialogPositiveButton and it's ok. The second problem and the real one is that I cannot retrieve the data insert into the editText. The SUpassword3is always equals to blank, not null. Can someone please help?
method:
public void confirmPassword(){
final LayoutInflater inflateSetup = getLayoutInflater();
AlertDialog.Builder alertSetup = new AlertDialog.Builder(this);
alertSetup.setView(inflateSetup.inflate(R.layout.inflate_setup, null));
alertSetup.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
System.out.println("User has clicked the [confirm] button");
View viewInflate_setup = inflateSetup.inflate(R.layout.inflate_setup, null);
edtPassword3 = (EditText)viewInflate_setup.findViewById(R.id.edtPassword3);
SUpassword3 = edtPassword3.getText().toString();
final ParseUser beforeConfirmPassword = ParseUser.getCurrentUser();
ParseUser.logInInBackground(beforeConfirmPassword.getUsername(), SUpassword3, new LogInCallback() {
#Override
public void done(ParseUser parseUser, ParseException e) {
if(e==null){
//password confirmed, logout last user and go to next setup
System.out.println("Password [" +SUpassword3+ "] and user [" +beforeConfirmPassword.getUsername()+ "] confirmed, logout last user and go to setup");
beforeConfirmPassword.logOut();
}else{
//passwords don't match
System.out.println("Password don't match: [" +SUpassword3 + "] USER [" +beforeConfirmPassword.getUsername()+ "]");
}
}
});
}
});
final AlertDialog dialogSetup = alertSetup.create();
dialogSetup.show();
/**
btnConfirmPassowod = (Button)viewInflate_setup.findViewById(R.id.btnConfirm);
btnConfirmPassowod.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
System.out.println("User has clicked the [confirm] button");
final ParseUser beforeConfirmPassword = ParseUser.getCurrentUser();
ParseUser.logInInBackground(beforeConfirmPassword.getUsername(), SUpassword3, new LogInCallback() {
#Override
public void done(ParseUser parseUser, ParseException e) {
if(e==null){
//password confirmed, logout last user and go to next setup
System.out.println("Password confirmed, logout last user and go to setup");
beforeConfirmPassword.logOut();
}else{
//passwords don't match
dialogSetup.dismiss();
Snackbar.make(v, "Wrong password, try again.", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
}
});
}
}); */
}
inflate_setup.xml(the xml file I inflate on the alertDialog)
<?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:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/edtPassword3"
android:layout_gravity="center_horizontal"
android:hint="#string/EN_txt.confirmPassword"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/btnConfirm"
android:layout_gravity="center_horizontal" />
</LinearLayout>
Final version(working):
public void confirmPassword(){
final LayoutInflater inflateSetup = getLayoutInflater();
final View viewInflate_setup = inflateSetup.inflate(R.layout.inflate_setup, null);
AlertDialog.Builder alertSetup = new AlertDialog.Builder(this);
alertSetup.setView(viewInflate_setup);
alertSetup.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
System.out.println("User has clicked the [confirm] button");
edtPassword3 = (EditText)viewInflate_setup.findViewById(R.id.edtPassword3);
SUpassword3 = edtPassword3.getText().toString();
...
You inflate another view inside your onClickListener. That's why you actually check text of another edtPassword3, not that one which visible for user. It should be something like that:
View view = inflateSetup.inflate(R.layout.inflate_setup;
final EditText edtPassword3 = (EditText)viewInflate_setup.findViewById(R.id.edtPassword3);
alertSetup.setView(view, null));
alertSetup.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
System.out.println("User has clicked the [confirm] button");
SUpassword3 = edtPassword3.getText().toString();
....
Try to use: Dialog class
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom);
dialog.setTitle("Title...");
Get a reference of the inflated view:
View dialogView = inflateSetup.inflate(R.layout.inflate_setup, null);
In dialog use:
alertSetup.setView(dialogView);
Then, access button using:
Button myButton = (Button) dialogView.findViewById(R.id.btnConfirm);

Trouble with my custom layout for an Alert Dialog

Making a to-do list. Having 2 issues, The not so important issue is that for some reason I can't see the TextView's that I set up as "labels". The more important thing is that when I click the create new task button, my alert pops up, I can put values in my EditText boxes, but when I hit create, it crashes and I get a NullPointer exception saying I'm trying to call getText() on a null object reference. I can't figure out if I'm inflating incorrectly or if I'm not linking the EditTexts to the alert properly. The annoying thing is that my edittext alert box works just fine editing existing list items(that I hardcoded for testing). Here's my layout and activity, I commented the line in which it breaks. Sorry about all the Log.d's I'm really trying to visualize how all this works.
The Layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<EditText
android:layout_width="55dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/txtCreatePriority"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="25dp"
android:hint="1"
android:textAlignment="center" />
<EditText
android:layout_width="235dp"
android:layout_height="wrap_content"
android:id="#+id/txtCreateItemContent"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/txtCreatePriority"
android:layout_toEndOf="#+id/txtCreatePriority"
android:layout_marginLeft="15dp"
android:hint="Do Laundry"
android:textAlignment="center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Priority"
android:id="#+id/lblPriority"
android:layout_above="#+id/txtCreatePriority"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="17dp"
android:textStyle="bold"
android:textSize="23dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Task to-do"
android:id="#+id/lblItemContent"
android:layout_above="#+id/txtCreateItemContent"
android:layout_toRightOf="#+id/lblPriority"
android:layout_toEndOf="#+id/lblPriority"
android:layout_marginLeft="65dp"
android:textStyle="bold"
android:textSize="23dp" />
</RelativeLayout>
The Activity
public class MainActivity extends AppCompatActivity {
private ListDataSource ds;
private ListView listViewToDo;
private Button btnAddNew;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Context context = this;
Log.d("MainActivity","Attempting to create data source");
try {
ds = new ListDataSource();
}
catch(Exception e)
{
e.printStackTrace();
Log.d("MainActivity","Failed to create data source");
}
btnAddNew = (Button)findViewById(R.id.btnAddNew);
Log.d("Main Activity","Attempting to link empty list view to on screen view");
listViewToDo = (ListView)findViewById(R.id.listOfLists);
Log.d("Main Activity", "Views linked, Attempting to set adapter to listView");
listViewToDo.setAdapter(new ListDataSourceAdapter(this, ds));
Log.d("Main Activity", "Successfully set Adapter");
btnAddNew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("addItem", "Entered onclick, Attempting to create AlertDialog");
AlertDialog.Builder addItem = new AlertDialog.Builder(context);
Log.d("addItem", "AlertDialog Built, attempting to create inflater");
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
addItem.setView(inflater.inflate(R.layout.create_item_layout, null));
Log.d("addItem", "inflater built linking text boxes");
final TextView txtCreatePriority = (TextView)findViewById(R.id.txtCreatePriority);
final TextView txtCreateCellContent = (TextView)findViewById(R.id.txtCreateItemContent);
final TextView lblPriority = (TextView)findViewById(R.id.lblPriority);
final TextView lblItemContent = (TextView)findViewById(R.id.lblItemContent);
addItem.setTitle("Create new item");
addItem
.setCancelable(false)
.setPositiveButton("Create", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("editText onClick", "in onClick method, preparing to add entry");
// This is where the code breaks
ds.getList().add(Integer.valueOf(txtCreatePriority.getText().toString()), new CellContent(Integer.valueOf(txtCreatePriority.getText().toString()) + 1, txtCreateCellContent.getText().toString().trim()));
Log.d("editText onClick", "added new entry");
ListDataSourceAdapter adapter = new ListDataSourceAdapter(context, ds);
Log.d("editText onClick", "reestablished link to adapter");
listViewToDo.setAdapter(adapter);
Log.d("editText onClick", "adapter set");
adapter.notifyDataSetChanged();
Log.d("editText onClick", "DataSetChanged");
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = addItem.create();
alertDialog.show();
}
});
// add button listener
listViewToDo.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id)
{
AlertDialog.Builder editItem = new AlertDialog.Builder(context);
final EditText edittext = new EditText(context);
editItem.setTitle("Change item");
editItem
.setMessage("Set new todo item")
.setView(edittext)
.setCancelable(false)
.setPositiveButton("Submit", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
Log.d("editText onClick","in onClick method, preparing to remove previous entry");
ds.getList().remove(position);
Log.d("editText onClick", "removed previous entry");
ds.getList().add(position, new CellContent(position + 1, edittext.getText().toString().trim()));
Log.d("editText onClick", "added new entry");
ListDataSourceAdapter adapter = new ListDataSourceAdapter(context,ds);
Log.d("editText onClick","reestablished link to adapter");
listViewToDo.setAdapter(adapter);
Log.d("editText onClick", "adapter set");
adapter.notifyDataSetChanged();
Log.d("editText onClick", "DataSetChanged");
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = editItem.create();
alertDialog.show();
}
});
}
}
The Error
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
You're calling "(EditText)v.findViewById" on the view v.
The view v is the view passed back in the onClickListener, which is the button itself.
Since that button does not contain the EditTexts within it, those views are null. And crash when you try to access them.
I'm a little uncertain where the layout with the edit texts is in this code. Is it in the same layout as the listview, or in create_item_layout?
If its create_item_layout, that needs to be inflated before getting the EditTexts. Use the view you inflate to findViewById.

Why can't I make this TextView if the String isn't null? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'd like to create a TextView with the name of the person you've just tapped, but when I tap a name, it prints an error message to the console.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parentView, View childView, int position, long id) {
System.err.println("clicked " + position);
System.err.println("clicked " + friendsIO.getPresentationText(position));
try {
JSONObject friendInformations = new JSONObject(friendsIO.getPresentationText(position));
String friendNames = friendInformations.getString("name");
System.err.println(friendNames);
TextView peopleName = (TextView) findViewById(R.id.peoplePerson);
peopleName.setText(friendNames);
String friendEmails = friendInformations.getString("email");
System.err.println(friendEmails);
String friendNumbers = friendInformations.getString("phone number");
System.err.println(friendNumbers);
String friendEmailsNumbers = friendNames + "\n" + friendEmails;
// TextView peopleInformations = (TextView) findViewById(R.id.peopleInfo);
// peopleInformations.setText(friendEmailsNumbers);
} catch (Exception e) {
e.printStackTrace();
}
final LayoutInflater peopleInflater = LayoutInflater.from(MainActivity.this);
final View peopleView = peopleInflater.inflate(R.layout.popup2, null);
final PopupWindow peoplePopup = new PopupWindow(peopleView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
peoplePopup.showAtLocation(peopleView, Gravity.CENTER, 0, 0);
final Button peopleBack = (Button) peopleView.findViewById(R.id.cancel_button);
peopleBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
peoplePopup.dismiss();
}
}
);
I print the name to the console first, to make sure that it actually exists and I get the name I tapped (as well as the email and number, obviously), but instead of printing the name to the screen in a TextView, it gives me the following error message:
10-01 17:39:55.505 4259-4259/com.logit.data.returntosender W/System.err﹕ java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
10-01 17:39:55.506 4259-4259/com.logit.data.returntosender W/System.err﹕ at com.logit.data.returntosender.MainActivity$1.onItemClick(MainActivity.java:60)
It says the error is at the line
System.err.println(friendNames);
But the TextView is only actually given afterwards, in line 61. I have tried around a bit, and not found what the problem could be. It's technically exactly how it should be, at least that's what I've been able to gather from other StackOverflow questions and a thorough google search.
The XML file of the popup with the name (and email and phone number, but that's not part of the question):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#color/colorAroundPopups"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical|center_horizontal">
<TextView android:id="#+id/peoplePerson"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorOfPopups"
android:textStyle="bold"
android:text=""
android:textSize="52sp"/>
<TextView android:id="#+id/peopleInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorOfPopups"
android:textStyle="normal"
android:textSize="26sp"/>
<Button android:id="#+id/cancel_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/cancel_it" />
</LinearLayout>
Thanks in advance
-Léon
EDIT: I added the part of the code where the popup, containing the TextView, is created.
EDIT: I found the found the solution. I had to put the name of the view containing the TextView before findViewById
Also, Frank N. Stein, thank you for not helping at all by sending me a question I had already looked through :)
You are retrieving the view from the activity, if the TextView was on the list item view, you would change...
TextView peopleName = (TextView) findViewById(R.id.peoplePerson);
to...
TextView peopleName = (TextView) childView.findViewById(R.id.peoplePerson);
instead of doing this:
TextView peopleName = (TextView) findViewById(R.id.peoplePerson);
do this:
TextView peopleName = (TextView) childView.findViewById(R.id.peoplePerson);
as your textview is a child of the listview.

Alertdialog with checkbox ( Don't show again )

I need to show an AlertDialog with "Don't Show Again" checkbox. I searched, but I couldn't find a working solution :/
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
PackageManager pk = getPackageManager();
Drawable icon;
alertDialogBuilder
.setTitle(R.string.confirm)
.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
//Do something
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
If i'm not wrong then just Make one class extends with View.
public class DialogShow extends View {
SharedPreferences dialogPreferences;
String prefrencestring;
CheckBox nevershowagain;
Button closedialog;
Dialog dialog;
View view;
public DialogShow(final Context context) {
super(context);
dialog = new Dialog(context);
view = View.inflate(context, R.layout.startdialog, null);
dialog.setContentView(view);
nevershowagain = (CheckBox) view.findViewById(R.id.nevershowagain);
closedialog = (Button) view.findViewById(R.id.closedialog);
closedialog.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (nevershowagain.isChecked()) {
prefrencestring = "1";
dialogPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
Editor editprefrences = dialogPreferences.edit();
editprefrences.putString("showdialog", prefrencestring);
editprefrences.commit();
}
dialog.dismiss();
}
});
dialogPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
String check = dialogPreferences.getString("showdialog", "");
if (check.equals("1")) {
} else {
dialog.show();
}
}
}
Now call this class in your splash Activity on onCreate() method..
DialogShow d = new Dialog(this);
You can try this for AlertDialog :
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.myDialogLayout, null));
Dialog d = builder.create();
Edit: Please look into HERE FOR DETAILS EXPLANATION
Pass your view to the setView() method and it will set your view to the dialog body.
alertDialogBuilder.setView(your_view);
Since the accepted answer is not a good one in 2023 (IMO) and this post is the first one on google search, here is my solution:
private void showAlertWithCheck() {
boolean infoShowed = PreferenceManager.getDefaultSharedPreferences(this).
getBoolean(Const.PREF_KEY_INFO_SHOWN, false);
if (!infoShowed) {
View view = getLayoutInflater().inflate(R.layout.dialog_remember_check, null);
final CheckBox chk_drc_Remember = view.findViewById(R.id.chk_drc_Remember);
chk_drc_Remember.setText(R.string.dont_show_again);
chk_drc_Remember.setChecked(true);
new AlertDialog.Builder(MainActivity.this).
setIcon(android.R.drawable.ic_dialog_info).
setMessage(R.string.fixed_info).
setView(view).
setNeutralButton(R.string.caption_ok, null).
setOnDismissListener(dialog ->
PreferenceManager.getDefaultSharedPreferences(this).edit().
putBoolean(Const.PREF_KEY_INFO_SHOWN,
chk_drc_Remember.isChecked()).apply()).
show();
}
}
requied view XML:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:orientation="vertical"
android:padding="#dimen/dialog_padding"
tools:context=".dialogs.PrayTimeDetailDialog"
tools:ignore="RtlHardcoded">
<CheckBox
android:id="#+id/chk_drc_Remember"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:paddingLeft="#dimen/dialog_padding"
android:paddingRight="#dimen/dialog_padding"
android:text="#string/remember_method" />

Categories

Resources