将Firebase和AlertDialog放入单独的类

时间:2017-05-05 17:26:20

标签: android

我正在制作购物清单应用。我想将Firebase和AlertDialog分成不同的类(即Firebase.class和AlertDialog.class)。我已经在这里阅读了所有的答案,并尝试了很多解决方案,但是如果我进行分离,我的应用程序每次都会崩溃(当所有内容都在同一个类中时,它的工作正常)。我很感激任何帮助。以下是我的代码。

编辑:下面这段代码是我的最后一次尝试,有MainActivity,Firebase和DialogAlert类以及输出。请注意,我现在完全在树林里。

**MainActivity.java**

    public class MainActivity extends AppCompatActivity {

    EditText editTextShoppingListName;
    Button buttonAddShoppingList;
    ListView listViewShoppingLists;
    List<ShoppingList> shoppingLists;
    DatabaseReference databaseShoppingLists;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        databaseShoppingLists = FirebaseDatabase.getInstance().getReference("shoppingLists");
        editTextShoppingListName = (EditText) findViewById(R.id.editTextShoppingListName);
        listViewShoppingLists = (ListView) findViewById(R.id.listViewShoppingLists);
        buttonAddShoppingList = (Button) findViewById(R.id.buttonAddShoppingList);
        shoppingLists = new ArrayList<>();

        buttonAddShoppingList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addShoppingList();
            }
        });

        listViewShoppingLists.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ShoppingList shoppingList = shoppingLists.get(i);

                Intent intent = new Intent(getApplicationContext(), ShoppingListActivity.class);
                intent.putExtra(Constants.SHOPPINGLIST_ID, shoppingList.getShoppingListId());
                intent.putExtra(Constants.SHOPPINGLIST_NAME, shoppingList.getShoppingListName());
                startActivity(intent);
            }
        });

        listViewShoppingLists.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                ShoppingList shoppingList = shoppingLists.get(i);
                showUpdateDeleteDialog(shoppingList.getShoppingListId(), shoppingList.getShoppingListName());
                return true;
            }
        });
    }

    private void showUpdateDeleteDialog(final String shoppingListId, String shoppingListName) {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();
        final View dialogView = inflater.inflate(R.layout.update_dialog, null);
        dialogBuilder.setView(dialogView);

        final EditText editTextShoppingListName = (EditText) dialogView.findViewById(R.id.editTextShoppingListName);
        final Button buttonUpdateShoppingList = (Button) dialogView.findViewById(R.id.buttonUpdateShoppingList);
        final Button buttonDeleteShoppingList = (Button) dialogView.findViewById(R.id.buttonDeleteShoppingList);

        dialogBuilder.setTitle(shoppingListName);
        final AlertDialog alertDialog = dialogBuilder.create();
        alertDialog.show();

        buttonUpdateShoppingList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = editTextShoppingListName.getText().toString().trim();
                if (!TextUtils.isEmpty(name)) {
                    updateShoppingList(shoppingListId, name);
                    alertDialog.dismiss();
                }
            }
        });

        buttonDeleteShoppingList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                deleteShoppingList(shoppingListId);
                alertDialog.dismiss();
            }
        });
    }

    private boolean updateShoppingList(String id, String name) {
        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("shoppingLists").child(id);
        ShoppingList shoppingList = new ShoppingList(id, name);
        databaseReference.setValue(shoppingList);
        Toast.makeText(getApplicationContext(), R.string.shopping_list_updated, Toast.LENGTH_LONG).show();
        return true;
    }

    private boolean deleteShoppingList(String id) {
        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("shoppingLists").child(id);
        databaseReference.removeValue();
        DatabaseReference databaseReferenceItems = FirebaseDatabase.getInstance().getReference("items").child(id);
        databaseReferenceItems.removeValue();
        Toast.makeText(getApplicationContext(), R.string.shopping_list_deleted, Toast.LENGTH_LONG).show();
        return true;
    }

    @Override
    protected void onStart() {
        super.onStart();

        databaseShoppingLists.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                shoppingLists.clear();
                for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                    ShoppingList shoppingList = postSnapshot.getValue(ShoppingList.class);
                    shoppingLists.add(shoppingList);
                }
                ListOfShoppingLists shoppingListAdapter = new ListOfShoppingLists(MainActivity.this, shoppingLists);
                listViewShoppingLists.setAdapter(shoppingListAdapter);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });
    }

    private void addShoppingList() {
        String name = editTextShoppingListName.getText().toString().trim();
        if (!TextUtils.isEmpty(name)) {
            String id = databaseShoppingLists.push().getKey();
            ShoppingList shoppingList = new ShoppingList(id, name);
            databaseShoppingLists.child(id).setValue(shoppingList);
            editTextShoppingListName.setText("");
            Toast.makeText(this, R.string.shopping_list_added, Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, R.string.shopping_list_enter, Toast.LENGTH_LONG).show();
        }
    }
    }

