0

Good morning,

I am in the process of developing an android app and I stumbled on something that i can't solve (searches didn't help neither trying and adapting code from here and there found on the net) and it may have been answered here before I just need help in my specific case.

My app is simple, a splash screen at start(that runs for 5 seconds) than goes to main activity(which is a FragmentActivity). In the main activity I have 5 different ListFragments (right now I have loaded in the list some random text to see how it would look). Every fragment will have it's own database which will populate the ListFragment (I have 1 database complete to try it out before going on and making the other databases).

For the 1 database I have complete I tried playing around with adapter, handler and provider but nothing worked (the ListFragment with the database was displaying the loading circle).

Then I found the tutorial "Use own database in app" but that didn't helped either (better say I wasn't able to modify the code to work on my project).

All I need is this :

  • during the splashscreen, the database needs to be loaded (in the future more databases) for the first time and stored on the device (the splashscreen should show up every time the app starts but only load the databases the first time) - NOTE not sure if this is possible thou, in any case since the splashscreen shows up every time the databases can be loaded each time and I think 5 seconds are enough for 5 DB of 200bytes each so no problem here.
  • the main activity displays the first ListFragment with the data from the database
  • swiping to the next ListFragment should display data from the second database and so on...

Here is my code until now:

Splashscreen

public class Splash extends Activity {

    private boolean bIsBackButtonPressed;
    private static final int SPLASH_DURATION = 5000;
    private static final int FM_NOTIFICATION_ID = 0;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.notification_icon)
            .setContentTitle("Testing app in execution")
            .setContentText("Click here to go back in the app");

        Intent notificationIntent = new Intent(this, Main.class);
        notification.setOngoing(true);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        notification.setContentIntent(contentIntent);

        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(FM_NOTIFICATION_ID, notification.build());


        setContentView(R.layout.splash);

        ImageView splashImage = (ImageView) findViewById(R.id.splash_screen_);

        int orient = getWindowManager().getDefaultDisplay().getRotation();
        if (orient == 0) {
            splashImage.setBackgroundResource(R.drawable.splash_screen_port);
        } else {
            splashImage.setBackgroundResource(R.drawable.splash_screen_land);

        }

        Handler handler = new Handler();

        handler.postDelayed(new Runnable() {

            @Override
            public void run() {

                finish();

                if (!bIsBackButtonPressed) {
                    Intent intent = new Intent(Splash.this, Main.class);
                    Splash.this.startActivity(intent);
                }
            }
        }, SPLASH_DURATION); 
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        ImageView splashImage = (ImageView) findViewById(R.id.splash_screen_);
        int orient = getWindowManager().getDefaultDisplay().getRotation();
        if (orient == 0) {
            splashImage.setBackgroundResource(R.drawable.splash_screen_port);
        } else {
            splashImage.setBackgroundResource(R.drawable.splash_screen_land);
        }

    }

    @Override
    public void onBackPressed() {
        bIsBackButtonPressed = true;
        finish();
        super.onBackPressed();
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.cancel(FM_NOTIFICATION_ID);
    }

}

Here is my MainActivity

public class Main extends FragmentActivity { 

    SectionsPagerAdapter mSectionsPagerAdapter;
    ViewPager mViewPager;

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

        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {

            Fragment fragment = new Fragment();
            switch (position) {
            case 0:
                return fragment = new 1List();
            case 1:
                return fragment = new 2List();
            case 2:
                return fragment = new 3List();
            case 3:
                return fragment = new 4List();
            case 4:
                return fragment = new 5List();              
            default:
                break;
            }
            return fragment;
        }

        @Override
        public int getCount() {

            return 5;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
            case 0:
                return getString(R.string.1);
            case 1:
                return getString(R.string.2);
            case 2:
                return getString(R.string.3);
            case 3:
                return getString(R.string.4);
            case 4:
                return getString(R.string.5);               

            }

            return null;
        }
    }

    private static final int FM_NOTIFICATION_ID = 0;

    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(this)
        .setMessage("Do you want to close the app?") 
        .setCancelable(false)
        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                 Main.this.finish();
                NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                manager.cancel(FM_NOTIFICATION_ID);
            }
        })
        .setNegativeButton("No", null)
        .show();
    }

}

This is my first ListFragment (the other 4 have the same exact content - this should be populated with data from my database which is stored in the assets folder) :

