-1

So I am creating my first functional app, i.e. I am still very new to android development and coding in general. So in my app I have Alert dialog pop up each time I want to insert a new contact( it contains street address, phone number and date). Here is some of the code.

package com.profiapp.profi;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

public class DataListFragment extends Fragment {

    private RecyclerView contactList;
    private ContactListAdapter adapter;
    private LinearLayoutManager layoutManager;
    private SQLiteDatabase mDatabase;
    private static DataListFragment instance;
    private AlertDialog optionDialog;


    public DataListFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        contactList = (RecyclerView) inflater.inflate(R.layout.fragment_data_list,
                container, false);

        layoutManager = new LinearLayoutManager(getActivity());
        contactList.setLayoutManager(layoutManager);

        ProfiDatabase profi = new ProfiDatabase(getContext());
        mDatabase = profi.getWritableDatabase();


        adapter = new ContactListAdapter(getContext(), getAllItems());
        contactList.setAdapter(adapter);
        adapter.setListener(new ContactListAdapter.Listener() {
            @Override
            public void onLongClick(long id, String nr, String ad, String dat) {
                openOptionDialog(id, nr, ad, dat);
            }
        });

        instance = this;

        return contactList;
    }
    public void onStart(){
        super.onStart();
    }



    public Cursor getAllItems() {
        return mDatabase.query(
                ContactContract.ContactEntry.TABLE_NAME,
                null,
                null,
                null,
                null,
                null,
                "_id DESC"
        );
    }

    public static DataListFragment getInstance(){
        return instance;
    }

    public void updateCursor(){
        adapter.swapCursor(getAllItems());
    }

    public void openOptionDialog(final long entryId, final String nr, final String ad, final String dat){

        AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(position == 0){
                    NewContactDialogFragment fragment = new NewContactDialogFragment();
                    fragment.show(getActivity().getSupportFragmentManager(), "contact");
                    fragment.onEditContact(nr, ad, dat);


                }else if(position == 1){
                    deleteEntry(entryId);
                    optionDialog.dismiss();
                }
            }
        } ;

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getLayoutInflater();
        View optionMenu = inflater.inflate(R.layout.fragment_option_alert_dialog, null);
        builder.setView(optionMenu);
        builder.setTitle("Nustatymai");
        ListView optionsList = optionMenu.findViewById(R.id.option_list);
        optionsList.setOnItemClickListener(itemClickListener);
        builder.setNeutralButton(R.string.atsaukti, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setCancelable(true);
        optionDialog = builder.create();
        optionDialog.show();

    }

    public void deleteEntry(long id){
        mDatabase.delete(ContactContract.ContactEntry.TABLE_NAME,
                "_id = ?",
                new String[]{Long.toString(id)});
        updateCursor();
    }
}

package com.profiapp.profi;


import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import static com.profiapp.profi.ProfiDatabase.insertContact;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;



public class NewContactDialogFragment extends DialogFragment {
    private AlertDialog contact;
    private static View dialogView2;
    private View dialogView;
    private EditText numerisMade;
    private EditText addressMade;
    private TextView dateMade;



    public NewContactDialogFragment() {
        // Required empty public constructor
    }

    public class onClick implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.input_date:
                    new DataPickerFragment().show(getActivity().getSupportFragmentManager(),
                            "datapicker");
            }
        }
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();
        dialogView = inflater.inflate(R.layout.fragment_new_contact_dialog, null);
        dialogView2 = dialogView;
        TextView date = dialogView.findViewById(R.id.input_date);
        Date currentDate = Calendar.getInstance().getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String currentDateTimeString = format.format(currentDate);
        date.setText(currentDateTimeString);
        date.setOnClickListener(new onClick());
        final EditText numeris = dialogView.findViewById(R.id.input_number);
        final EditText address = dialogView.findViewById(R.id.input_address);

         TextWatcher textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(!numeris.getText().toString().isEmpty() && !address.getText().toString().isEmpty()
                && numeris.getText().toString().trim().length() == 11 || numeris.getText().toString().trim().length() == 9) {
                    contact.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
                }else{
                    contact.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
                }
            }
        };

         numeris.addTextChangedListener(textWatcher);
         address.addTextChangedListener(textWatcher);


        builder.setView(dialogView)
                .setTitle("Prideti nauja adresata")
                .setPositiveButton(R.string.prideti, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    TextView date = dialogView.findViewById(R.id.input_date);

                        long nr = Long.parseLong(numeris.getText().toString());
                        String adresas = address.getText().toString();
                        String data = date.getText().toString();
                        onPrideti(nr, adresas, data);
                }
            })
                .setNegativeButton(R.string.atsaukti, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dismiss();
                    }
                });

        contact = builder.create();
        contact.setCancelable(true);
        return contact;


    }

    public void onStart(){
        super.onStart();
        contact.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
    }



    public void onPrideti(long nr, String adresas, String data){
        SQLiteOpenHelper profi = new ProfiDatabase(getContext());
        SQLiteDatabase db = profi.getWritableDatabase();
        insertContact(db, adresas, nr, data);
        db.close();
        DataListFragment.getInstance().updateCursor();
    }


    public static void setNewDate(String date){
        TextView dateInput = dialogView2.findViewById(R.id.input_date);
        dateInput.setText(date);
    }

    public void onEditContact(String nr, String adresas, String data){
        numerisMade = dialogView.findViewById(R.id.input_number);
        addressMade = dialogView.findViewById(R.id.input_address);
        dateMade = dialogView.findViewById(R.id.input_date);

        numerisMade.setText(nr);
        addressMade.setText(adresas);
        dateMade.setText(data);
    }
}

Now I want to use the same AlertDialog that I use to add new contact to edit details of the contacts. So far I was successful in retrieving the necessary data from my database, however each time I try to add text to the AlertDialog I get this exception "Attempt to invoke virtual method on a null object reference". I kinda get that when I call for a setter method (onEditContact()) to set the values for my AlertDialog the views are not yet initialized and therefore the exception but I would like to know is there any way to go around this and populate the views after they have been created together with the AlertDialog ?

  • 1
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Tamir Abutbul Jan 29 '19 at 15:21
  • Thank you for the link but it is not a duplicate of that since I asked a question how to fix an issue and if it is even possible and not a more in detailed explanation of what null exception is... – Tavo Meile Jan 30 '19 at 07:05

1 Answers1

0

I resolved the problem by creating an identical AlerDialog fragment and passing my values to its onCreate method rather then trying to pass the data after it has been created. Do not know if is the proper way to do it but it worked like a charm