为什么getView没有被调用?

时间:2013-04-01 09:11:01

标签: android

我有一个扩展simplecursoradapter的适配器。由于某些原因我似乎无法看到,我的getView甚至没有被调用。我在getView中有一个断点,它永远不会到达那里,列表只显示为空。任何人都可以通过看看我做错了什么?

package com.example.ok1;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.app.ListActivity;

public class MainActivity extends Activity {
//  Button btnCalendar;

//*******************************************8
String[] names = {"Иван", "Марья", "Петр", "Антон", "Даша", "Борис",
          "Костя", "Игорь", "Анна", "Денис", "Андрей"};
//Button buttonAddTask;
final String Tag="States";
final String Ten = "Ten";
TextView txtDataTaskToday;
String id_for_listtsk_today;
ListView lvMain_today;
String[] arr_date;
SharedPreferences sPref;
static Cursor c;
private ListView listView = null;
//public static String id_for_listtsk_today;
//  static SQLiteDatabase db;
MySqlCursorAdapter adapter = null;
//***********************************************8

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
//  btnCalendar = (Button) findViewById(R.id.btnActTwo);
//  btnCalendar.setOnClickListener(this);

    //*********************************************
    // переменные для query
    String[] columns = null;
    String selection = null;
    String[] selectionArgs = null;
    String groupBy = null;
    String having = null;
    String orderBy = null;

  //*********работа с БД****************
    // создаем объект для данных

    //  txtDataTaskToday = (TextView) findViewById(R.id.txtDataTaskToday);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String id_for_listtsk_today = sdf.format(new Date());
        //final String b = id_for_listtsk_today;
    //  txtDataTaskToday.setText(id_for_listtsk_today.toString());
        Log.d(Tag, "id_for_listtsk_today ="+id_for_listtsk_today );
        ContentValues cv = new ContentValues();
        DBHelper dbHelper = new DBHelper(this);     
        final SQLiteDatabase db = dbHelper.getWritableDatabase();
        columns = new String[] {"name"};
        selection = "data_id = ?";
        selectionArgs = new String[] {id_for_listtsk_today};
        //c = db.query("mytable", columns, selection, selectionArgs, null, null, null);
        try {
        c=dbHelper.getCursor();
        } catch (SQLException sqle) {
            Log.d(Tag, "неудача");
            throw sqle;

        }
        String[] arr_date = logCursor(c);

    //*********работа с БД****************  

            lvMain_today = (ListView) findViewById(R.id.list);
//            lvMain_today.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        //this.listView=getl
        //listView = MainActivity.this.getlgetListView();
        lvMain_today.setItemsCanFocus(false);
        lvMain_today.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        //ArrayAdapter<String> adapter =  new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice, arr_date);// R.layout.item, my_list_item
        startManagingCursor(c);
        int[] listFields = new int[] { R.id.txtTitle };
        String[] dbColumns = new String[] { DBHelper.COLUMN_NAME };
        Log.d(Tag, "трассировка" );
        MainActivity.this.adapter = new MySqlCursorAdapter(
                this, R.layout.my_list_item,
                c, dbColumns, listFields,
                dbHelper);
 //           
        lvMain_today.setAdapter(MainActivity.this.adapter);
    //    setListAdapter(MainActivity.this.adapter);
        names = arr_date;
        c.close();
        db.close();
        dbHelper.close();



        lvMain_today.setOnItemClickListener(new OnItemClickListener() {
              public void onItemClick(AdapterView<?> parent, View view,
                  int position, long id) {
                  SparseBooleanArray chosen = ((ListView) parent).getCheckedItemPositions();
                  for (int i = 0; i < chosen.size(); i++) {
                      int key = chosen.keyAt(i);
                      if (chosen.get(key))
                        Log.d(Tag, "выделены ====="+names[key]);
                  Log.d(Tag, "itemClick: position = " + position + ", id = "
                    + id);}


                //****************nen пробная фигня**************

//                  String[] columns = null;
//                  String selection = null;
//                  String[] selectionArgs = null;
//                  String groupBy = null;
//                  String having = null;
//                  String orderBy = null;
//                  columns = new String[] {"name"};
//                  selection = "data_id = ?";
//                  selectionArgs = new String[] {id_for_listtsk_today};//id_for_listtsk_today 
//                  Cursor c = db.query("mytable", columns, selection, selectionArgs, null, null, null);
             //   String[] arr = logCursor(c);
                 //**************************************************  
                  //  String s=test();   
              }

            });

//          lvMain_today.setOnItemSelectedListener(new OnItemSelectedListener() {
//                public void onItemSelected(AdapterView<?> parent, View view,
//                    int position, long id) {
//                  Log.d(Tag, "Было выделение позиции меню!!!!position = " + position + ", id = "
//                      + id);
//                }
//
//                public void onNothingSelected(AdapterView<?> parent) {
//                  Log.d(Tag, "itemSelect: nothing");
//                }
//              }); 
}

