Android在列表视图中设置sqlite数据库值

时间:2016-07-18 11:26:16

标签: android sqlite listview

我遇到了在android中设置ListView的问题。一切正常,但它没有设置我想要它设置的方式。这里是发生的图像

Inserting data to listview and sqlite

Retrieving data from sqlite to listview

当我添加数据时,它显示正常并准确插入数据但当我返回然后再次启动活动时,它会检索数据并将其显示在listview的单行中。

1)我想在列表视图的不同项目上显示每个条目的数据。我不知道如何实现它。

2)当我启动活动时,它应该显示所有数据库条目,当我添加新项目时,它应该附加上一个列表。但实际发生的事情是,当已有3条记录显示时,我再添加一条记录,显示最后添加的单条记录。之前添加的记录消失了。我不知道为什么他们没有展示。

这是我的代码

public class noticall extends ListActivity {


    CustomDateTimePicker custom;
    TextView tv,tv1;
    EditText ed;
    String store;
    static String Names;
    public static final int PICK_CONTACT = 1;
    String [] adi ;
    String [] adi1 ;
    String [] adi2 ;
    String [] adi3 ;
    static int incre=0;
    ArrayList<String> myrows = new ArrayList<String>();
    ArrayList<String> time1 = new ArrayList<String>();
    ArrayList<String> name1 = new ArrayList<String>(); 
    ArrayList<String> number1 = new ArrayList<String>();
    private PendingIntent pendingIntent;
    ListView listview;
    String temp1 ,temp2 ;
    int x=0; 
    OnItemClickListener listener;
    String Date,Time,Name,Number;
    MyNotiAdapter adp;


    private SQLiteAdapter mySQLiteAdapter = new SQLiteAdapter(noticall.this);



        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.notify);
            listview = (ListView) findViewById(android.R.id.list);

           listview.setDividerHeight(2);



    custom = new CustomDateTimePicker(noticall.this,new CustomDateTimePicker.ICustomDateTimeListener() {

               @Override
               public void onCancel() { 
                   finish();
               }


               @Override
               public void onSet(Dialog dialog, Calendar calendarSelected,Date dateSelected, int year, String monthFullName,
                            String monthShortName, int monthNumber, int date,
                            String weekDayFullName, String weekDayShortName,
                            int hour24, int hour12, int min, int sec,
                            String AM_PM) {

                      Calendar calendar =  Calendar.getInstance();
                      calendar.set(year, monthNumber, date, hour24,  min, 0);

                      long when = calendar.getTimeInMillis();         // notification time

                      Intent myIntent = new Intent(noticall.this, MyReceiver.class);
                      pendingIntent = PendingIntent.getBroadcast(noticall.this, 0, myIntent,0);

                      AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
                      alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);


        Date = calendarSelected.get(Calendar.DAY_OF_MONTH) + "/" + (monthNumber+1) + "/" +year; 
        Time = hour12 + ":" + min + " " + AM_PM;


        setlisto(Date);


        //Toast.makeText(noticall.this, store, Toast.LENGTH_SHORT).show();

           }
    });      



            custom.set24HourFormat(false);
            custom.setDate(Calendar.getInstance());



                findViewById(R.id.button_date).setOnClickListener(
                    new OnClickListener() {
                        @Override
                        public void onClick(View v) {



                        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                        startActivityForResult(intent,PICK_CONTACT);
                        custom.showDialog();
                        incre++;
                        }
                    });



                read_db();

    }




     @Override
     protected void onActivityResult(int requestCode, int resultCode, Intent data)
     {
       super.onActivityResult(requestCode, resultCode, data);

        if(resultCode != RESULT_CANCELED){

            if (requestCode == 1)
            {
                // Get the URI that points to the selected contact
                Uri contactUri = data.getData();

                // We only need the NUMBER column, because there will be only one row in the result
                String[] projection = {ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.CONTACT_ID};

                String[] segments = contactUri.toString().split("/");
                String id = segments[segments.length - 1];

                // Perform the query on the contact to get the NUMBER column
                // We don't need a selection or sort order (there's only one result for the given URI)
                // CAUTION: The query() method should be called from a separate thread to avoid blocking
                // your app's UI thread. (For simplicity of the sample, this code doesn't do that.)
                // Consider using CursorLoader to perform the query.
                Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null, null);
                cursor.moveToFirst();
                while (!cursor.isAfterLast())
                {
                    int cid = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
                    String contactid = cursor.getString(cid);

                    if (contactid.equals(id))
                    {
                        // Retrieve the phone number from the NUMBER column
                        int column = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                        String number = cursor.getString(column);

                        // Retrieve the contact name from the DISPLAY_NAME column
                        int column_name = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
                        String name = cursor.getString(column_name);

                        // Do something with the phone number...
                       // Toast.makeText(this, "I added the Contact: \n" + name + " " + number, Toast.LENGTH_SHORT).show();

                       // ed.setText(name+" - "+number);

                      Name=  Names=name;
                      Number =number;  



                    }

                 cursor.moveToNext();
                }
                cursor.close();


               }
            }
        }


     public void setlisto(String one ){



    // Log.e("setlistoo",one+"");
     myrows.add(one);
     time1.add(Time);
     name1.add(Name);
     number1.add(Number);

      adi=myrows.toArray(new String[myrows.size()]);
     adi1=time1.toArray(new String[time1.size()]);
     adi2=name1.toArray(new String[name1.size()]);
     adi3=number1.toArray(new String[number1.size()]);
     x++;
     listview.setAdapter(new MyNotiAdapter(noticall.this, adi,adi1,adi2,adi3));



     Log.i("a=",one+"");

     Log.i("b=",Time+"");

     Log.i("c=",Name+"");

     Log.i("d=",Number+"");



     mySQLiteAdapter = new SQLiteAdapter(noticall.this);
     mySQLiteAdapter.openToWrite();

     mySQLiteAdapter.insert(one,Time,Name,Number);


     mySQLiteAdapter.close();


  }
     public void del_db(){

         mySQLiteAdapter = new SQLiteAdapter(noticall.this);
         mySQLiteAdapter.openToWrite();

         mySQLiteAdapter.deleteAll();

     }



     public void read_db(){

         Log.e("jsahbdv", "munda agaya medaan men hay jamaalo");


            mySQLiteAdapter.openToRead();

            Cursor cursor = mySQLiteAdapter.getAllData();

            startManagingCursor(cursor);

            String[] from = new String[]{SQLiteAdapter.KEY_Name,SQLiteAdapter.KEY_Number,SQLiteAdapter.KEY_Date,SQLiteAdapter.KEY_Time};
            int[] to = new int[]{R.id.dato,R.id.tym,R.id.person,R.id.edu};

           SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(noticall.this, R.layout.row2, cursor, from, to);



           while (cursor.moveToNext()){



               cursor.getString(0);
               cursor.getString(1);
               cursor.getString(2);
               cursor.getString(3);
               cursor.getString(4);



            /*   strBfr.append("Id :"+ cursor.getString(0) + "\n");
               strBfr.append("Name:" + cursor.getString(1) + "\n");
               strBfr.append("Number:" +cursor.getString(2) + "\n");
               strBfr.append("Date:" + cursor.getString(3) + "\n");
               strBfr.append("Time:" + cursor.getString(4) + "\n");

             */  

               Log.i("Error", cursor.getString(0)+"");
               Log.i("Error", cursor.getString(1)+"");
               Log.i("Error", cursor.getString(2)+"");
               Log.i("Error", cursor.getString(3)+"");
               Log.i("Error 8", cursor.getString(4)+"");


               listview.setAdapter(cursorAdapter);

     }

     }


}

