Search code examples
android-tabs

android tab content does not show up


I'm currently learning to build app for Android, and I use Android Studio to do so.

I searched for similar posts but did not find what could help me.

My goal is to have an Activity with a tabHost and 4 Tabs (for the moment). I will put the code after giving some details. To begin, I'm just focused on two tabs on which I would like to: - put a button to start (on the first Tab) a dedicated activity to create an item (contact item), - Display the Contact list on the second Tab.

My problem : The button is correctly visible and works fine (I can create a Contact). i also have a function checking wheter a contact already exists or not (correctly working). What's not working is when I select the second Tab, my list won't show up and I can't see my contacts.

This my General Activity :

package avappmobile.fourwe;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;


public class General extends Activity {

    List<Contact> Contacts = new ArrayList<Contact>();
    List<Stuff> Stuffs = new ArrayList<Stuff>();
    List<Money> Moneys = new ArrayList<Money>();
    ListView contactListView;
    DatabaseContactHandler dbContactHandler;
    DatabaseMoneyHandler dbMoneyHandler;
    DatabaseStuffHandler dbStuffHandler;

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

        TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
        contactListView = (ListView) findViewById(R.id.listViewContact);

        dbContactHandler = new DatabaseContactHandler(getApplicationContext());
        dbMoneyHandler = new DatabaseMoneyHandler(getApplicationContext());
        dbStuffHandler = new DatabaseStuffHandler(getApplicationContext());

        tabHost.setup();

        TabHost.TabSpec tabSpec = tabHost.newTabSpec("home");
        tabSpec.setContent(R.id.tabHome);
        tabSpec.setIndicator("Home");
        tabHost.addTab(tabSpec);

        tabHost.newTabSpec("contact");
        tabSpec.setContent(R.id.tabContact);
        tabSpec.setIndicator("Contact");
        tabHost.addTab(tabSpec);

        tabHost.newTabSpec("money");
        tabSpec.setContent(R.id.tabMoney);
        tabSpec.setIndicator("Money");
        tabHost.addTab(tabSpec);

        tabHost.newTabSpec("stuff");
        tabSpec.setContent(R.id.tabStuff);
        tabSpec.setIndicator("Stuff");
        tabHost.addTab(tabSpec);

        if (dbContactHandler.getContactsCount() != 0)
            Contacts.addAll(dbContactHandler.getAllContacts());

        populateList();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.general, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void goToContactCreation(View view) {
        Intent intent = new Intent(this, ContactCreation.class);
        startActivity(intent);
    }

    //Contact

    private void populateList() {
        ArrayAdapter<Contact> adapter = new ContactListAdapter();
        contactListView.setAdapter(adapter);
    }

    private class ContactListAdapter extends ArrayAdapter<Contact> {
        public ContactListAdapter() {
            super (General.this, R.layout.contact_listview, Contacts);
        }

        @Override
        public View getView(int position, View view, ViewGroup parent) {
            if (view == null)
                view = getLayoutInflater().inflate(R.layout.contact_listview, parent, false);

            Contact currentContact = Contacts.get(position);

            TextView firstName = (TextView) view.findViewById(R.id.txtFirstName);
            firstName.setText(currentContact.getFirstName());
            TextView lastName = (TextView) view.findViewById(R.id.txtLastName);
            lastName.setText(currentContact.getLastName());

            return view;
        }
    }
}

My DbContactHandler :

package avappmobile.fourwe;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by a.vescera on 13/11/2014.
 */
public class DatabaseContactHandler extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;

    private static final String DATABASE_NAME = "fourWe",
            TABLE_CONTACTS = "contacts",
            KEY_ID = "id",
            KEY_FIRSTNAME = "firstName",
            KEY_LASTNAME = "lastName",
            KEY_PHONE = "phone",
            KEY_EMAIL = "email",
            KEY_MONEYLEND = "moneyLend",
            KEY_MONEYBORROWED = "moneyBorrowed",
            KEY_STUFFLEND = "stuffLend",
            KEY_STUFFBORROWED = "stuffBorrowed";

    public DatabaseContactHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + TABLE_CONTACTS + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_FIRSTNAME + " TEXT," +
                KEY_LASTNAME + " TEXT," + KEY_PHONE + " TEXT," + KEY_EMAIL + " TEXT," + KEY_MONEYLEND + " INTEGER," + KEY_MONEYBORROWED + " INTEGER," +
                KEY_STUFFLEND + " INTEGER," + KEY_STUFFBORROWED + " INTEGER)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

        onCreate(db);
    }

// Method to create a contact.
    public void createContact(Contact contact) {
        SQLiteDatabase db = getWritableDatabase();

        ContentValues values = new ContentValues();

        values.put(KEY_FIRSTNAME, contact.getFirstName());
        values.put(KEY_LASTNAME, contact.getLastName());
        values.put(KEY_PHONE, contact.getPhone());
        values.put(KEY_EMAIL, contact.getEmail());
        values.put(KEY_MONEYLEND, 0);
        values.put(KEY_MONEYBORROWED, 0);
        values.put(KEY_STUFFLEND, 0);
        values.put(KEY_STUFFBORROWED, 0);

        db.insert(TABLE_CONTACTS, null, values);
        db.close();
    }

