Android - 基于onclick listview从SQLite数据库中检索数据

时间:2016-08-02 17:55:52

标签: java android sqlite

所以我的问题是我需要从数据库中检索数据到一个特定的预定义活动。当我点击listview中的任何项目时,它将每次显示相同的活动,只填充不同的数据。第1项与第2项有不同的数据。我已经有了保存数据并打开了特定的预定义活动。但我不知道如何用我的数据填充活动。我开始绝望了。所以我会感激任何帮助。

这是我的代码 DataListActivity.java

public class DataListActivity extends AppCompatActivity {
    ListView listView;
    SQLiteDatabase sqLiteDatabase;
    DbOperace dbOperace;
    Cursor cursor;
    ListDataAdapter listDataAdapter;

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

        listView = (ListView) findViewById(R.id.lis_view);
        listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.row_layout);
        listView.setAdapter(listDataAdapter);

        dbOperace = new DbOperace(getApplicationContext());
        sqLiteDatabase = dbOperace.getReadableDatabase();
        cursor = dbOperace.getInformations(sqLiteDatabase);

        if (cursor.moveToFirst())
        {
            do {

                String kod,den;
                kod = cursor.getString(0);
                den = cursor.getString(1);
                DataProvider dataProvider = new DataProvider(kod,den);
                listDataAdapter.add(dataProvider);

            }while (cursor.moveToNext());
        }

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(DataListActivity.this, RetrieveData.class);
                intent.putExtra("data", listView.getSelectedItemPosition());
                startActivity(intent);
            }
        });


    }
}

检索数据

public class RetrieveData extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrieve_data);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            DataProvider dataProvider = bundle.getParcelable("data");
        }
    }
}

DataProvider.java

    package jansoldat.formular100;

import android.os.Parcel;
import android.os.Parcelable;

/**
 * Created by Monsignore Frajeris on 02.08.2016.
 */
public class DataProvider implements Parcelable {

    private String kod;
    private String den;

    public String getKod() {
        return kod;
    }

    public void setKod(String kod) {
        this.kod = kod;
    }

    public String getDen() {
        return den;
    }

    public void setDen(String den) {
        this.den = den;
    }

    public DataProvider(String kod, String den)
    {
        this.kod=kod;
        this.den=den;

    }

    protected DataProvider(Parcel in) {
        kod = in.readString();
        den = in.readString();
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(kod);
        dest.writeString(den);
    }

    @SuppressWarnings("unused")
    public static final Parcelable.Creator<DataProvider> CREATOR = new Parcelable.Creator<DataProvider>() {
        @Override
        public DataProvider createFromParcel(Parcel in) {
            return new DataProvider(in);
        }

        @Override
        public DataProvider[] newArray(int size) {
            return new DataProvider[size];
        }
    };
}

