0

我正在尝试将数据保存在 sqlite 数据库上。我的问题是我不知道为什么 ListView 的适配器没有显示。我有一个对话框来获取值,然后单击接受,我将值发送到数据库,然后我试图在 ListView 上显示结果。

我做错了什么?

对话

代码:

服务器SQLiteDB

public class ServersSQLiteDB extends SQLiteOpenHelper {

    // Sentencia SQL para crear la tabla de Usuarios
    String sqlCreate = "CREATE TABLE ServerDB (code INTEGER PRIMARY KEY AUTOINCREMENT, address TEXT, mntFolder TEXT, resorceName TEXT)";

    public ServersSQLiteDB(Context context, String dbname,
            CursorFactory factory, int version) {
        super(context, dbname, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // Se ejecuta la sentencia SQL de creación de la tabla
        db.execSQL(sqlCreate);
    }

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

        // Se elimina la versión anterior de la tabla
        db.execSQL("DROP TABLE IF EXISTS ServerDB");

        // Se crea la nueva versión de la tabla
        db.execSQL(sqlCreate);
    }

}

服务器

public class Server {

    private int code = -1;
    private String address = "";
    private String mntFolder = "";
    private String resourceName = "";

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getMntFolder() {
        return mntFolder;
    }

    public void setMntFolder(String mntFolder) {
        this.mntFolder = mntFolder;
    }

    public String getResourceName() {
        return resourceName;
    }

    public void setResourceName(String resourceName) {
        this.resourceName = resourceName;
    }

}

自定义基础适配器

public class CustomBaseAdapter extends BaseAdapter {
    private static ArrayList<Server> serverArrayList;

    private LayoutInflater mInflater;

    public CustomBaseAdapter(Context context, ArrayList<Server> results) {
        serverArrayList = results;
        mInflater = LayoutInflater.from(context);
    }

    public int getCount() {
        return serverArrayList.size();
    }

    public Object getItem(int position) {
        return serverArrayList.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.custom_row_view, null);
            holder = new ViewHolder();
            holder.txtAddress = (TextView) convertView.findViewById(R.id.address);
            holder.txtMntFolder = (TextView) convertView
                    .findViewById(R.id.mntFolder);
            holder.txtResourceName = (TextView) convertView.findViewById(R.id.resourceName);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.txtAddress.setText(serverArrayList.get(position).getAddress());
        holder.txtMntFolder.setText(serverArrayList.get(position)
                .getMntFolder());
        holder.txtResourceName.setText(serverArrayList.get(position).getResourceName());

        return convertView;
    }

    static class ViewHolder {
        TextView txtAddress;
        TextView txtMntFolder;
        TextView txtResourceName;
    }
}

最后,ServersActivity

public class ServersActivity extends Activity {

    final Context context = this;
    private Button btnAddServer;
    private Button btnDelServer;
    private EditText ed_address;
    private EditText ed_mntFolder;
    private EditText ed_resourceName;
    private ListView lvServers;
    private CustomBaseAdapter cAdapter;

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

        btnAddServer = (Button) findViewById(R.id.btnAdd);
        btnDelServer = (Button) findViewById(R.id.btnDelete);

        ArrayList<Server> serverResults = GetServerResults();

        lvServers = (ListView) findViewById(R.id.lvServers);
        cAdapter = new CustomBaseAdapter(this, serverResults);
        lvServers.setAdapter(cAdapter);