sqlite适配器类:

public class SQLiteAdapter {

    public static final String MYDATABASE_NAME = "notidb.db";
    public static final String MYDATABASE_TABLE = "MY_TABLE";
    public static final int MYDATABASE_VERSION = 1;
    public static final String KEY_ID = "_id";
    public static final String KEY_Name = "Name";
    public static final String KEY_Number = "Number";
    public static final String KEY_Date = "Date";
    public static final String KEY_Time = "Time";



    //create table MY_DATABASE (ID integer primary key, Content text not null);
    private static final String SCRIPT_CREATE_DATABASE =
        "create table " + MYDATABASE_TABLE + " ("
        + KEY_ID + " integer primary key autoincrement, "
        + KEY_Name + " text not null, " 
        + KEY_Number + " text not null, " 
        + KEY_Date + " text not null, " 
        + KEY_Time + " text not null);";


    private SQLiteHelper sqLiteHelper;
    private SQLiteDatabase sqLiteDatabase;

    private Context context;

    public SQLiteAdapter(Context c){
        context = c;
    }

    public SQLiteAdapter openToRead() throws android.database.SQLException {
        sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
        sqLiteDatabase = sqLiteHelper.getReadableDatabase();
        return this;    
    }

    public SQLiteAdapter openToWrite() throws android.database.SQLException {
        sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
        sqLiteDatabase = sqLiteHelper.getWritableDatabase();
        return this;    
    }

    public void close(){
        sqLiteHelper.close();
    }