**ShoppingListActivity.java**

    public class ShoppingListActivity extends AppCompatActivity {

    Button buttonAddItem;
    EditText editTextItemName;
    TextView textViewShoppingList;
    ListView listViewItems;
    DatabaseReference databaseItems;
    List<Item> items;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_list);

        Intent intent = getIntent();
        databaseItems = FirebaseDatabase.getInstance().getReference("items").child(intent.getStringExtra(Constants.SHOPPINGLIST_ID));
        buttonAddItem = (Button) findViewById(R.id.buttonAddItem);
        editTextItemName = (EditText) findViewById(R.id.editTextShoppingListName);
        textViewShoppingList = (TextView) findViewById(R.id.textViewShoppingList);
        listViewItems = (ListView) findViewById(R.id.listViewItems);
        items = new ArrayList<>();
        textViewShoppingList.setText(intent.getStringExtra(Constants.SHOPPINGLIST_NAME));
        buttonAddItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                saveItem();
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();

        databaseItems.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                items.clear();
                for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                    Item item = postSnapshot.getValue(Item.class);
                    items.add(item);
                }
                ListOfItems listOfItemsAdapter = new ListOfItems(ShoppingListActivity.this, items);
                listViewItems.setAdapter(listOfItemsAdapter);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });
    }

    private void saveItem() {
        String trackName = editTextItemName.getText().toString().trim();
        if (!TextUtils.isEmpty(trackName)) {
            String id  = databaseItems.push().getKey();
            Item item = new Item(id, trackName);
            databaseItems.child(id).setValue(item);
            Toast.makeText(this, R.string.item_saved, Toast.LENGTH_LONG).show();
            editTextItemName.setText("");
        } else {
            Toast.makeText(this, R.string.item_enter, Toast.LENGTH_LONG).show();
        }
    }
    }

MainActivity:
public class MainActivity extends AppCompatActivity {

    EditText editTextShoppingListName;
    Button buttonAddShoppingList;
    ListView listViewShoppingLists;
    List<ShoppingList> shoppingLists;
    DatabaseReference databaseShoppingLists;
    com.example.nemanja.execomshoplist.AlertDialog alertDialog;
    Firebase firebase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        databaseShoppingLists = FirebaseDatabase.getInstance().getReference("shoppingLists");
        editTextShoppingListName = (EditText) findViewById(R.id.editTextShoppingListName);
        listViewShoppingLists = (ListView) findViewById(R.id.listViewShoppingLists);
        buttonAddShoppingList = (Button) findViewById(R.id.buttonAddShoppingList);
        shoppingLists = new ArrayList<>();

        buttonAddShoppingList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                firebase.addShoppingList();
            }
        });

        listViewShoppingLists.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ShoppingList shoppingList = shoppingLists.get(i);

                Intent intent = new Intent(getApplicationContext(), ShoppingListActivity.class);
                intent.putExtra(Constants.SHOPPINGLIST_ID, shoppingList.getShoppingListId());
                intent.putExtra(Constants.SHOPPINGLIST_NAME, shoppingList.getShoppingListName());
                startActivity(intent);
            }
        });

        listViewShoppingLists.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                ShoppingList shoppingList = shoppingLists.get(i);
                alertDialog.showUpdateDeleteDialog(shoppingList.getShoppingListId(), shoppingList.getShoppingListName());
                return true;
            }
        });
    }
}

AlertDialog:
public class AlertDialog extends android.support.v7.app.AlertDialog{


    protected AlertDialog(@NonNull Context context) {
        super(context);
    }
    private Firebase firebase;

    void showUpdateDeleteDialog(final String shoppingListId, String shoppingListName) {
        android.support.v7.app.AlertDialog.Builder dialogBuilder = new android.support.v7.app.AlertDialog.Builder(getContext());
        LayoutInflater inflater = getLayoutInflater();
        final View dialogView = inflater.inflate(R.layout.update_dialog, null);
        dialogBuilder.setView(dialogView);

        final EditText editTextShoppingListName = (EditText) dialogView.findViewById(R.id.editTextShoppingListName);
        final Button buttonUpdateShoppingList = (Button) dialogView.findViewById(R.id.buttonUpdateShoppingList);
        final Button buttonDeleteShoppingList = (Button) dialogView.findViewById(R.id.buttonDeleteShoppingList);

        dialogBuilder.setTitle(shoppingListName);
        final android.support.v7.app.AlertDialog alertDialog = dialogBuilder.create();
        alertDialog.show();

        buttonUpdateShoppingList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = editTextShoppingListName.getText().toString().trim();
                if (!TextUtils.isEmpty(name)) {
                    firebase.updateShoppingList(shoppingListId, name);
                    alertDialog.dismiss();
                }
            }
        });

        buttonDeleteShoppingList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                firebase.deleteShoppingList(shoppingListId);
                alertDialog.dismiss();
            }
        });
    }

}

