проблема выбора из списка пользовательских списков просмотра из базы данных sqlite - PullRequest
0 голосов
/ 21 марта 2020

У меня проблемы с выбором из моего пользовательского списка и получением itemName из базы данных sqlite. я помещаю некоторый другой код ниже, не уверенный, если они необходимы.

The Log.d (TAG, "Имя -" + itemName); возвращает «Имя mypackagename. ListItems@ece56a4», которое не является именем

Log.d (TAG, «ID is» + ItemID); Идентификатор mypackagename. ListItems@ece56a4, а не идентификатор

ThreeColumn_ListAdapter.class преобразует @ ece56a4 в 3 столбца. Есть ли способ выбрать эти столбцы из списка? ??

        public class ViewListContents extends AppCompatActivity
    {
        private static final String TAG = "ViewListContents";

    DBManager dbManager;
    ArrayList<ListItems> listItems;
    ListView listView;
    ListItems items;

    private int selectedID;
    private String selectedName;

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

        dbManager = new DBManager(this);
        Intent receiveIntent = getIntent();
        selectedID = receiveIntent.getIntExtra("id",-1);
        selectedName = receiveIntent.getStringExtra("title");

        Log.d(TAG, "TitleID = " + selectedID);

        listItems = new ArrayList<>();

        Cursor data = dbManager.getItem(selectedID);

        int numRows = data.getCount();
        if (numRows == 0)
        {
            Toast.makeText(this, "there is nothing in database", Toast.LENGTH_SHORT).show();
        }
        else
        {
            while (data.moveToNext())
            {
                items = new ListItems(data.getInt(2),data.getString(1), data.getInt(0));
                Log.d(TAG, "" + new ListItems(data.getInt(0),data.getString(1), data.getInt(2)));
                listItems.add(items);
            }
            ThreeColumn_ListAdapter adapter = new ThreeColumn_ListAdapter(this, R.layout.custom_list, listItems);
            listView = (ListView) findViewById(R.id.item_name_listview);
            listView.setAdapter(adapter);

            listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
            {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int position, long id)
                {
                    String itemName = adapterView.getItemAtPosition(position).toString();
                    Log.d(TAG, "The name is" + itemName);
                    Cursor data = dbManager.getItemID2(itemName);

                    int ItemID = -1;
                    while (data.moveToNext())
                    {
                        ItemID = data.getInt(2);
                        Log.d(TAG, "The ID is" + ItemID);
                    }
                    if (ItemID > -1)
                    {
                        Intent edit = new Intent(ViewListContents.this, ItemActivity.class);
                        edit.putExtra("itemid", ItemID);
                        edit.putExtra("item", itemName);
                        startActivity(edit);
                    }
                    else
                    {
                        Toast.makeText(ViewListContents.this, "No id associated with that name", Toast.LENGTH_SHORT).show();
                    }

                }
            });
        }
    }
}

ThreeColumn_ListAdapter.class

public class ThreeColumn_ListAdapter extends ArrayAdapter<ListItems>
{
    private static final String TAG = "ThreeColumn_Listadapter";

    private LayoutInflater mInflater;
    private ArrayList<ListItems> items;
    private int mViewResourceId;

    public ThreeColumn_ListAdapter(Context context, int textViewResourceId, ArrayList<ListItems> items)
    {
        super(context, textViewResourceId, items);
        this.items = items;
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mViewResourceId = textViewResourceId;

    }

    public View getView(int position, View convertView, ViewGroup parents)
    {
        convertView = mInflater.inflate(mViewResourceId,null);
        ListItems listItems = items.get(position);

        TextView titleID = (TextView) convertView.findViewById(R.id.text11);
        TextView itemID = (TextView) convertView.findViewById(R.id.text22);
        TextView itemName = (TextView) convertView.findViewById(R.id.text33);

        if (titleID != null)
        {
            titleID.setText((""+listItems.getid()));
            Log.d(TAG, "getting titleid " + listItems.getid());
        }
        if (itemID != null)
        {
            itemID.setText((""+listItems.getitemid()));
            Log.d(TAG, "getting itemid " + listItems.getitemid());
        }
        if (itemName != null)
        {
            itemName.setText((listItems.getcontext()));
            Log.d(TAG, "getting itemname " + listItems.getcontext());
        }
        return convertView;
    }

}