    public long insert(String content,String content1,String content2,String content3){

        ContentValues contentValues = new ContentValues();
        contentValues.put(KEY_Name, content.toString());
        contentValues.put(KEY_Number, content1.toString());
        contentValues.put(KEY_Date, content2.toString());
        contentValues.put(KEY_Time, content3.toString());
        return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);


    }

    public int deleteAll(){
        return sqLiteDatabase.delete(MYDATABASE_TABLE, null, null);
    }

    public Cursor queueAll(){
        String[] columns = new String[]{KEY_ID, KEY_Name, KEY_Number, KEY_Date, KEY_Time};
        Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,null, null, null, null, null);

        return cursor;
    }


    public Cursor getAllData()
    {
        SQLiteDatabase db= sqLiteHelper.getWritableDatabase();
        Cursor res=db.rawQuery("select * from "+MYDATABASE_TABLE,null);

        return res;
    }

    public class SQLiteHelper extends SQLiteOpenHelper {

        public SQLiteHelper(Context context, String name,
                CursorFactory factory, int version) {
            super(context, name, factory, version);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            db.execSQL(SCRIPT_CREATE_DATABASE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub

             // Drop older table if existed
            db.execSQL("DROP TABLE IF EXISTS " + MYDATABASE_TABLE);

            // Create tables again
            onCreate(db);

        }

    }

}

与此相关= Android Store Listview data in SQlite database and retrieve data oncreate of activity in Listview

如何设置此问题或如何根据ID读取行然后设置为listview ..请帮助我们..

1 个答案:

答案 0 :(得分:2)

您在列表视图中使用多个适配器。

listview.setAdapter(new MyNotiAdapter(noticall.this, adi,adi1,adi2,adi3));

以后

listview.setAdapter(cursorAdapter);

虽然,是的,代码运行,你会看到一些意想不到的结果。

例如,第二个图像看起来像是在一行中显示一个Arraylist而不是每行显示一个元素。

这可能是由你在这里引用一些arraylists

引起的
mySQLiteAdapter.insert(myrows.toString(),time1.toString(),name1.toString(),number1.toString());

所以,我的建议是使用一个适配器(可能只是一个CursorAdapter,因为你使用SQLite)来显示你的数据。而setAdapter只能在onCreateCursor cursor = mySQLiteAdapter.getAllData(); startManagingCursor(cursor); // ... SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(noticall.this, R.layout.row2, cursor, from, to); while (cursor.moveToNext()){ // <--- This is bad 进行一次,而不需要再次设置它。您只需重新加载光标。

另一件需要注意的事情。将光标添加到适配器后,请勿迭代光标。因为适配器读取光标并显示其内容,所以您稍后会耗尽迭代器。

- (void)routingService:(SKRoutingService *)routingService didFinishRouteCalculationWithInfo:(SKRouteInformation *)routeInformation {
    dispatch_async(dispatch_get_main_queue(), ^{
       __block BOOL routeExists = NO;
       [_calculatedRoutes enumerateObjectsUsingBlock:^(SKRouteInformation *obj, NSUInteger idx, BOOL *stop) {
            if (routeInformation.routeID == obj.routeID) {
                routeExists = YES;
                *stop = YES;
            }
        }];

       if (!routeInformation.corridorIsDownloaded || routeExists || _calculatedRoutes.count == _configuration.numberOfRoutes) {
           return;
       }

       //are we still calculating the routes?
       if ([self hasState:SKTNavigationStateCalculatingRoute]) {
           [_calculatedRoutes addObject:routeInformation];

           //stop progress for the calculated route
           SKTRouteProgressView *progressVIew = _mainView.calculatingRouteView.progressViews[_calculatedRoutes.count - 1]; // HERE!!!
           [progressVIew startProgress];

           //show the info for the calculated route
           [_mainView.calculatingRouteView showInfoViewAtIndex:_calculatedRoutes.count - 1];
           [self updateCalculatedRouteInformationAtIndex:_calculatedRoutes.count - 1];

           //start progress for next route if needed
           if (_calculatedRoutes.count < _mainView.calculatingRouteView.numberOfRoutes) {
               SKTRouteProgressView *progressVIew = _mainView.calculatingRouteView.progressViews[_calculatedRoutes.count];
               [progressVIew startProgress];
           }

           if (!_selectedRoute) {
               _selectedRoute = routeInformation;
               [SKRoutingService sharedInstance].mainRouteId = _selectedRoute.routeID;
               [self zoomOnSelectedRoute];
               _mainView.calculatingRouteView.selectedInfoIndex = 0;
               _mainView.calculatingRouteView.startButton.hidden = NO;
           }
       } else if ([self hasState:SKTNavigationStateRerouting]) { //nope, we're being rerouted
           _selectedRoute = routeInformation;
           _navigationInfo.currentDTA = _selectedRoute.distance;
           [self updateDTA];
           _navigationInfo.currentETA = _selectedRoute.estimatedTime;
           [self updateETA];
           [SKRoutingService sharedInstance].mainRouteId = _selectedRoute.routeID;
           [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(removeReroutingState) object:nil];
           [self performSelector:@selector(removeReroutingState) withObject:nil afterDelay:kMinReroutingDisplayTime];
       }
    });
}