数据库不检索数据

时间:2013-10-19 09:02:56

标签: android sqlite android-sqlite

我想在Android中创建一个应用程序,我想要显示公共汽车,火车,使用数据库可用的航班。我为此编写了代码,但是当我想从数据库中检索数据时,只调用为总线编写的方法。其他方法没有任何价值。 我的代码是:

Database_Activity.java

public class Database_Activity {

public int id;
private DbHelper ourHelper;
private Context ourContext;
private SQLiteDatabase ourDatabase;

private static class DbHelper extends SQLiteOpenHelper {

    // this is database name (change it as you want)
    public DbHelper(Context context) {
        super(context, "shrirang", null, 1);
    }

    @Override
    // create corrsponding tables
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE travel ( id INTEGER PRIMARY KEY AUTOINCREMENT, src TEXT NOT NULL,dest TEXT NOT NULL,bcost INTEGER NOT NULL,tcost INTEGER,acost INTEGER);");
        db.execSQL("CREATE TABLE bus ( bid INTEGER PRIMARY KEY AUTOINCREMENT, bsname TEXT NOT NULL, bsrc TEXT NOT NULL,bdest TEXT NOT NULL,bcost INTEGER NOT NULL,bt1 TEXT NOT NULL,bt2 TEXT NOT NULL);");
        db.execSQL("CREATE TABLE train ( tid INTEGER PRIMARY KEY AUTOINCREMENT, trname TEXT NOT NULL, tsrc TEXT NOT NULL,tdest TEXT NOT NULL,tcost INTEGER NOT NULL,tt1 TEXT NOT NULL,tt2 TEXT NOT NULL);");
        db.execSQL("CREATE TABLE flight ( fid INTEGER PRIMARY KEY AUTOINCREMENT, flname TEXT NOT NULL, fsrc TEXT NOT NULL,fdest TEXT NOT NULL,fcost INTEGER NOT NULL,ft1 TEXT NOT NULL,ft2 TEXT NOT NULL);");
        db.execSQL("CREATE TABLE history ( sid INTEGER PRIMARY KEY AUTOINCREMENT, src TEXT NOT NULL,dest TEXT NOT NULL,budget INTEGER NOT NULL, day INTEGER NOT NULL,mon INTEGER NOT NULL, year INTEGER NOT NULL);");
        db.execSQL("CREATE TABLE install (db INTEGER NOT NULL);");
    }

    @Override
    // if tables all ready exist then delete
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS travel");
        db.execSQL("DROP TABLE IF EXISTS bus");
        db.execSQL("DROP TABLE IF EXISTS train");
        db.execSQL("DROP TABLE IF EXISTS flight");
        db.execSQL("DROP TABLE IF EXISTS history");
        db.execSQL("DROP TABLE IF EXISTS install");
        onCreate(db);
    }
}

public Database_Activity(Context c) {
    ourContext = c;
}
// method for opening database
public Database_Activity open() throws SQLException {
    ourHelper = new DbHelper(ourContext);
    ourDatabase = ourHelper.getWritableDatabase();
    return this;
}

// method for creating entry
public long createentry(String src, String dest, int bcost,int tcost,int acost) {
    ContentValues cv = new ContentValues();
    cv.put("src", src);
    cv.put("dest", dest);
    cv.put("bcost", bcost);
    cv.put("tcost", tcost);
    cv.put("acost", acost);
    return ourDatabase.insert("travel", null, cv);

}
// method for adding bus details
public long Add_BUS_Entry(String bname, String bsrc, String bdest, int bcost,String bt1,String bt2) {
    ContentValues cv = new ContentValues();
    cv.put("bsname", bname);
    cv.put("bsrc", bsrc);
    cv.put("bdest", bdest);
    cv.put("bcost",bcost);
    cv.put("bt1", bt1);
    cv.put("bt2", bt2);
    return ourDatabase.insert("bus", null, cv);

}

// method for add train to database
public long Add_TRAIN_Entry(String trname, String src, String dest, int cost,String t1,String t2) {
    ContentValues cv = new ContentValues();
    cv.put("trname", trname);
    cv.put("tsrc", src);
    cv.put("tdest", dest);
    cv.put("tcost",cost);
    cv.put("tt1", t1);
    cv.put("tt2", t2);
    return ourDatabase.insert("train", null, cv);

}

