Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
swdev:android:database_sqlite [2018/04/30 09:01]
smayr [Database Helper]
swdev:android:database_sqlite [2018/05/02 20:30] (current)
smayr [Database Utils]
Line 1: Line 1:
 = Database: SQLite = = Database: SQLite =
 ==== DB Connector ==== ==== DB Connector ====
-Download the appropriate Java database connector: +When using the built-in ''android.database.sqlite'' library, there is not need to add an additional database connector
-  * [[https://github.com/xerial/sqlite-jdbc|Download JDBC Connector library]]. +
-  * Extract JAR file to some folder. +
-  * Add JAR file as module: ''app'', right-click then ''New'' > ''Module'', then select 'Import .JAR/.AAR Package', and find JAR file. +
-  * JAR package should be now listed under the project Gradle Scripts: ''build.gradle (sqlite-jdbc-3.20.0)''+
-  * If there is an error including the JAR package, try the following: +
-    * In ''settings.gradle (Project Settings)'', add references to the sqlite-jdbc: <code bash> +
-include ':app' +
-include ':sqlite-jdbc-3.20.0' +
-</code> +
-  * Sync project (File > Sync Project with Gradle Files). +
-  * Add ''sqlite-jdbc'' module as dependency to ''app'' module: +
-    * Right-click on the ''app'' module folder, and select "Open Module Settings" (F4). +
-    * In the top left navigation pane of the "Project Structure" window, go to category "Modules" and select tab "Dependencies"+
-    * Click on the green plus (+), and select 'Module Dependencies'. Select the ''sqlite-jdbc'' module. +
-    * Click OK, and close all the opened windows. A synchronization process should take place once more. +
-  * If there is an error including the JAR package, try the following: +
-    * In ''build.gradle (Module:app)'', add references to compile ''sqlite-jdbc'' under dependencies: <code bash> +
-dependencies { +
-  //... +
-  compile project(':sqlite-jdbc-3.20.0'+
-+
-</code> +
-  * If succesfull, under the ''app'' module folder there should be a ''sqlite-jdbc'' module folder. +
-  * Include the classes required in your code.+
  
  
Line 246: Line 222:
         //String selection = DbContract.TeamEntry.COL_NAME + " = ?";         //String selection = DbContract.TeamEntry.COL_NAME + " = ?";
         //String[] selectionArgs = { "My Team" };         //String[] selectionArgs = { "My Team" };
 +        String selection = null;         // no filters
 +        String[] selectionArgs = null;   // no filters
  
         // How you want the results sorted in the resulting Cursor         // How you want the results sorted in the resulting Cursor
Line 254: Line 232:
                 DbContract.TeamEntry.TABLE_NAME,   // The table to query                 DbContract.TeamEntry.TABLE_NAME,   // The table to query
                 projection,             // The array of columns to return (pass null to get all)                 projection,             // The array of columns to return (pass null to get all)
-                //selection,              // The columns for the WHERE clause +                selection,              // The columns for the WHERE clause 
-                null, +                selectionArgs,          // The values for the WHERE clause
-                //selectionArgs,          // The values for the WHERE clause +
-                null,+
                 null,                   // don't group the rows                 null,                   // don't group the rows
                 null,                   // don't filter by row groups                 null,                   // don't filter by row groups
Line 294: Line 270:
         //String selection = DbContract.TeamEntry.COL_NAME + " = ?";         //String selection = DbContract.TeamEntry.COL_NAME + " = ?";
         //String[] selectionArgs = { "My Team" };         //String[] selectionArgs = { "My Team" };
 +        String selection = null;         // no filters
 +        String[] selectionArgs = null;   // no filters
  
         // How you want the results sorted in the resulting Cursor         // How you want the results sorted in the resulting Cursor
Line 303: Line 281:
                 projection,             // The array of columns to return (pass null to get all)                 projection,             // The array of columns to return (pass null to get all)
                 //selection,              // The columns for the WHERE clause                 //selection,              // The columns for the WHERE clause
-                null, 
                 //selectionArgs,          // The values for the WHERE clause                 //selectionArgs,          // The values for the WHERE clause
-                null, 
                 null,                   // don't group the rows                 null,                   // don't group the rows
                 null,                   // don't filter by row groups                 null,                   // don't filter by row groups
Line 360: Line 336:
  
  
 +}
 +</code>
 +
 +=== MainActivity ===
 +<code java>
 +public class MainActivity extends AppCompatActivity {
 +
 +    // Const
 +    private static final String TAG = "ROBOTICS_LEAGUE_APP";
 +
 +    // Properties
 +    ListView lstTeams;
 +    String[] arrTeams;
 +    List<String> teamNames;
 +
 +    @Override
 +    protected void onCreate(Bundle savedInstanceState)
 +    {
 +        super.onCreate(savedInstanceState);
 +        setContentView(R.layout.activity_main);
 +
 +        // Connect to resources
 +        Resources res = getResources();
 +        lstTeams = (ListView) findViewById(R.id.lstTeams);
 +        //arrTeams = res.getStringArray(R.array.teams);  // get data from resource stings
 +
 +        try {
 +            DbUtils dbutil = new DbUtils();
 +            dbutil.getConnection(this);
 +            teamNames = dbutil.findTeamNamesAll();  // get data from database
 +        } catch (Exception ex) {
 +            ex.printStackTrace();
 +        }
 +        // Using custom ItemAdapter with custom layout
 +        TeamItemAdapter itemAdapter = new TeamItemAdapter(
 +                this,    // context
 +                //arrTeams     // data
 +                teamNames     // data
 +        );
 +        lstTeams.setAdapter(itemAdapter);
 +
 +        lstTeams.setOnItemClickListener(new AdapterView.OnItemClickListener() {
 +            @Override
 +            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
 +                Log.d(TAG, "Loading rubric for Team " + (position+1));
 +                Toast.makeText(getApplicationContext(), "Loading rubric for Team " + (position+1), Toast.LENGTH_SHORT).show();
 +
 +                Intent showRubricActivity = new Intent(getApplicationContext(), RobotRubricActivity.class);
 +                showRubricActivity.putExtra("com.acme.roboticsleague.TEAM_ID", (position+1)+"");
 +                showRubricActivity.putExtra("com.acme.roboticsleague.TEAM_INDEX", position);
 +                startActivity(showRubricActivity);
 +            }
 +        });
 +    }
 +}
 +</code>
 +
 +activiy_main.xml Layout:
 +<code xml>
 +<?xml version="1.0" encoding="utf-8"?>
 +<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
 +    xmlns:app="http://schemas.android.com/apk/res-auto"
 +    xmlns:tools="http://schemas.android.com/tools"
 +    android:layout_width="match_parent"
 +    android:layout_height="match_parent"
 +    tools:context=".MainActivity">
 +
 +    <ListView
 +        android:id="@+id/lstTeams"
 +        android:layout_width="match_parent"
 +        android:layout_height="495dp"
 +        android:layout_marginEnd="8dp"
 +        android:layout_marginStart="8dp"
 +        android:layout_marginTop="8dp"
 +        app:layout_constraintEnd_toEndOf="parent"
 +        app:layout_constraintStart_toStartOf="parent"
 +        app:layout_constraintTop_toTopOf="parent" />
 +</android.support.constraint.ConstraintLayout>
 +</code>
 +
 +=== ItemAdapter ===
 +<code java>
 +package com.acme.myapp;
 +
 +import android.content.Context;
 +import android.view.LayoutInflater;
 +import android.view.View;
 +import android.view.ViewGroup;
 +import android.widget.BaseAdapter;
 +import android.widget.TextView;
 +
 +import java.util.List;
 +
 +public class TeamItemAdapter extends BaseAdapter {
 +    LayoutInflater mInflater;
 +
 +    //String[] arrTeams;
 +    List<String> arrTeams;
 +
 +    //public TeamItemAdapter(Context cx, String[] teams)
 +    public TeamItemAdapter(Context cx, List<String> teams)
 +    {
 +        arrTeams = teams;
 +
 +        mInflater = (LayoutInflater) cx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 +    }
 +
 +    @Override
 +    //public int getCount()
 +    //{
 +    //    return arrTeams.length;
 +    //}
 +    public int getCount()
 +    {
 +        return arrTeams.size();
 +    }
 +
 +    @Override
 +    //public Object getItem(int idx)
 +    //{
 +    //    return arrTeams[idx];
 +    //}
 +    public Object getItem(int idx)
 +    {
 +        return arrTeams.get(idx);
 +    }
 +
 +    @Override
 +    public long getItemId(int idx)
 +    {
 +        return idx;
 +    }
 +
 +    @Override
 +    public View getView(int idx, View view, ViewGroup viewGroup)
 +    {
 +        // Use layout inflater.  Use listview_detail_team.xml layout
 +
 +        View vw = mInflater.inflate(R.layout.listview_detail_team, null);
 +        TextView lblItemNumber = (TextView) vw.findViewById(R.id.lblItemNumber);
 +        TextView lblTeamName = (TextView) vw.findViewById(R.id.lblTeamName);
 +
 +        String strItemNumber = (idx+1) + "";
 +        //String strTeam = arrTeams[idx];
 +        String strTeam = arrTeams.get(idx);
 +
 +        lblItemNumber.setText(strItemNumber);
 +        lblTeamName.setText(strTeam);
 +
 +        return vw;
 +    }
 } }
 </code> </code>
Line 368: Line 495:
   * [[https://developer.android.com/training/data-storage/sqlite|Data Storage: SQLite]]   * [[https://developer.android.com/training/data-storage/sqlite|Data Storage: SQLite]]
   * [[https://developer.android.com/training/data-storage/room|Data Storage: Room]]   * [[https://developer.android.com/training/data-storage/room|Data Storage: Room]]
 +  * [[https://dzone.com/articles/create-a-database-android-application-in-android-s|Create a database Android application]]