private String[] logCursor(Cursor c) {
    // TODO Auto-generated method stub
    final String Tag="States";
    String[] arr_date = new String[c.getCount()];//String[] arr_date  = new String[] {};
    Log.d(Tag,"мы в курсоре");
    if (c!=null) {
        if (c.moveToFirst()) {
        //  Log.d(Tag,"мы в курсоре1");
            String str;
            int i=-1;
            do {
            //  Log.d(Tag,"мы в курсоре2");
                str="";
                i=i+1;
                for (String cn: c.getColumnNames()) {
                str =     str.concat(c.getString(c.getColumnIndex(cn)));
                }
                Log.d(Tag, "++++"+str);
                arr_date[i]=String.valueOf(str);
            } while (c.moveToNext());

        } 
    }

    return arr_date;

}




@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    menu.add(0, 1, 0, "календарь");
    menu.add(0, 2, 0, "Убрать выполненные");
      menu.add(0, 3, 3, "Уйти");
//        menu.add(1, 4, 1, "copy");
//        menu.add(1, 5, 2, "paste");
//        menu.add(1, 6, 4, "exit");

      return super.onCreateOptionsMenu(menu);
//  getMenuInflater().inflate(R.menu.main, menu);
    //return true;
}

public boolean onOptionsItemSelected(MenuItem item) {
      // TODO Auto-generated method stub
      StringBuilder sb = new StringBuilder();

      // Выведем в TextView информацию о нажатом пункте меню 
     // txtDataTaskToday.setText("Item Menu");
    //  txtDataTaskToday.setText(item.getGroupId());
////          txtDataTaskToday.setText("\r\n itemId: " + String.valueOf(item.getItemId()));
     // txtDataTaskToday.setText("\r\n order: " + String.valueOf(item.getOrder()));
     // txtDataTaskToday.setText("\r\n title: " + item.getTitle());
      switch (item.getItemId()) {
    case 1:
        Intent intent = new Intent(this, ToDoCalendarActivity.class);
        startActivity(intent);
        break;
    case 2:

        SparseBooleanArray sbArray = lvMain_today.getCheckedItemPositions();
        for (int i = 0; i < sbArray.size(); i++) {
          int key = sbArray.keyAt(i);
          if (sbArray.get(key))
            Log.d(Tag, "выделены "+names[key]);
          sPref = getPreferences(MODE_PRIVATE);
          Editor ed = sPref.edit();
          ed.putString(Ten, "1");
          ed.commit();
          Log.d(Tag, "ставим константу для скрытия");
        }


        break;
    case 3:
        sPref = getPreferences(MODE_PRIVATE);
        String savedText = sPref.getString(Ten, "");
        Log.d(Tag, "ten= "+ savedText);
        finish();
        break;

    }

      return super.onOptionsItemSelected(item);
    }



//  @Override
//  public void onClick(View v) {
//      // TODO Auto-generated method stub
//      switch (v.getId()) {
//      case R.id.btnActTwo:
//          
//          Intent intent = new Intent(this, ToDoCalendarActivity.class);
//          startActivity(intent);
//          break;
//      }
//  }

}

MySqlCursorAdapter

package com.example.ok1;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class MySqlCursorAdapter extends SimpleCursorAdapter implements OnClickListener {
final String Tag="States";
private Context context;

private DBHelper dbHelper;
private Cursor currentCursor;

public MySqlCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to, DBHelper dbHelper) {

super(context, layout, c, from, to);
Log.d(Tag, "трассировка1" );
this.currentCursor = c;
this.context = context;
this.dbHelper = dbHelper;
Log.d(Tag, "MySqlCursorAdapter()");
Integer b = c.getCount();
Log.d(Tag, "b="+b);
}

public View getView(int pos, View inView, ViewGroup parent) {
Log.d(Tag, "getView() + posss=" + pos);
View v = inView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.my_list_item, null);
}

this.currentCursor.moveToPosition(pos);

CheckBox cBox = (CheckBox) v.findViewById(R.id.bcheck);