ListItem.class getters setters

public class ListItems
{
    private final int titleid;
    private int id;
    private String context;

    public int getid()
    {
        return id;
    }
    public int getitemid()
    {
        return titleid;
    }
    public String getcontext()
    {
        return context;
    }
    public ListItems(int id, String context, int titleid)
    {
        this.id = id;
        this.context = context;
        this.titleid = titleid;
    }
}

dbmanger.class

    public class DBManager extends SQLiteOpenHelper
{

    static final String TAG ="DBManager";
    static final String DB_NAME = "todolist.db";
    static final int DB_VERSION = 1;
    static final String TABLE_NAME = "title_table";
    static final String C_TITLE_ID = "TitleID";///
    static final String C_TITLE_NAME = "title_name";

    static final String TABLE_ITEM = "item_table";
    static final String C_ITEM_ID = "ItemID";///
    static final String C_ITEM_NAME = "item_name";

    static final String TitleID_ref = "TitleID_ref";


    public DBManager(Context context)
    {
        super(context, DB_NAME, null, DB_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase database)
    {
        database.execSQL("create table " + TABLE_NAME +
                " (TitleID INTEGER PRIMARY KEY AUTOINCREMENT, " +
                C_TITLE_NAME + " text) ");

        database.execSQL("PRAGMA foreign_keys=ON");

        database.execSQL("create table " + TABLE_ITEM +
                " (ItemID INTEGER PRIMARY KEY AUTOINCREMENT, " +
                C_ITEM_NAME + " text, " +
                 TitleID_ref + " INTEGER,"+
                " FOREIGN KEY (TitleID_ref) REFERENCES " + TABLE_NAME + "(TitleID )) ");

       Log.d(TAG, "create tables");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        db.execSQL("drop table if exists " + TABLE_NAME);
        Log.d(TAG, " updating table " + TABLE_NAME);

        onCreate(db);
    }

    public boolean addTitle(String title)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(C_TITLE_NAME,title);

        long result = db.insert(TABLE_NAME, null, cv);

        db.close();
        if (result == -1)
        {
            return false;
        }
        else
        {
            return true;
        }
    }

    public boolean addItem(String title, int item)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(C_ITEM_NAME,title);
        cv.put(TitleID_ref,item);

        //inserting row
        long result = db.insert(TABLE_ITEM, null, cv);

        db.close();
        if (result == -1)
        {
            return false;
        }
        else
        {
            return true;
        }
    }

    public Cursor getTitle()
    {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT * FROM " + TABLE_NAME;
        Cursor data = db.rawQuery(query, null);
        return data;
    }

    public Cursor getItem(int title)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT * FROM " + TABLE_ITEM + " WHERE " + TitleID_ref + " = '" + title + " '" ;
        Cursor data = db.rawQuery(query, null);
        return data;
    }

    public Cursor getItemID(int title)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT " + C_ITEM_ID + " FROM " + TABLE_ITEM +
                " WHERE " + C_TITLE_ID + " = '" + title + "'" ;
        Cursor data = db.rawQuery(query, null);
        return data;
    }

    public Cursor getItemID2(String itemid)//naming 
    {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT " + C_ITEM_ID + " FROM " + TABLE_ITEM +
                " WHERE " + C_ITEM_NAME + " = '" + itemid + "'" ;
        Cursor data = db.rawQuery(query, null);
        return data;
    }

    public Cursor getTitleID(String title)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT " + C_TITLE_ID + " FROM " + TABLE_NAME +
                " WHERE " + C_TITLE_NAME + " = '" + title + "'" ;
        Cursor data = db.rawQuery(query, null);
        return data;
    }
}

1 Ответ

0 голосов
/ 22 марта 2020

Когда вы делаете следующее, вы получаете объект ListItems и присваиваете ему String.

// This gives you the object associated with your list
String itemName = adapterView.getItemAtPosition(position).toString(); 

Если вы хотите получить идентификатор элемента списка, вам нужно сделать следующее:

String itemName = adapterView.getItemAtPosition(position).getid() + ""; 
...