Reputation: 3163
I'm building an app that manages the tasks. The user can enter the task name, set priority and add that task. What I want to implement is for the user to be able to click an item, launch an alert dialog and edit the details of that item (name, priority) from that dialog, click "Save Edits" and save the edits for that particular list item. However, the alert dialog does not launch when an item is clicked. I'm trying to call a method containing the dialog through onclick:
recyclerView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
addTaskActivity.onClickEditTask(view);
return true;
}
});
And this is the onClickEditText
method:
public class AddTaskActivity extends AppCompatActivity {
...
public void onClickEditTask(View view){
String editedInput = ((EditText)findViewById(R.id.edit_task)).getText().toString();
if(editedInput.length() == 0){
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(getLayoutInflater().inflate(R.layout.edit_dialog, null))
.create();
}
...
}
Currently, I want to know how to launch this method per item click and get the details of that item plastered onto the launched dialog. The following are my relevant classes:
AddTaskActivity.java:
public class AddTaskActivity extends AppCompatActivity {
private int mPriority;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_task);
((RadioButton) findViewById(R.id.radButton1)).setChecked(true);
mPriority = 1;
}
public void onClickAddTask(View view) {
String input = ((EditText) findViewById(R.id.editTextTaskDescription)).getText().toString();
if (input.length() == 0) {
return;
}
ContentValues contentValues = new ContentValues();
contentValues.put(TaskContract.TaskEntry.COLUMN_DESCRIPTION, input);
contentValues.put(TaskContract.TaskEntry.COLUMN_PRIORITY, mPriority);
Uri uri = getContentResolver().insert(TaskContract.TaskEntry.CONTENT_URI, contentValues);
if(uri != null) {
Toast.makeText(getBaseContext(), uri.toString(), Toast.LENGTH_LONG).show();
}
finish();
}
public void onClickEditTask(View view){
String editedInput = ((EditText)findViewById(R.id.edit_task)).getText().toString();
if(editedInput.length() == 0){
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(getLayoutInflater().inflate(R.layout.edit_dialog, null))
.create();
}
public void onPrioritySelected(View view) {
if (((RadioButton) findViewById(R.id.radButton1)).isChecked()) {
mPriority = 1;
} else if (((RadioButton) findViewById(R.id.radButton2)).isChecked()) {
mPriority = 2;
} else if (((RadioButton) findViewById(R.id.radButton3)).isChecked()) {
mPriority = 3;
}
}
}
MainActivity.java:
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int LOADER_ID = 0;
private CustomCursorAdapter customCursorAdapter;
RecyclerView recyclerView;
private AddTaskActivity addTaskActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerViewTasks);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
customCursorAdapter = new CustomCursorAdapter(this);
recyclerView.setAdapter(customCursorAdapter);
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
int id = (int) viewHolder.itemView.getTag();
String itemId = Integer.toString(id);
Uri uri = TaskContract.TaskEntry.CONTENT_URI;
uri = uri.buildUpon().appendPath(itemId).build();
getContentResolver().delete(uri, null, null);
getSupportLoaderManager().restartLoader(LOADER_ID, null, MainActivity.this);
}
}).attachToRecyclerView(recyclerView);
recyclerView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
addTaskActivity.onClickEditTask(view);
return true;
}
});
FloatingActionButton floatingActionButton = (FloatingActionButton) findViewById(R.id.fab_btn);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent addTaskIntent = new Intent(MainActivity.this, AddTaskActivity.class);
startActivity(addTaskIntent);
}
});
getSupportLoaderManager().initLoader(LOADER_ID, null, this);
}
@Override
protected void onResume() {
super.onResume();
getSupportLoaderManager().restartLoader(LOADER_ID, null, this);
}
@Override
public Loader<Cursor> onCreateLoader(int id, final Bundle loaderArgs) {
return new AsyncTaskLoader<Cursor>(this) {
Cursor cursor = null;
@Override
protected void onStartLoading() {
if (cursor != null) {
deliverResult(cursor);
} else {
forceLoad();
}
}
@Override
public Cursor loadInBackground() {
try {
return getContentResolver().query(TaskContract.TaskEntry.CONTENT_URI,
null,
null,
null,
TaskContract.TaskEntry.COLUMN_PRIORITY);
} catch (Exception e) {
Log.e(TAG, "Failed to load data.");
e.printStackTrace();
return null;
}
}
public void deliverResult(Cursor data) {
cursor = data;
super.deliverResult(data);
}
};
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
customCursorAdapter.swapCursor(data);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
customCursorAdapter.swapCursor(null);
}
}
CustomCursorAdapter.java:
public class CustomCursorAdapter extends RecyclerView.Adapter<CustomCursorAdapter.TaskViewHolder> {
private Cursor cursor;
private Context con;
public CustomCursorAdapter(Context context) {
this.con = context;
}
@Override
public TaskViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(con).inflate(R.layout.task_layout, parent, false);
return new TaskViewHolder(view);
}
@Override
public void onBindViewHolder(TaskViewHolder holder, int position) {
int index = cursor.getColumnIndex(TaskContract.TaskEntry._ID);
int descriptionOfIndex = cursor.getColumnIndex(TaskContract.TaskEntry.COLUMN_DESCRIPTION);
int priorityofIndex = cursor.getColumnIndex(TaskContract.TaskEntry.COLUMN_PRIORITY);
cursor.moveToPosition(position);
final int id = cursor.getInt(index);
String description = cursor.getString(descriptionOfIndex);
int priority = cursor.getInt(priorityofIndex);
holder.itemView.setTag(id);
holder.taskDescriptionView.setText(description);
String priorityString = "" + priority;
holder.priorityView.setText(priorityString);
GradientDrawable priorityCircle = (GradientDrawable) holder.priorityView.getBackground();
int priorityColor = getPriorityColor(priority);
priorityCircle.setColor(priorityColor);
}
private int getPriorityColor(int priority) {
int priorityColor = 0;
switch(priority) {
case 1: priorityColor = ContextCompat.getColor(con, R.color.materialRed);
break;
case 2: priorityColor = ContextCompat.getColor(con, R.color.materialOrange);
break;
case 3: priorityColor = ContextCompat.getColor(con, R.color.materialYellow);
break;
default: break;
}
return priorityColor;
}
@Override
public int getItemCount() {
if (cursor == null) {
return 0;
}
return cursor.getCount();
}
public Cursor swapCursor(Cursor c) {
if (cursor == c) {
return null;
}
Cursor temp = cursor;
this.cursor = c;
if (c != null) {
this.notifyDataSetChanged();
}
return temp;
}
class TaskViewHolder extends RecyclerView.ViewHolder {
TextView taskDescriptionView;
TextView priorityView;
public TaskViewHolder(View itemView) {
super(itemView);
taskDescriptionView = (TextView) itemView.findViewById(R.id.taskDescription);
priorityView = (TextView) itemView.findViewById(R.id.priorityTextView);
}
}
}
Upvotes: 1
Views: 1111
Reputation: 56938
You appear to have omitted showing the alter dialog by coding builder.show();
Additionally may want to setup some buttons (you can use Neutral, Positive and Negative buttons, below is example with just Neutral button).
You probably want to set the title and make the AlertDialog
cancelable.
You may also have an issue with the custom layout, so the code below will ignore that and use the default layout.
I believe that the following code will fix this issue:-
public void onClickEditTask(View view){
String editedInput = ((EditText)findViewById(R.id.edit_task)).getText().toString();
if(editedInput.length() == 0){
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Test");
builder.setCancelable(true);
builder.setNeutralButton("TEST", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d("TAG","You click the TEST button of the dialog.");
}
});
builder.show();
}
The following is the above but with an added rudimentary custom view, first the layout, namely test_hi.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">
<TextView
android:id="@+id/buildertv"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginTop="30dp"
android:layout_marginStart="30dp"
android:layout_marginLeft="30dp"
android:text="TEST"
android:textColor="#ff557799"
android:gravity="center"
>
</TextView>
</LinearLayout>
And the code (i.e. with builder.setView(R.layout.test_hi);
added) :-
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(R.layout.test_hi);
builder.setTitle("Test");
builder.setCancelable(true);
builder.setNeutralButton("TEST", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d("TAG","You clicked the TEST button of the dialog.");
}
});
builder.show();
Running the above should be something like (*running the previous code will not have the middle *Test**):-
Clicking the bottom (Red) Test will add a line to the log along the lines of:-
....D/TAG: You clicked the TEST button of the dialog.
You would replace Log.d("TAG","You clicked the TEST button of the dialog.");
with the code that you want to run when the Neutral Button is clicked. If you wanted other options then you can use the Positive and Negative buttons in a similar way by adding builder.setPositiveButton(....
and builder.setNegativeButton(....
accordingly.
Upvotes: 1