RetrieveData.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/scrollView"
    xmlns:android="http://schemas.android.com/apk/res/android">


    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="jansoldat.formular100.MainActivity">


        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Úsek komunikace:"
            android:id="@+id/textView81"
            android:textStyle="bold"
            android:textSize="20dp"
            android:textColor="#870b0f"
            android:layout_marginTop="30dp"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText_Usek_komunikace"
            android:layout_below="@+id/textView81"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Kód úseku komunikace:"
            android:id="@+id/textView82"
            android:layout_column="0"
            android:textColor="#870b0f"
            android:textStyle="bold"
            android:layout_below="@+id/editText_Usek_komunikace"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="15dp" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/kod"
            android:layout_below="@+id/textView82"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Kódy sousedících objektů/ komunikací"
            android:id="@+id/textView83"
            android:layout_column="0"
            android:textColor="#870b0f"
            android:textStyle="bold"
            android:layout_below="@+id/kod"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_marginTop="15dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="na počátku úseku komunikace:"
            android:id="@+id/textView84"
            android:layout_column="0"
            android:textColor="#870b0f"
            android:textStyle="bold"
            android:layout_below="@+id/textView83"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignRight="@+id/textView81"
            android:layout_alignEnd="@+id/textView81"
            android:layout_marginTop="10dp" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText3"
            android:layout_below="@+id/textView84"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignRight="@+id/textView84"
            android:layout_alignEnd="@+id/textView84" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="na konci úseku komunikace:"
            android:id="@+id/textView85"
            android:layout_column="0"
            android:textColor="#870b0f"
            android:textStyle="bold"
            android:layout_below="@+id/textView83"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_toRightOf="@+id/textView86"
            android:layout_toEndOf="@+id/textView86"
            android:layout_marginTop="10dp" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText4"
            android:layout_below="@+id/textView84"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_alignLeft="@+id/textView85"
            android:layout_alignStart="@+id/textView85" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Součást měřené trasy/ lokality:"
            android:id="@+id/textView86"
            android:layout_column="0"
            android:textColor="#870b0f"
            android:textStyle="bold"
            android:layout_below="@+id/editText3"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="15dp" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText5"
            android:layout_below="@+id/textView86"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="GPS souřadnice"
            android:id="@+id/textView87"
            android:layout_column="0"
            android:textColor="#870b0f"
            android:textStyle="bold"
            android:layout_below="@+id/editText5"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="15dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="počátek měřeného úseku:"
            android:id="@+id/textView88"
            android:layout_column="0"
            android:textColor="#870b0f"
            android:textStyle="bold"
            android:layout_below="@+id/textView87"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="10dp"
            android:layout_marginLeft="10dp" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText6"
            android:layout_alignParentStart="true"
            android:inputType="numberDecimal"
            android:digits="0123456789,.°&apos;"
            android:layout_below="@+id/textView88"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="konec měřeného úseku:"
            android:id="@+id/textView89"
            android:layout_column="0"
            android:textColor="#870b0f"
            android:textStyle="bold"
            android:layout_below="@+id/editText6"
            android:layout_alignParentLeft="true"
            android:layout_marginTop="10dp"
            android:layout_marginLeft="10dp" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText7"
            android:digits="0123456789,.°&apos;"
            android:inputType="numberDecimal"
            android:layout_below="@+id/textView89"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Mapové schéma:"
            android:id="@+id/textView90"
            android:layout_column="0"
            android:textColor="#870b0f"
            android:textStyle="bold"
            android:layout_below="@+id/editText7"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="15dp" />

        <ImageView
            android:layout_width="250dp"
            android:layout_height="250dp"
            android:id="@+id/imageView_mapa"
            android:contextClickable="false"
            android:adjustViewBounds="false"
            android:background="#850202"
            android:layout_below="@+id/textView90"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="10dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Měření provedl(i):"
            android:id="@+id/textView91"
            android:layout_column="0"
            android:textColor="#870b0f"
            android:textStyle="bold"
            android:layout_below="@+id/imageView_mapa"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="15dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="dne:"
            android:id="@+id/textView92"
            android:layout_column="0"
            android:textColor="#870b0f"
            android:textStyle="bold"
            android:layout_above="@+id/editText8"
            android:layout_toRightOf="@+id/textView86"
            android:layout_toEndOf="@+id/textView86" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="date"
            android:ems="10"
            android:id="@+id/editText8"
            android:layout_below="@+id/textView91"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignRight="@+id/textView88"
            android:layout_alignEnd="@+id/textView88" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/den"
            android:layout_below="@+id/textView92"
            android:layout_alignLeft="@+id/textView92"
            android:layout_alignStart="@+id/textView92"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Délka úseku komunikace:"
            android:id="@+id/textView93"
            android:layout_column="0"
            android:textColor="#870b0f"
            android:textStyle="bold"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/den"
            android:layout_alignParentLeft="true"
            android:layout_marginTop="10dp" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText10"
            android:layout_alignParentStart="true"
            android:inputType="numberDecimal"
            android:digits="0123456789,.m"
            android:layout_below="@+id/textView93"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Typ komunikace:"
            android:id="@+id/textView94"
            android:layout_column="0"
            android:textColor="#870b0f"
            android:textStyle="bold"
            android:layout_below="@+id/editText10"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="15dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Materiál povrchu:"
            android:id="@+id/textView95"
            android:layout_column="0"
            android:textColor="#870b0f"
            android:textStyle="bold"
            android:layout_below="@+id/radioGroup3"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="15dp" />

        <RadioGroup
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/radioGroup3"
            android:layout_below="@+id/textView94"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="10dp">

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="pás pro pěší (chodník)"
                android:id="@+id/radioButton"
                android:checked="false" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="stezka pro chodce (označeno značkou C07)"
                android:id="@+id/radioButton2"
                android:checked="false" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="stezka pro chodce a cyklisty ( označeno značkou C09 nebo C10)"
                android:id="@+id/radioButton3"
                android:checked="false" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="nezpevněná komunikace (pěšina, polní cesta...)"
                android:id="@+id/radioButton4"
                android:checked="false" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="pěší zóna (označeno značkou IP27)"
                android:id="@+id/radioButton5"
                android:checked="false" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="obytná zóna (označeno značkou IP26)"
                android:id="@+id/radioButton6"
                android:checked="false" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="pohyb po motoristické komunikaci (krajnice...)"
                android:id="@+id/radioButton7"
                android:checked="false" />
        </RadioGroup>

        <Spinner
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/spinner2"
            android:layout_below="@+id/textView95"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText11"
            android:visibility="visible"
            android:layout_below="@+id/spinner2"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />

    </RelativeLayout>