public class 1List extends ListFragment {

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        String[] values = new String[] { 
                "Android", "iPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Mac OS X", "Linux", "OS/2"
        };
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, values);
        setListAdapter(adapter);
    }

}

As I mentioned I have an adapter which extends a CursorAdapter - 1ListDatabaseAdapter :

public class 1ListDatabaseAdapter extends CursorAdapter {

    private LayoutInflater inflater; 
    private int s;
    String TAG = "1ListDatabaseAdapter";

    public 1ListDatabaseAdapter(Context context, Cursor c){
        super(context, c);
        inflater = LayoutInflater.from(context);
        s = c.getCount();
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {

        TextView name = (TextView) view.findViewById(R.id.name);


        name.setText(cursor.getString(1));

        cursor.moveToNext();

    }

    @Override
    public View newView(Context arg0, Cursor arg1, ViewGroup arg2) {
        return inflater.inflate(R.layout.list_item, null);
    }
}

And I have a handler 1ListDatabaseHandler :

public class 1ListDatabaseHandler extends SQLiteOpenHelper {

    private static final String TAG = 1ListDatabaseHandler.class.getSimpleName();

    private static final String DATABASE_NAME = "1ldb.db";
    private static final int DATABASE_VERSION = 1;


    public static final String ID = "_id";
    public static final String TABLE_NAME = "1list";
    public static final String NAME = "name";
    public static final String TYPE = "type";
    public static final String ADDRESS = "adress";
    public static final String PHONE = "phone";
    public static final String MAIL = "email";
    public static final String SITE = "website";

    private static final String TABLE_CREATE = " CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " ( " + ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + NAME + " STRING, "  + TYPE + " STRING, " + ADDRESS + " STRING, "  + PHONE + " STRING, " + MAIL + " STRING, " + SITE + " STRING ); ";

    private static final String TABLE_DROP = "DROP TABLE IF EXISTS " + TABLE_NAME;

    AlojamentoDatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
//      Log.i(TAG, "DatabaseHandler was initiated. ");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(TABLE_CREATE);
        Log.i(TAG, "1ListDatabaseHandler: " + db);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading the database from version " + oldVersion + " to version " + newVersion);
        db.execSQL(TABLE_DROP);
        onCreate(db);
    }

    public void insert(String name, String type, String adress, String phone, String email, String website) {
        long rowId = -1;
        try {
            SQLiteDatabase db = getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put(NAME, name);
            values.put(TYPE, type);
            values.put(ADDRESS, adress);
            values.put(PHONE, phone);
            values.put(MAIL, email);
            values.put(SITE, website);
            rowId = db.insert(TABLE_NAME, null, values);
            Log.i(TAG, "insert: " + name + ", " + type + ", " + adress + ", " + phone + ", " + email + ", " + website);
        } catch (SQLiteException e) {
            Log.i(TAG, "insert()", e);
        } finally {
            Log.i(TAG, "insert(): rowId=" + rowId);
        }

    }

    public Cursor query() {
        SQLiteDatabase db = getWritableDatabase();
        return db.query(TABLE_NAME, null, null, null, null, null, ID + " ASC");
    }



}

All the imports are made correctly, the app runs great as it is without database (for a visual example of course) and now I need to connect a sqlite database to display the data in the 1ListFragment and up until now (before asking the question here) I did lot of research trying to figure out on my own (cause that's how I work - oh yeah!) but always came out scratching my head, so many code I tried to make up and adapt and nothing work and I really think it's simple I just can't put my finger on it. How do I connect my own premade database to my app and display the data in the 1ListFragment ?

Thanks in advance.

4

1 回答 1

0

您正在使用 ArrayAdapter,您必须使用您的 adpater:
将 1List 类的 de 代码替换为:

public class 1List extends ListFragment {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    1ListDatabaseHandler Db = new 1ListDatabaseHandler(getActivity());
    Cursor cursor = Db.query();
    if (cursor != null) {
        cursor.moveToFirst();
    }
    1ListDatabaseAdapter adapter = new 1ListDatabaseAdapter(getActivity(), cursor);
    setListAdapter(adapter);
}  

我看到的另一件事是你给了你的名字1ListDatabaseHandlerSQLiteOpenHelper class命名了它的构造函数AlojamentoDatabaseHandler
替换AlojamentoDatabaseHandler(Context context)为从in 中1ListDatabaseHandler(Context context)
删除cursor.moveToNext();bindView1ListDatabaseAdapter

于 2013-10-26T16:22:02.740 回答