// method for add flight to databse
public long Add_FLIGHT_Entry(String flname, String src, String dest, int cost,String t1,String t2) {
    ContentValues cv = new ContentValues();
    cv.put("flname", flname);
    cv.put("fsrc", src);
    cv.put("fdest", dest);
    cv.put("fcost",cost);
    cv.put("ft1", t1);
    cv.put("ft2", t2);
    return ourDatabase.insert("flight", null, cv);

}

// method for closing database
public void close() {
    ourHelper.close();
}

// method for showing database entries 
public String getData() {
    String[] columns = new String[] { "id", "src", "dest", "bcost" , "tcost", "acost"};
    Cursor c = ourDatabase.query("travel", columns, null, null, null, null,
            null);
    String result = "";

    int iRow = c.getColumnIndex("id");
    int iun = c.getColumnIndex("src");
    int ipw = c.getColumnIndex("dest");
    int ib = c.getColumnIndex("bcost");
    int it = c.getColumnIndex("tcost");
    int ia = c.getColumnIndex("acost");
    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
        result = result + c.getString(iRow) + " " + c.getString(iun) + " "
                + c.getString(ipw) + " " + c.getShort(ib) + " " + c.getShort(it)+ " " + c.getShort(ia)+ "\n";
    }

    return result;
}

// method for adding search entry
public long AddSearch_entry(String s, String d, int b, int day, int mon,
        int year) {
    ContentValues cv = new ContentValues();
    cv.put("src", s);
    cv.put("dest", d);
    cv.put("budget", b);
    cv.put("day", day);
    cv.put("mon", mon);
    cv.put("year", year);
    return ourDatabase.insert("history", null, cv); 
}

// method for getting search data
public String getSearchData() {
    String[] columns = new String[] { "sid", "src", "dest", "budget" , "day", "mon","year"};
    Cursor c = ourDatabase.query("history", columns, null, null, null, null,
            null);
    String result = "";

    int iRow = c.getColumnIndex("sid");
    int iun = c.getColumnIndex("src");
    int ipw = c.getColumnIndex("dest");
    int ib = c.getColumnIndex("budget");
    int it = c.getColumnIndex("day");
    int ia = c.getColumnIndex("mon");
    int ic = c.getColumnIndex("year");
    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
        result = result + c.getString(iRow) + " " + c.getString(iun) + " "
                + c.getString(ipw) + " " + c.getShort(ib) + " " + c.getShort(it)+ "/" + c.getShort(ia)+ "/" + c.getShort(ic)+ "\n";
    }

    return result;
}

// methods for reading corrosponding database entries 
public Cursor GetLatestSearch() {
    return ourDatabase.query("history", new String[] {"sid","src","dest","budget","day","mon","year"},null, null, null, null, null);
}   
public Cursor Get_BUS_details() {
    return ourDatabase.query("bus", new String[] {"bid","bsname","bsrc","bdest","bcost","bt1","bt2"},null, null, null, null, null);
}
public Cursor findBUS(int temp) {
    return ourDatabase.query("bus", new String[] {"bid","bsname","bsrc","bdest","bcost","bt1","bt2"},"bid="+temp, null, null, null, null);
}



public Cursor Get_TRAIN_Details() {
    return ourDatabase.query("train", new String[] {"tid","trname","tsrc","tdest","tcost","tt1","tt2"},null, null, null, null, null);
}
public Cursor findTRAIN(int temp) { 
    return ourDatabase.query("train", new String[] {"tid","trname","tsrc","tdest","tcost","tt1","tt2"},"tid="+temp, null, null, null, null);
}

public Cursor findAIR(int temp) {
    return ourDatabase.query("flight", new String[] {"fid","flname","fsrc","fdest","fcost","ft1","ft2"},"fid="+temp, null, null, null, null);
}
public Cursor Get_flight_details() {
    return ourDatabase.query("flight", new String[] {"fid","flname","fsrc","fdest","fcost","ft1","ft2"},null, null, null, null, null);
}
public Cursor GetHistorySearch(long schid) {
    return ourDatabase.query("history", new String[] {"sid","src","dest","budget","day","mon","year"},"sid="+schid, null, null, null, null);
}

// method for deleting history
public void DeleteHistory() {
    ourDatabase.delete("history", null, null);      
}

public int getM() {
    String[] columns = new String[] { "id", "src", "dest", "bcost" , "tcost", "acost"};
    Cursor c = ourDatabase.query("travel", columns, null, null, null, null,
            null);
    int iRow = c.getColumnIndex("id");          

    return iRow;
}