</ScrollView>

编辑3 ListDataAdapter

public class ListDataAdapter extends BaseAdapter{
    DbOperace dbOperace;
    Context context;
    SurfaceHolder newViewHolder;
    SQLiteDatabase sqliteDatabase;
    List newsList = new ArrayList();
    ArrayList<ClassA> list = new ArrayList();


    public class NewViewHolder
    {
        TextView kod,den;
    }


    @Override
    public long getItemId(int position) {
        return list.get(position).getId();
    }
    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View new_view = convertView;
        try {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            if (new_view == null) {

                new_view = inflater.inflate(R.layout.row_layout, null);

                newViewHolder = new NewViewHolder();
                newViewHolder.kod =((TextView) new_view.findViewById(R.id.t_kod));
                newViewHolder.setTag(newViewHolder);



            } else {
                newViewHolder = (NewViewHolder)new_view.getTag();
                newViewHolder.kod.setText ="your text";
            }

            // set parameters here



        } catch (Exception e) {

        }
        return new_view;
    }}

ClassA的

public class ClassA {
    private long id;

    public long getId()
    {
        return id;
    }

    public ClassA(long id)
    {
        this.id=id;


    }
}

编辑4

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;

public class RetrieveData extends AppCompatActivity {
    EditText usek_kom,kod_1,pocatek_1;



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


        usek_kom = (EditText) findViewById(R.id.usek_komunikace1);
        kod_1 = (EditText) findViewById(R.id.kod_1);
        pocatek_1 = (EditText) findViewById(R.id.pocatek_1);





        Bundle bundle = getIntent().getExtras();
        if (bundle!=null){
            DataProvider dataProvider = bundle.getParcelable("data");
            usek_kom.setText(dataProvider.getDen());
            kod_1.setText(dataProvider.getKod());
            pocatek_1.setText(dataProvider.getUsek_komun());




        }
    }
}

2 个答案:

答案 0 :(得分:2)

使用此代码查看listView如何与数据库一起使用:
创建一个新项目并复制并粘贴代码。 请不要忘记将您的项目包名称添加到每个类别
Class MainActivity.java

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;


public class MainActivity extends ActionBarActivity {

    public static String MyLog = "Log:";
    ListView myListView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myListView = (ListView) findViewById(R.id.listView);
        myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast t = Toast.makeText(getBaseContext(), "my id is:" + id, Toast.LENGTH_SHORT);
            }
        });

        //fill listView by database values
        FillListView();


    }

    private void FillListView() {

        InitDatabase();

        // read all data from database
        ListDataBaseAdapter lda = new ListDataBaseAdapter(getBaseContext());
        ArrayList<Category> allDataList =  lda.ReadAllCategory();

        // inserting into listView
        ListAdapter adapter = new CategoryListAdapter(getBaseContext(), allDataList);
        myListView.setAdapter(adapter);
    }

    private void InitDatabase() {
        ListDataBaseAdapter lda = new ListDataBaseAdapter(getBaseContext());
        // read all from database;
        ArrayList<Category> allData =  lda.ReadAllCategory();
        if(allData.size() == 0) // if db is empty, so fill it with some random data
        {
            for(int i=1000;i<1100;i++) {
                // insert some data to database;
                Category cat = new Category(i,"kod "+i,i%7);
                lda.Insert(cat);
            }
        }
    }

}


类Category.java

public class Category {
    private int id;
    private String name;
    private int order;
    private int width = 1;
    private int height = 1;

    public Category() {
    }

    public Category(int id, String name, int order) {
        setId(id);
        setName(name);
        setOrder(order);
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getOrder() {
        return order;
    }

    public void setOrder(int order) {
        this.order = order;
    }

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }
}


类CategoryListAdapter

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by Astronomer on 2016-08-03.
 */
public class CategoryListAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<Category> Category_List;
    //   int W,H;

    public CategoryListAdapter(Context context, ArrayList<Category> list_category) {
        this.context = context;
        this.Category_List = list_category;
      /*  W = w;
        h = H;*/
    }

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

        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View gridView;

        if (convertView == null) {

            gridView = new View(context);

            // get layout from mobile.xml
            gridView = inflater.inflate(R.layout.single_category_dom, null);

            // set value into textview
            TextView cat_name = (TextView) gridView
                    .findViewById(R.id.tv_name);
            cat_name.setText(Category_List.get(position).getName());

            TextView cat_id = (TextView) gridView
                    .findViewById(R.id.tv_id);
            String id_str = Category_List.get(position).getId()+"";
            cat_id.setText(id_str);

        } else {
            gridView = (View) convertView;
        }

        return gridView;
    }

    @Override
    public int getCount() {
        return Category_List.size();
    }

    @Override
    public Object getItem(int position) {
        return Category_List.get(position);
    }

    @Override
    public long getItemId(int position) {
        return Category_List.get(position).getId();
    }
}