        lvServers.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> a, View v, int position,
                    long id) {
                Object o = lvServers.getItemAtPosition(position);
                Server fullObject = (Server) o;

                Crouton.makeText(
                        ServersActivity.this,
                        "You have chosen: " + " "
                                + fullObject.getResourceName(), Style.CONFIRM)
                        .show();
            }
        });

        btnAddServer.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // get custom_dialog_layout.xml view
                LayoutInflater li = LayoutInflater.from(context);
                View customDialogView = li.inflate(
                        R.layout.custom_dialog_layout, null);

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        ServersActivity.this);

                // set custom_dialog_layout.xml to alertdialog builder
                alertDialogBuilder.setView(customDialogView);

                ed_address = (EditText) customDialogView
                        .findViewById(R.id.etAddress);
                ed_mntFolder = (EditText) customDialogView
                        .findViewById(R.id.etMntFolder);
                ed_resourceName = (EditText) customDialogView
                        .findViewById(R.id.etResourceName);

                // set the title of the Alert Dialog
                alertDialogBuilder.setTitle(getResources().getString(
                        R.string.addDialogTitle));

                // set dialog message
                alertDialogBuilder
                        .setCancelable(false)
                        .setPositiveButton(
                                getResources().getString(R.string.accept),
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                            int id) {
                                        // Time to write data on SQLITE

                                        if (isEmpty(ed_address)
                                                && isEmpty(ed_mntFolder)
                                                && isEmpty(ed_resourceName)) {

                                            Crouton.makeText(
                                                    ServersActivity.this,
                                                    getString(R.string.emptyfields),
                                                    Style.INFO).show();

                                        } else {
                                            ServersSQLiteDB dbinstance = new ServersSQLiteDB(
                                                    ServersActivity.this,
                                                    "ServerDB", null, 1);

                                            SQLiteDatabase db = dbinstance
                                                    .getWritableDatabase();

                                            ContentValues values = new ContentValues();
                                            values.put("address", ed_address
                                                    .getText().toString());
                                            values.put("mntFolder",
                                                    ed_mntFolder.getText()
                                                            .toString());
                                            values.put("resorceName",
                                                    ed_resourceName.getText()
                                                            .toString());

                                            db.insert("ServerDB", null, values);
                                            db.close();

                                            Log.i("INSERT", values.toString());

                                            DisplayMetrics metrics = new DisplayMetrics();
                                            getWindowManager()
                                                    .getDefaultDisplay()
                                                    .getMetrics(metrics);

                                            // metrics.heightPixels;
                                            // metrics.widthPixels;

                                            Crouton.makeText(
                                                    ServersActivity.this,
                                                    getString(R.string.insertion_ok),
                                                    Style.CONFIRM).show();

                                            // Now we need to update the
                                            // ListView
                                            runOnUiThread(new Runnable() {
                                                public void run() {
                                                    ArrayList<Server> serverResults = GetServerResults();
                                                    cAdapter = null;
                                                    cAdapter = new CustomBaseAdapter(ServersActivity.this, serverResults);
                                                    cAdapter.notifyDataSetChanged();
                                                    lvServers.setAdapter(cAdapter);
                                                }
                                            });
                                        }
                                    }
                                })
                        .setNegativeButton(
                                getResources().getString(R.string.cancel),
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                            int id) {
                                        dialog.cancel();
                                    }
                                });

                AlertDialog alertDialog = alertDialogBuilder.create();

                alertDialog.show();

            }

        });

        btnDelServer.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Time to delete the selected item of the listview
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.servers, menu);
        return true;
    }

    private ArrayList<Server> GetServerResults() {
        ArrayList<Server> results = new ArrayList<Server>();

        ServersSQLiteDB dbinstance = new ServersSQLiteDB(ServersActivity.this,
                "ServerDB", null, 1);

        SQLiteDatabase db = dbinstance.getReadableDatabase();

        Cursor c = db.rawQuery("SELECT * FROM ServerDB WHERE 0", null);
        try {
            // Nos aseguramos de que existe al menos un registro
            if (c.moveToFirst()) {
                // Recorremos el cursor hasta que no haya más registros
                do {
                    int code = c.getInt(0);
                    String address = c.getString(1);
                    String mntFolder = c.getString(2);
                    String resourceName = c.getString(3);
                    Server dummy = new Server();
                    dummy.setCode(code);
                    dummy.setAddress(address);
                    dummy.setMntFolder(mntFolder);
                    dummy.setResourceName(resourceName);
                    Log.i("GET", dummy.toString());
                    results.add(dummy);
                    dummy = null;
                } while (c.moveToNext());
            }
        } finally {
            c.close();
            db.close();
        }

        return results;
    }

    // Check if a EditText is empty
    private boolean isEmpty(EditText etText) {
        if (etText.getText().toString().trim().length() > 0) {
            return false;
        } else {
            return true;
        }
    }

}

感谢您的所有评论。

4

1 回答 1

1

将您的查询更改为以下以读取所有记录:

Cursor c = db.rawQuery("SELECT * FROM ServerDB", null);
于 2013-10-15T11:47:11.377 回答