// Method to get the details of a specific contact by an id.
    public Contact getContactId(int id) {
        SQLiteDatabase db = getReadableDatabase();

        Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID, KEY_FIRSTNAME, KEY_LASTNAME, KEY_PHONE, KEY_EMAIL, KEY_MONEYLEND,
                KEY_MONEYBORROWED, KEY_STUFFLEND, KEY_STUFFBORROWED }, KEY_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null );

        if (cursor != null)
            cursor.moveToFirst();

        Contact contact = new Contact(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4),
                Integer.parseInt(cursor.getString(5)),Integer.parseInt(cursor.getString(6)),Integer.parseInt(cursor.getString(7)),Integer.parseInt(cursor.getString(8)));
        db.close();
        cursor.close();
        return contact;
    }

// Method to get the details of a specific contact by firstName and lastName.
    public Boolean getContact(String firstName, String lastName) {
        SQLiteDatabase db = getReadableDatabase();
        Contact contact;

        Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID, KEY_FIRSTNAME, KEY_LASTNAME, KEY_PHONE, KEY_EMAIL, KEY_MONEYLEND,
                KEY_MONEYBORROWED, KEY_STUFFLEND, KEY_STUFFBORROWED }, KEY_FIRSTNAME + "=?" + " AND " + KEY_LASTNAME + "=?", new String[] { firstName, lastName }, null, null, null, null );

        if (cursor != null && cursor.moveToFirst()) {
            db.close();
            cursor.close();
            return true;
        } else {
            db.close();
            cursor.close();
            return false;
        }
    }

// Method to delete a specific contact.
    public void deleteContact(Contact contact) {
        SQLiteDatabase db = getWritableDatabase();
        db.delete(TABLE_CONTACTS, KEY_ID + "=?", new String[] { String.valueOf(contact.getId()) });
        db.close();
    }

// Method to get the total number of existing contacts into the DB.
    public int getContactsCount() {
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_CONTACTS, null);
        int count = cursor.getCount();
        db.close();
        cursor.close();

        return count;
    }

// Method to update the details of a specific contact.
    public int updateContact(Contact contact) {
        SQLiteDatabase db = getWritableDatabase();

        ContentValues values = new ContentValues();

        values.put(KEY_FIRSTNAME, contact.getFirstName());
        values.put(KEY_LASTNAME, contact.getLastName());
        values.put(KEY_PHONE, contact.getPhone());
        values.put(KEY_EMAIL, contact.getEmail());
        values.put(KEY_MONEYLEND, contact.getMoneyLend());
        values.put(KEY_MONEYBORROWED, contact.getMoneylBorrowed());
        values.put(KEY_STUFFLEND, contact.getStuffLend());
        values.put(KEY_STUFFBORROWED, contact.getStuffBorrowed());

        int rowsAffected = db.update(TABLE_CONTACTS, values, KEY_ID + "=?", new String[] { String.valueOf(contact.getId()) });
        db.close();

        return rowsAffected;
    }

// Method to get the list of the details of all the contacts present into the DB.
    public List<Contact> getAllContacts() {
        List<Contact> contacts = new ArrayList<Contact>();

        SQLiteDatabase db = getWritableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_CONTACTS, null);

        if (cursor.moveToFirst()) {
            do {
                contacts.add(new Contact(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4),
                        Integer.parseInt(cursor.getString(5)),Integer.parseInt(cursor.getString(6)),Integer.parseInt(cursor.getString(7)),Integer.parseInt(cursor.getString(8))));
            }
            while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return contacts;
    }
}

I don't put the detail of the Contact class, but if you think you need it, please feel free to ask me.

I put then the Design part of my main activity:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="avappmobile.fourwe.General">

    <TabHost
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/tabHost">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical">

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"></TabWidget>

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent">

                <LinearLayout
                    android:id="@+id/tabHome"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:orientation="vertical">

                    <Button
                        style="?android:attr/buttonStyleSmall"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/new_contact"
                        android:id="@+id/btnNewContact"
                        android:onClick="goToContactCreation"
                        android:enabled="true"
                        android:layout_gravity="right" />
                </LinearLayout>

                <LinearLayout
                    android:id="@+id/tabContact"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:orientation="vertical">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textAppearance="?android:attr/textAppearanceLarge"
                        android:text="@string/contacts_list"
                        android:id="@+id/txtMyContacts"
                        android:layout_gravity="center_horizontal"
                        android:layout_marginTop="10dp" />

                    <ListView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:id="@+id/listViewContact"
                        android:layout_marginTop="20dp" />
                </LinearLayout>

                <LinearLayout
                    android:id="@+id/tabMoney"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:orientation="vertical"></LinearLayout>

                <LinearLayout
                    android:id="@+id/tabStuff"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:orientation="vertical"></LinearLayout>

            </FrameLayout>

        </LinearLayout>
    </TabHost>
</LinearLayout>

And the layout created to display my contacts on the secont Tab.

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/first_name_contact"
        android:id="@+id/txtFirstName"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:id="@+id/txtLastName"
        android:layout_gravity="center_horizontal"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="@string/first_name_contact"
        android:singleLine="false" />

</RelativeLayout>

Thanks.


Solution

  • After further investigation on internet, I found that with the latest version of android, it might be more interesting to show a file with tab (and each tab having a different file, which is my goal) using the ViewPager.

    A quick and correctly defined tutorial is available here : http://architects.dzone.com/articles/android-tutorial-using.

    I then close my subject since I'm now focused on this way of doing my work.

    Regards.