Good evening, gentlemen, professionals! I describe my situation: I need to change the text on the screen by pressing the side menu. Fragment one, respectively. The text is in the database. In fact, I need to know which element of the side menu under which id, and then just get an element from the database on this id. But the problem is that I do not understand exactly how to do it. Normal examples can not be found. Although I am sure that it will not take so long. Can you tell me how to do or what to read, because the head is already boiling, and thoughts are confused. Thank you all in advance for your help! Here is my code:

MainActivity.java

public class MainActivity extends ActionBarActivity { private DrawerLayout mDrawerLayout; private ListView myDrawerList; private ActionBarDrawerToggle myDrawerToggle; // navigation drawer title private CharSequence myDrawerTitle; // used to store app title private CharSequence myTitle; private String [] viewsNames; @Override public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Инициализируем наш класс-обёртку DatabaseHelper dbh = new DatabaseHelper(this); // База нам нужна для записи и чтения SQLiteDatabase sqdb = dbh.getWritableDatabase(); // закрываем соединения с базой данных sqdb.close(); dbh.close(); myTitle = getTitle(); myDrawerTitle = getResources().getString(R.string.menu); viewsNames = getResources().getStringArray(R.array.views_array); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); myDrawerList = (ListView) findViewById(R.id.left_drawer); myDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, viewsNames)); android.support.v7.app.ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); myDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open_menu, R.string.close_menu ) { public void onDrawerClosed(View view) { getSupportActionBar().setTitle(myTitle); // название в ActionBar при закрытом меню invalidateOptionsMenu(); } public void onDrawerOpened(View drawerView) { getSupportActionBar().setTitle(myDrawerTitle); // название в ActionBar при открытом меню invalidateOptionsMenu(); } }; mDrawerLayout.setDrawerListener(myDrawerToggle); if (savedInstanceState == null) { // on first time display view for first nav item displayView(0); } myDrawerList.setOnItemClickListener(new DrawerItemClickListener()); } private class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick( AdapterView<?> parent, View view, int position, long id ) { // display view for selected nav drawer item displayView(position); } } // Метод displayView(int position) получает в параметрах id нужного view, // а далее блок switch определяет, каким именно фрагментом нужно заполнить FrameLayout. private void displayView(int position) { // update the main content by replacing fragments Fragment fragment = null; switch (position) { case 0: fragment = new FirstFragment(); break; case 1: fragment = new FirstFragment(); break; case 2: fragment = new FirstFragment(); break; default: break; } if (fragment != null) { android.app.FragmentManager fragmentManager = getFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.content_frame, fragment).commit(); // update selected item and title, then close the drawer myDrawerList.setItemChecked(position, true); myDrawerList.setSelection(position); setTitle(viewsNames[position]); mDrawerLayout.closeDrawer(myDrawerList); } else { // error in creating fragment Log.e("MainActivity", "Error in creating fragment"); } } 

DatabaseHelper.java

 public class DatabaseHelper extends SQLiteOpenHelper { private final Context fContext; // имя базы данных private static final String DATABASE_NAME = "colorcat_database.db"; public static final String TABLE_NAME = "cattable"; DatabaseHelper(Context context) { // версия базы данных последняя цифра super(context, DATABASE_NAME, null, 1); fContext = context; } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL("CREATE TABLE " + TABLE_NAME + " (" + "_id INTEGER PRIMARY KEY, " + "title TEXT"+ ");"); // Добавляем записи в таблицу ContentValues values = new ContentValues(); // Получим файл из ресурсов Resources res = fContext.getResources(); // Открываем xml-файл XmlResourceParser _xml = res.getXml(R.xml.cats_records); try { // Ищем конец документа int eventType = _xml.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { // Ищем теги record if ((eventType == XmlPullParser.START_TAG) && (_xml.getName().equals("record"))) { // Тег Record найден, теперь получим его атрибуты и // вставляем в таблицу String title = _xml.getAttributeValue(0); values.put("title", title); db.insert(TABLE_NAME, null, values); } eventType = _xml.next(); } 

MyAdapter.java

 public class MyAdapter extends BaseAdapter { ArrayList<SimpleObject> objects; Context context; public MyAdapter (Context context, ArrayList<SimpleObject> objects){ this.context = context; this.objects = objects; } // кол-во элементов @Override public int getCount() { return objects.size(); } // элемент по позиции @Override public Object getItem(int i) { return objects.get(i); } // id по позиции @Override public long getItemId(int i) { return i; } // пункт списка @Override public View getView(int i, View view, ViewGroup viewGroup) { // используем созданные, но не используемые view if(view == null){ view = LayoutInflater.from(context).inflate(R.layout.drawer_list_item, viewGroup, false); } SimpleObject object = objects.get(i); // заполняем View ((TextView) view.findViewById(R.id.txtLabel)).setText(object.getName()); return view; } } 

SimpleObject.java

 public class SimpleObject { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } 
  • You brought a lot of extra code, not related to the problem. Leave only the necessary - for many, such an abundance of code completely cuts off the desire to delve into the essence of the problem. In particular, the markup is completely useless here, just like the data model, the adapter, the empty fragment and the class for working with the database, and most of the activation code, incl. methods for the menu. - YurySPb
  • In general, you also have a list of data with id - from there and take the ID to query the database .... - YuriySPb

1 answer 1

Your problem is not very clear. Perhaps, you just need to pass the number of the position element pressed into the fragment just before clicking on the menu item before displaying it as an argument using Bundle and setArguments(Bubdle args) . Further, already in the fragment, in onCreateView, get the position from the arguments ( getArguments().getInt("key") ) and, using this number, make a query in the database. So when you click on the menu item, you will see a fragment with info from the database for ID 0, 1, 2, 3 etc from the database.

  • But the position number is not the same as the ID in the database. Positions are always in ascending order from 0, the ID is numbered and will only increase when deleting inserts into the database. Thus, if you delete the first element, then ID = 0 will not exist, but the position will be. - pavlofff 10:21 pm
  • @pavlofff, I may not have correctly expressed my thought. As I understand it, the vehicle wants items in the menu for as many as the records in the table. And it is necessary, of course, not to equate ID with position , but the sequence number of the record in the table, sorted by key). Or, in general, by clicking from the data object, this ID is taken ... It’s just that the vehicle, as for me, didn’t clearly describe the task and the problem and it’s difficult to answer something more specific. - Yuriy SPb