Get off the OBD on the side menu list



  • Good evening, professional gentlemen! I'm talking about my situation. I need the side menu to change the text on the screen. Fragment One, respectively. The text is in the OBD system. In fact, I need to know what part of the side menu under what id is, and then just get an element with the OBD on this id. But the problem is, I don't understand how to do it. There are no good examples. Though I'm sure it won't last long. Maybe you can tell me how to do it or what to read, because the head's already dripping and the thoughts are confused. Thank you for your help. Here's 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)
                    &amp;&amp; (_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;
    

    }
    }



  • Your problem is not very clear. Maybe you should just, at the time of the application to the menu element, hand over the wiretap number. position in a fragment before its reflection as an argument, using Bundle and setArguments(Bubdle args)♪ Next, in the fragment, onCreateView get position from argumentsgetArguments().getInt("key")and use this number to request OBD. So you'll have a piece of info from the ID 0, 1, 2, 3 etc from the BDE when compressing the menu element.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2