Мое приложение получает имя, адрес и тип (сидячий, забираемый, заказ по телефону) ресторана и добавляет его в sqlite, а затем в просмотр списка.
Я пытаюсь выбрать опцию удалениякогда один из элементов в списке просмотра долго нажимается, но я не знаю, как я могу это сделать, и я хотел иметь опцию редактирования после создания элемента строки, поэтому я создал контекстное меню для длительного нажатия и опцию удаления и редактированияи если пользователь выбирает опцию редактирования, появляется диалоговое окно, и появляется текст для редактирования и радиогруппа, чтобы пользователь мог изменить выбранный элемент
Я новичок в Android.
MainActivity:
package com.test.fastfoodfinder;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ListView listview;
private Button btn;
Cursor model = null;
RestaurantAdapter adapter = null;
EditText ffname = null;
EditText ffaddress = null;
RadioGroup types = null;
RestaurantHelper helper = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.btn);
helper = new RestaurantHelper(this);
ffname = findViewById(R.id.edittext_name);
ffaddress = findViewById(R.id.edittext_name);
types = findViewById(R.id.radiogroup_type);
listview = findViewById(R.id.list_view);
model = helper.getAll();
startManagingCursor(model);
adapter = new RestaurantAdapter(model);
listview.setAdapter(adapter);
btn.setOnClickListener(onSave);
registerForContextMenu(listview);
}
public void onDestroy() {
super.onDestroy();
helper.close();
}
boolean doubleBackToExitPressedOnce = false;
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, (ContextMenu.ContextMenuInfo) menuInfo);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
menu.add(0, 1, 0, "Edit");
menu.add(0, 2, 1, "Remove");
menu.add(0, 3, 2, "Add Note");
menu.add(0, 4, 3, "All Notes");
}
public boolean onContextItemSelected(MenuItem item) {
if (item.getTitle().equals("Edit")) {
TextView title = new TextView(this);
title.setText("Edit Your Inputs");
title.setBackgroundColor(Color.DKGRAY);
title.setPadding(10, 16, 10, 10);
title.setGravity(Gravity.CENTER);
title.setTextColor(Color.WHITE);
title.setTextSize(20);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View loginForm = inflater.inflate(R.layout.set_dialog, null, false);
builder.setView(loginForm);
builder.setCustomTitle(title);
AlertDialog dialog = builder.create();
dialog.getWindow().getAttributes().windowAnimations = R.style.customdialog;
dialog.show();
} else if (item.getTitle().equals("Remove")) {
} else if (item.getTitle().equals("Add Note")) {
} else if (item.getTitle().equals("All Notes")) {
}
return super.onContextItemSelected(item);
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
ListView listView = findViewById(R.id.list_view);
EditText nameInput = findViewById(R.id.edittext_name);
EditText addressInput = findViewById(R.id.editText_address);
RadioGroup types = findViewById(R.id.radiogroup_type);
int id = item.getItemId();
switch (id) {
case R.id.clearlist:
helper.deleteDatabase(this);
listView.setAdapter(null);
break;
case R.id.clearforum:
nameInput.setText("");
addressInput.setText("");
types.check(0);
break;
case R.id.settings:
break;
case R.id.exit:
finish();
System.exit(0);
break;
}
return super.onOptionsItemSelected(item);
}
private View.OnClickListener onSave = new View.OnClickListener() {
@Override
public void onClick(View v) {
String type = null;
switch (types.getCheckedRadioButtonId()) {
case R.id.sitdown:
type = ("sitdown");
break;
case R.id.take_away:
type = ("take_away");
break;
case R.id.phone_order:
type = ("phone_order");
break;
}
if (ffname.getText().toString().isEmpty()) {
Toast.makeText(MainActivity.this, "Please enter a name to continue", Toast.LENGTH_SHORT).show();
Animation right = AnimationUtils.loadAnimation(MainActivity.this, R.anim.alert);
ffname.startAnimation(right);
btn.startAnimation(right);
} else if (ffaddress.getText().toString().isEmpty()) {
Toast.makeText(MainActivity.this, "Please enter an address to continue", Toast.LENGTH_SHORT).show();
Animation shake = AnimationUtils.loadAnimation(MainActivity.this, R.anim.alert);
ffaddress.startAnimation(shake);
btn.startAnimation(shake);
} else if (type.equals("")) {
Toast.makeText(MainActivity.this, "Please select a type", Toast.LENGTH_SHORT).show();
Animation shake = AnimationUtils.loadAnimation(MainActivity.this, R.anim.alert);
types.startAnimation(shake);
} else {
helper.insert(ffname.getText().toString(), ffaddress.getText().toString(), type, null);
model.requery();
Toast.makeText(MainActivity.this, "Total number of FastFoods in the list:" + listview.getAdapter().getCount(), Toast.LENGTH_SHORT).show();
}
}
};
class RestaurantAdapter extends CursorAdapter {
RestaurantAdapter(Cursor cursor) {
super(MainActivity.this, cursor);
}
public void bindView(View row, Context context, Cursor cursor) {
RestaurantHolder holder = (RestaurantHolder) row.getTag();
holder.populateFrom(cursor, helper);
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.row_layout, parent, false);
Animation animation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.fadein);
row.startAnimation(animation);
RestaurantHolder holder = new RestaurantHolder(row);
row.setTag(holder);
return (row);
}
}
static class RestaurantHolder {
private TextView nameV = null;
private TextView addressV = null;
private ImageView icon = null;
RestaurantHolder(View row) {
nameV = row.findViewById(R.id.listview_name);
addressV = row.findViewById(R.id.listview_address);
icon = row.findViewById(R.id.type_ic);
}
void populateFrom(Cursor cursor, RestaurantHelper helper) {
nameV.setText(helper.getName(cursor));
addressV.setText(helper.getName(cursor));
if (helper.getType(cursor).equals("sitdown")) {
icon.setImageResource(R.drawable.sitdownn);
} else if (helper.getType(cursor).equals("take_away")) {
icon.setImageResource(R.drawable.takeaway);
} else if (helper.getType(cursor).equals("phone_order")) {
icon.setImageResource(R.drawable.phoneorderr);
}
}
}
}
sqlopenhelper
package com.test.fastfoodfinder;
import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
class RestaurantHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="lunchlist.db";
private static final int SCHEMA_VERSION=1;
public RestaurantHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS restaurants (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, address TEXT, type TEXT, notes TEXT);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// no-op, since will not be called until 2nd schema
// version exists
}
public Cursor getAll() {
return(getReadableDatabase()
.rawQuery("SELECT _id, name, address, type, notes FROM restaurants ORDER BY name",
null));
}
public void deleteDatabase(Context mContext) {
mContext.deleteDatabase(DATABASE_NAME);
}
public void insert(String name, String address,
String type, String notes) {
ContentValues cv=new ContentValues();
cv.put("name", name);
cv.put("address", address);
cv.put("type", type);
cv.put("notes", notes);
getWritableDatabase().insert("restaurants", "name", cv);
}
public String getName(Cursor c) {
return(c.getString(1));
}
public String getAddress(Cursor c) {
return(c.getString(2));
}
public String getType(Cursor c) {
return(c.getString(3));
}
public String getNotes(Cursor c) {
return(c.getString(4));
}
}
диалоговое окно
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"><![CDATA[>
]]>
<TextView
android:id="@+id/address"
style="@style/texts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="48dp"
android:text="Address"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/name" />
<TextView
android:id="@+id/type"
style="@style/texts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="52dp"
android:text="Type"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/address" />
<TextView
android:id="@+id/name"
style="@style/texts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Name"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"></TextView>
<EditText
android:id="@+id/edittext_name"
style="@style/texts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="60dp"
android:layout_marginLeft="60dp"
android:hint="Please enter fast food name"
app:layout_constraintStart_toEndOf="@+id/name"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/editText_address"
style="@style/texts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="46dp"
android:layout_marginLeft="46dp"
android:layout_marginTop="16dp"
android:hint="Please enter fast food address"
app:layout_constraintStart_toEndOf="@+id/address"
app:layout_constraintTop_toBottomOf="@+id/edittext_name" />
<RadioGroup
android:id="@+id/radiogroup_type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="@+id/type"
app:layout_constraintTop_toBottomOf="@+id/editText_address">
<RadioButton
android:id="@+id/sitdown"
style="@style/texts"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sit Down" />
<RadioButton
android:id="@+id/take_away"
style="@style/texts"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Take away" />
<RadioButton
android:id="@+id/phone_order"
style="@style/texts"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Phone Order" />
</RadioGroup>
<Button
android:id="@+id/btn"
style="@style/texts"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:paddingTop="16dp"
android:text="Add"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/radiogroup_type" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_begin="0dp" />
<androidx.constraintlayout.widget.Barrier
android:id="@+id/barrier"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:barrierDirection="left" />
</androidx.constraintlayout.widget.ConstraintLayout>
любая помощь будет оценена