Firebase:
public class Firebase {

    private EditText editTextShoppingListName;
    private ListView listViewShoppingLists;
    private List<ShoppingList> shoppingLists;
    private DatabaseReference databaseShoppingLists;
    Context context;

    public Firebase(EditText editTextShoppingListName, Button buttonAddShoppingList, ListView listViewShoppingLists, List<ShoppingList>
            shoppingLists, DatabaseReference databaseShoppingLists, Context context) {
        this.editTextShoppingListName = editTextShoppingListName;
        this.listViewShoppingLists = listViewShoppingLists;
        this.shoppingLists = shoppingLists;
        this.databaseShoppingLists = databaseShoppingLists;
        this.context = context;
    }

    public boolean updateShoppingList(String id, String name) {
        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("shoppingLists").child(id);
        ShoppingList shoppingList = new ShoppingList(id, name);
        databaseReference.setValue(shoppingList);
        // Toast.makeText(getContext(), R.string.shopping_list_updated, Toast.LENGTH_LONG).show();
        return true;
    }

    public boolean deleteShoppingList(String id) {
        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("shoppingLists").child(id);
        databaseReference.removeValue();
        DatabaseReference databaseReferenceItems = FirebaseDatabase.getInstance().getReference("items").child(id);
        databaseReferenceItems.removeValue();
        // Toast.makeText(getContext(), R.string.shopping_list_deleted, Toast.LENGTH_LONG).show();
        return true;
    }

    public void AddValueEventListener() {

    databaseShoppingLists.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            shoppingLists.clear();
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                ShoppingList shoppingList = postSnapshot.getValue(ShoppingList.class);
                shoppingLists.add(shoppingList);
            }
            ListOfShoppingLists shoppingListAdapter = new ListOfShoppingLists(context, shoppingLists);
            listViewShoppingLists.setAdapter(shoppingListAdapter);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}
    public void addShoppingList() {
        String name = editTextShoppingListName.getText().toString().trim();
        if (!TextUtils.isEmpty(name)) {
            String id = databaseShoppingLists.push().getKey();
            ShoppingList shoppingList = new ShoppingList(id, name);
            databaseShoppingLists.child(id).setValue(shoppingList);
            editTextShoppingListName.setText("");
            // Toast.makeText(this, R.string.shopping_list_added, Toast.LENGTH_LONG).show();
        } else {
            // Toast.makeText(this, R.string.shopping_list_enter, Toast.LENGTH_LONG).show();
        }
    }
}

Android Monitor:
E/AndroidRuntime: FATAL EXCEPTION: main 
java.lang.NullPointerException: Attempt to invoke virtual method
on a null object reference   MainActivity$1.onClick(MainActivity.java:44)                                                                                        at android.view.View.performClick(View.java:5697)                                                                                        at android.widget.TextView.performClick(TextView.java:10826)                                                                                        at android.view.View$PerformClick.run(View.java:22526)                                                                                        at android.os.Handler.handleCallback(Handler.java:739)                                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)                                                                                        at android.os.Looper.loop(Looper.java:158)                                                                                        at android.app.ActivityThread.main(ActivityThread.java:7224)                                                                                        at java.lang.reflect.Method.invoke(Native Method)                                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230                                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

1 个答案:

答案 0 :(得分:0)

这里试试这个

public class Dialog extends DialogFragment {


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View mView = inflater.inflate(R.layout.activity_add_rooms,container,false);
    getDialog().setTitle("Smart Room");
    getDialog().requestWindowFeature(Window.FEATURE_LEFT_ICON);


    return mView;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    getDialog().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,R.drawable.logo);
 }


}

在你的firebase类中

首先将活动上下文作为

Activity activity;

在firebase的构造函数中我们这个

this.activity=context;

然后使用下面的代码调用片段

Dialog dialog = new Dialog ();
        dialog.setStyle(DialogFragment.STYLE_NORMAL, R.style.CustomDialog);
        dialog .show(activity.getFragmentManager(), "example");

如果你必须从活动中调用它

Dialog dialog = new Dialog ();                       
dialog.setStyle(DialogFragment.STYLE_NORMAL,R.style.CustomDialog);
dialog .show(getFragmentManager(), "example");