public int Install() {
    int t;
    String[] columns = new String[]{"db"};
    Cursor c = ourDatabase.query("install", columns,null, null, null, null, null);
    if (c != null){
        c.moveToFirst();            
        t = c.getInt(0);            
        return t;
    }
    return 0;       
}

public long AddDB() {
    ContentValues cv = new ContentValues();
    cv.put("db", "1");      
    return ourDatabase.insert("install", null, cv);     
}

}

Train.java

public class Train extends ListActivity{

LayoutInflater mInflater;
static Object[] wer;
static Object searchid;
Dialog dialog = null;
String s1="",s2="",s3="",info="";
private long schid = 0;
String title = "",url="";
String f="",t="",b="",a="",d="",n="";
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    try{
            // set screen 'srchres.xml'
            setContentView(R.layout.bus);   

    List<String> strings;   // create string list to store search entry
    final List<String> listid;  // create string list for store list id's

    strings = new ArrayList<String>();  
    listid = new ArrayList<String>();
    super.onCreate(savedInstanceState);

    Database_Activity db_obj = new Database_Activity(this);

    // Define strings to store database entries
    @SuppressWarnings("unused")
    String temp0="",t="",temp1="", temp2="", temp3="" ,temp4="";
    @SuppressWarnings("unused")
    String bt0="",bt="",bt1="", bt2="", bt3="" ,bt4="";
    @SuppressWarnings("unused")
    String at0="",at="",at1="", at2="", at3="" ,at4="";                     


    db_obj.open();  // open database

    // ** check for who is starting activity either MainActivity.java (or) History.java **

    if(getIntent().getExtras() != null)// if this is true it is from History.java
    {
        // Get a History list index which we have selected
        Bundle bun2 = getIntent().getExtras();
        if (null == bun2) return;           
        this.schid  = bun2.getLong("uid");

        Cursor c2 = db_obj.GetHistorySearch(schid); // get search history from database

        if (c2.moveToFirst())
        {

                s1=c2.getString(1); // get source
                s2=c2.getString(2); // get destination
                s3=c2.getString(3); // get budget                                                                               

        }
    }
    else // if not then it is from MainActivity.java
    {
            Cursor c1 = db_obj.GetLatestSearch();   // Get search which is searched now 

            if (c1.moveToFirst())
            {

                    s1=c1.getString(1); // get source
                    s2=c1.getString(2); // get destination
                    s3=c1.getString(3); // get budget                                                                                                                                                       

            }
    }


    int co = Integer.parseInt(s3.toString());   

    Cursor c = db_obj.Get_TRAIN_Details();      


            if(c.moveToFirst()){                                
            // Retrive train information from database

            bt0 = c.getString(0);
            title = c.getString(1);
            bt = c.getString(2);
            bt1 = c.getString(3);
            bt2 = c.getString(4);
            int cost2 = Integer.parseInt(bt2.toString());
            bt3 = c.getString(5);
            bt4 = c.getString(6);

            // Compare given source, destination and budget with database entries
            if(s1.equalsIgnoreCase(bt) && s2.equalsIgnoreCase(bt1) && co>=cost2)
            {                   
                // ** if searched entry available in database show data
                info = bt+" to "+bt1+" in "+bt2+" at "+bt3;
                listid.add("B"+bt0);
                strings.add(info);                                    
            }                               

            mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);                          

            }





    db_obj.close(); // close database

    // Add search result to list
    setListAdapter(new ArrayAdapter<String>(this, R.layout.wtlist_item1, strings) 
            {

                @Override                   
                public View getView(int position, View convertView, ViewGroup parent) 
                {
                    View row;

                    if (null == convertView) 
                    {
                        row = mInflater.inflate(R.layout.wtlist_item1, null);
                    } else 
                    {
                        row = convertView;
                    }

                        TextView tv = (TextView) row.findViewById(android.R.id.text1);
                        tv.setText(getItem(position));                                                                  

                    return row;
                }

         });    

    ListView lv = getListView();

    //** Add action for click on search result **
    lv.setOnItemClickListener(new OnItemClickListener() 
    {
        @SuppressWarnings("deprecation")
        public void onItemClick(AdapterView<?> parent, View view,int position, long id) 
        {                           
            wer = listid.toArray();

            searchid =  wer[(int)id];   // add id to list

            // Show small dialog box
            showDialog(7);                                           

        }


    });


    }catch(Exception e)
    {
        Toast.makeText(getApplicationContext(), "Error"+e, Toast.LENGTH_LONG).show();
    }
}

0 个答案:

没有答案