cBox.setTag(Integer.parseInt(this.currentCursor
    .getString(this.currentCursor
            .getColumnIndex(DBHelper.COLUMN_ID))));
Log.d(Tag, "tag="+cBox.getTag().toString());
if (this.currentCursor.getString(this.currentCursor
    .getColumnIndex(DBHelper.COLUMN_STATUS)) != null
    && Integer.parseInt(this.currentCursor
            .getString(this.currentCursor
                    .getColumnIndex(DBHelper.COLUMN_STATUS))) != 0) {
cBox.setChecked(true);
} else {
cBox.setChecked(false);
}
cBox.setOnClickListener(this);

TextView txtTitle = (TextView) v.findViewById(R.id.txtTitle);
txtTitle.setText(this.currentCursor.getString(this.currentCursor
    .getColumnIndex(DBHelper.COLUMN_NAME)));

return (v);
}

public void ClearSelections() {
Log.d(Tag, "ClearSelections()");
//this.dbHelper.clearSelections();
//this.currentCursor.requery();

}

@Override
public void onClick(View v) {
Log.d(Tag, "onClick");
CheckBox cBox = (CheckBox) v;
Integer _id = (Integer) cBox.getTag();
Log.d(Tag, "Integer _id="+_id.toString());
ContentValues values = new ContentValues();
values.put(" selected", cBox.isChecked() ? 1 : 0);
//this.dbHelper.dbSqlite.update(SqlHelper.TABLE_NAME, values, "_id=?",
//      new String[] { Integer.toString(_id) });
}

}

DBHelper

package com.example.ok1;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.util.Log;


public class DBHelper extends SQLiteOpenHelper {
final String Tag="States";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_DATA = "data_id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_STATUS = "status";
public static final String TABLE_NAME = "mytable";
public SQLiteDatabase dbSqlite;
public DBHelper(Context context) {
  // конструктор суперкласса
    super(context, "myDB", null, 1);
}



@Override
public void onCreate(SQLiteDatabase db) {
  Log.d(Tag, "--- onCreate database ---");
  // создаем таблицу с полями
  db.execSQL("create table mytable ("
      + "_id integer primary key autoincrement," 
      + "data_id text,"
      + "name text,"
      + "task text,"
      + "status integer"
       + ");");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}
public Cursor getCursor() {
    Log.d(Tag, "getCursor() получили курсор с базы");
        String[] columns = null;
        String selection = null;
        String[] selectionArgs = null;
        String groupBy = null;
        String having = null;
        String orderBy = null;
//  SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

//  queryBuilder.setTables(TABLE_NAME);

//  String[] asColumnsToReturn = new String[] { COLUMN_ID, COLUMN_NAME,
//          COLUMN_DATA, COLUMN_STATUS };

//  Cursor mCursor = queryBuilder.query(dbSqlite, asColumnsToReturn, null,
//          null, null, null, "title ASC");
//  Log.d(Tag, "getCursor() получили курсор с базы конец");
            final SQLiteDatabase db = this.getWritableDatabase();
            columns = new String[] { COLUMN_ID, COLUMN_DATA, COLUMN_NAME, COLUMN_STATUS };
//              selection = "data_id = ?";
//              selectionArgs = new String[] {id_for_listtsk_today};
            Cursor c = db.query("mytable", columns, null, null, null, null,     null);
    return c;
}
  }

ActivityMain.xml

<!--?xml version="1.0" encoding="utf-8"?-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#81BEF7" android:scrollbars="vertical">

<TableLayout android:id="@+id/TableLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent" >
    <TableRow>

        <ListView
            android:id="@+id/list"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >
</ListView>
    </TableRow>

</TableLayout>

</LinearLayout>

my_list_item.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal" >

<CheckBox 
    android:id="@+id/bcheck" 
    android:layout_height="wrap_content" 
    android:layout_width="wrap_content" 
    android:focusable="false"> 
</CheckBox>  

<TextView
    android:id="@+id/txtTitle"
    android:layout_width="138dp"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:focusable="false"
    android:gravity="left|center_vertical"
    android:text="Test" >

</TextView>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="right|center_vertical"
    android:orientation="horizontal" >

    <ImageButton
        android:id="@+id/ImageButton01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.50"
        android:clickable="true" >
    </ImageButton>
</LinearLayout>

</LinearLayout>

1 个答案:

答案 0 :(得分:1)

我删除了

c.close();
db.close();

现在工作正常。