类ListDataBaseAdapter

public class ListDataBaseAdapter {
    private Context context;
    private SQLiteOpenHelper sqLiteOpenHelper;

    private final String DB_NAME = "DB_Category.db";
    private final String TBL_Name = "tbl_category";
    private final String ID ="id";
    private final String NAME = "name";
    private final String CATEGORY_ORDER = "category_order";
    private final String WIDTH="width";
    private final String HEIGHT="height";


    public ListDataBaseAdapter(Context context)
    {
        this.context = context;
        sqLiteOpenHelper = new SQLiteOpenHelper(context, DB_NAME, null, 1) {

            @Override
            public void onCreate(SQLiteDatabase db) {
                try {
                    String sql = "CREATE TABLE IF NOT EXISTS tbl_category (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name TEXT, category_order INT, width INT, height  INT);";
                    db.execSQL(sql);
                }
                catch (Exception e)
                {
                    Log.i(MainActivity.MyLog, "can not create db!"+e.toString());
                }

            }

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

    public long Insert(Category cat) {
        int id = cat.getId();
        String name = cat.getName();
        int order = cat.getOrder();
        int w = cat.getWidth();
        int h = cat.getHeight();

        SQLiteDatabase database = null;

        try {
            ContentValues values = new ContentValues();
            values.put(ID, id);
            values.put(NAME, name);
            values.put(CATEGORY_ORDER, order);
            values.put(WIDTH, w);
            values.put(HEIGHT, h);

            database = sqLiteOpenHelper.getWritableDatabase();
            id = (int) database.insert(TBL_Name, null, values);
        } catch (Exception ex) {
            Log.i(MainActivity.MyLog, "Exception in save category::" + ex.getMessage());
        } finally {
            if (database != null && database.isOpen()) {
                database.close();
            }
        }
        return id;
    }

    public Category Read(int id) {
        Category cat = null;
        String[] columns = new String[]{ID,NAME, CATEGORY_ORDER,WIDTH,HEIGHT};
        String selection = "id=?";
        String[] selectionArgs = new String[]{String.valueOf(id)};
        String groupBy = null;
        String having = null;
        String orderBy = null;
        String limit = null;

        SQLiteDatabase database = null;
        try {
            database = sqLiteOpenHelper.getWritableDatabase();
            Cursor cursor = database.query(TBL_Name, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
            if(cursor != null && cursor.moveToFirst()) {
                int idIndex = 0;
                int nameIndex = 1;
                int orderIndex = 2;
                int wIndex = 3;
                int hIndex = 4;

                int cat_id = cursor.getInt(idIndex);
                String cat_name = cursor.getString(nameIndex);
                int cat_order = cursor.getInt(orderIndex);
                int cat_w = cursor.getInt(wIndex);
                int cat_h = cursor.getInt(hIndex);

                cat = new Category();
                cat.setId(cat_id);
                cat.setName(cat_name);
                cat.setOrder(cat_order);
                cat.setWidth(cat_w);
                cat.setHeight(cat_h);
            }

        } catch (Exception ex) {
            Log.i(MainActivity.MyLog, "Exception in Read Category:" + ex.getMessage());
        } finally {
            if (database != null && database.isOpen()) {
                database.close();
            }
        }

        return cat;
    }

    public int Update(Category cat) {
        int noOfUpdatedRecords = 0;
        String whereClause = "id=?";
        String[] whereArgs = new String[] {String.valueOf(cat.getId())};

        SQLiteDatabase database = null;

        try {
            ContentValues values = new ContentValues();
            values.put(NAME, cat.getName());
            values.put(CATEGORY_ORDER, cat.getOrder());
            values.put(WIDTH, cat.getWidth());
            values.put(HEIGHT, cat.getHeight());

            database = sqLiteOpenHelper.getWritableDatabase();
            noOfUpdatedRecords = database.update(TBL_Name, values, whereClause, whereArgs);
        } catch (Exception ex) {
            Log.i(MainActivity.MyLog, "Exception in Update category:" + ex.getMessage());
        } finally {
            if( database != null && database.isOpen()) {
                database.close();
            }
        }

        return noOfUpdatedRecords;
    }

    public int Delete(int id) {
        int noOfDeletedRecords = 0;
        String whereClause = "id=?";
        String[] whereArgs = new String[] {String.valueOf(id)};

        SQLiteDatabase database = null;

        try {
            database = sqLiteOpenHelper.getWritableDatabase();
            noOfDeletedRecords = database.delete(TBL_Name, whereClause, whereArgs);
        } catch (Exception ex) {
            Log.i(MainActivity.MyLog, "Exception in delete category:" + ex.getMessage());
        } finally {
            if( database != null && database.isOpen()) {
                database.close();
            }
        }
        return noOfDeletedRecords;
    }

    public ArrayList<Category> ReadAllCategory() {

        ArrayList<Category> categories = null;
        String[] columns = new String[]{ID, NAME, CATEGORY_ORDER,WIDTH,HEIGHT};
        String selection = null;
        String[] selectionArgs = null;
        String groupBy = null;
        String having = null;
        String orderBy = null;
        String limit = null;

        SQLiteDatabase database = null;
        try {

            database = sqLiteOpenHelper.getWritableDatabase();

            Cursor cursor = database.query(TBL_Name, columns, selection, selectionArgs, groupBy, having, orderBy, limit);

            if (cursor != null && cursor.moveToFirst()) {

                categories = new ArrayList<>();

                int idIndex = 0;
                int nameIndex = 1;
                int orderIndex = 2;
                int wIndex = 3;
                int hIndex = 4;

                do {
                    int cat_id = cursor.getInt(idIndex);
                    String cat_name = cursor.getString(nameIndex);
                    int cat_order = cursor.getInt(orderIndex);
                    int cat_w = cursor.getInt(wIndex);
                    int cat_h = cursor.getInt(hIndex);

                    Category cat = new Category();
                    cat.setId(cat_id);
                    cat.setName(cat_name);
                    cat.setOrder(cat_order);
                    cat.setWidth(cat_w);
                    cat.setHeight(cat_h);

                    categories.add(cat);
                } while(cursor.moveToNext());
            }
        } catch (Exception ex) {
            Log.i(MainActivity.MyLog, "Exception in Read All Categories:" + ex.getMessage());
        } finally {
            if (database != null && database.isOpen()) {
                database.close();
            }
        }
        return categories;
    }
}

<强> activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView android:text="@string/hello_world" android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView" />

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="196dp" />

</RelativeLayout>


single_category_dom.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_vertical|fill_vertical"
    android:layout_centerInParent="true"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="10dp"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Id:"
        android:id="@+id/textView2"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Name:"
        android:id="@+id/textView3"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="39dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Order:"
        android:id="@+id/textView4"
        android:layout_marginTop="20dp"
        android:layout_alignParentTop="false"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/textView3" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/tv_id"
        android:layout_alignParentTop="true"
        android:layout_toEndOf="@+id/textView3" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/tv_name"
        android:layout_alignTop="@+id/textView3"
        android:layout_toEndOf="@+id/textView3" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/tv_order"
        android:layout_alignTop="@+id/textView4"
        android:layout_toEndOf="@+id/textView4" />

</RelativeLayout>

这就是全部 希望对你有用

答案 1 :(得分:1)

对于Start,创建一个名为ClassA的类,用于保存列表项并在其上实现getId()方法;

public ClassA
{
    public long getId(){return this.id;}

    public string getKod()    {   return kod;  }
   // other parameters...
 }  

然后在你的班级中创建一个班级数组:

ArrayList<ClassA> list = new ArrayList();

使用extends ArrayAdabter更改extends BaseAdapter并按照以下方式实施getItemId(int position)方法:

@Override
    public long getItemId(int position) {
        return list.get(position).getId();
    }
@Override
public int getCount() {
    return list.size();
}

@Override
public Object getItem(int position) {
    return list.get(position);
}


@Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View new_view = convertView;
        try {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            if (new_view == null) {

                new_view = inflater.inflate(R.layout.single_news_dom, null);

                newViewHolder = new NewsViewHolder();

                // set parameters here  
                 newViewHolder.yourTextView =((TextView)   new_view.findViewById(R.id.kod));

                  // etc ...

                newViewHolder.setTag(newViewHolder);

            } else {
                newViewHolder = (NewViewHolder)new_view.getTag();

                newViewHolder.yourTextView.setText = "your text";
                   // etc ... 

            }

        } catch (Exception e) {

        }
        return new_view;
    }

viewHolder课程中使用非静态listDataAdapter。有关详细信息,请访问this post

修改
ViewHolder类保存listView项目,将它们放在正确的位置。

public class ViewHolder {

    public TextView yourTextView;
    public ImageView yourImage;


  }