2

so my problem is that I need to retrieve data from database to one specific pre-define activity. When i click on any item from listview it will every time show the same activity just fill with different data. Item 1 has different data then item 2. I've already had the saving data and opening specific pre-define activity. But I don't know how to fill the activity with my data. I'm starting to be desperate. So i would be gratefull for any help.

this is my code 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);
            }
        });


    }
}

Retrieve Data

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>

EDIT 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;


    }
}

EDIT 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());




        }
    }
}
J Sol
  • 67
  • 7
  • Shouldn't it be `intent.putExtra("data", listDataAdapter.get(position));` ? – Titus Aug 02 '16 at 18:06
  • But in that case android says that: Can't resolve method get(int) – J Sol Aug 02 '16 at 18:16
  • You seem to be using a custom adapter `ListDataAdapter`, you'll have to implement this `get(int index)` method in your adapter to make it return the `DataProvider` object associated with a given list item (based on position/index). – Titus Aug 02 '16 at 18:18
  • I'm really sorry but I'm new in Android so i don't really know how to do this method. you mean somthing like `public void get(int index) ` ? – J Sol Aug 02 '16 at 18:27
  • You need to add a `public DataProvider get(int index)` method to your `ListDataAdapter` class, this method should return the `DataProvider` object that is associated with the list item at that index. I can't be more specific because I'm not sure how your `ListDataAdapter` class looks like. – Titus Aug 02 '16 at 18:30
  • Thank you so much, you are awesome!! I made edit in my post so i can show you ListDataAdapter – J Sol Aug 02 '16 at 18:37
  • It seems that you already have a method (`getItem(int position)`) that you can use to retrieve the `DateProvider` for an item at a given position. The call should look like this `intent.putExtra("data", (DataProvider) listDataAdapter.getItem(position));` – Titus Aug 02 '16 at 18:41
  • Still not working, it just show the activity but all edittexts are empty. Could that be because i don't have all editTExts, I mean I save about 200 strings and 2 pictures but now showing just one picture and 20 strings – J Sol Aug 02 '16 at 18:53
  • I'm not sure why that is, in the code that you've posted, you don't seem to be using the `DataProvider` object in any way in the `RetrieveData` activity. – Titus Aug 02 '16 at 19:00
  • If you be that kind, I can show rest of my code, if that would help. I really dont know what im doing wrong. – J Sol Aug 02 '16 at 19:07
  • 1) do not use `ArrayAdapter`, use `SimpleCursorAdapter` instead, 2) pass an `id` to the other activity (see the last parameter of the item click listener) – pskink Aug 02 '16 at 19:11
  • 1) I was making it from tutorial and there was an `ArrayAdapter` so i really dont know how to implement the `SimpleCursorAdapter` 2) i'm really sorry but i don't know what you mean. Sorry that I'm so dumb but I'm really a beginner. – J Sol Aug 02 '16 at 19:17
  • you dont need to implement anything: just create a new `SCA`, when you setup your `SCA` see what value has the last parameter of `onItemClick` method – pskink Aug 02 '16 at 19:23
  • so i just add this `SimpleCursorAdapter SCA = new SimpleCursorAdapter();` to my code below `List list = new ArrayList();` in `ListDataAdapter` ? The part about values just dont understand – J Sol Aug 02 '16 at 19:35
  • call `ListView#setAdapter` with an `SCA` instance, you dont need any `List`, just use a `Cursor` to initialize your `SCA` – pskink Aug 02 '16 at 20:05
  • Excuse me but can you just show me what you mean. `SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, db.getAllTitles(), new String[] { "title" }, new int[] { android.R.id.text1 });` it should look like this right? but i dont know which my values i should use. – J Sol Aug 02 '16 at 20:12
  • it is ok, doesn't it work? – pskink Aug 02 '16 at 20:32
  • This is from another thread. A actually don't know what to write there – J Sol Aug 02 '16 at 20:36
  • what column of your `Cursor` do you want to show? – pskink Aug 02 '16 at 20:38
  • I want to show all data which relate to the user choice from list view like if he choose row 4 it will show all information about this particular form. – J Sol Aug 02 '16 at 20:45
  • what do you want to show in every single list view item? what is your db table definition? – pskink Aug 02 '16 at 20:46
  • in that i want to show variable kod and den. – J Sol Aug 02 '16 at 20:48
  • so pass `new String[] {"kod", "den"}` – pskink Aug 02 '16 at 20:51
  • so it should be `SimpleCursorAdapter SCA = new SimpleCursorAdapter(new String[] {"kod", "den"})` but there should be other variables shouldn't be? – J Sol Aug 02 '16 at 20:59
  • did you see SCA doicumentation? look what parameters are passed to its constructor – pskink Aug 02 '16 at 20:59
  • I'm look at it right now it should look like this `SimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to)` and sorry for asking but i should write it in my ListDataAdapter right? – J Sol Aug 02 '16 at 21:03
  • why dont you just google for `SimpleCursorAdapter`? the second link is: https://thinkandroid.wordpress.com/2010/01/09/simplecursoradapters-and-listviews/ – pskink Aug 02 '16 at 21:09
  • Because I'm lost and don't know what I'm doing and how to put `SCA` and `ArrayAdapter` together... – J Sol Aug 02 '16 at 21:13
  • you **DONT** need any `ArrayAdapter` this is what i am trying to say from the very beginning: `"1) do not use ArrayAdapter, use SimpleCursorAdapter instead, 2) pass an id to the other activity (see the last parameter of the item click listener)"` – pskink Aug 02 '16 at 21:25
  • ohh again so sorry. So i should erase everything from ListDataAdapter and do it by SCA. but in that case everything i have would be useless. – J Sol Aug 02 '16 at 21:29
  • yes it is way too overcomplicated, just use `SCA` and remove that useless code – pskink Aug 02 '16 at 21:47
  • So i'm trying to do it, but still not working. i edit the main thread. – J Sol Aug 02 '16 at 22:09

2 Answers2

2

use this code to see how listView works with databse:
Create a new project and copy and Paste codes to it. PLEASE DO NOT FORGET TO ADD YOUR PROJECT PACKAGE NAME TO EACH CLASS
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);
            }
        }
    }

}


class 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;
    }
}


class 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();
    }
}


class 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>

That's all Hope to useful for you

Hamid
  • 1,493
  • 2
  • 18
  • 32
  • 1
    Thank you so much, you are really kind! Despite giving me errors when I click on `startActivity` I maybe got the solution i try to use `get method` in `Retrieve data` and it's working (**see EDIT 4**). I know that maybe it isn't the best or right solution but i think i can't do much more. But again thank you(@Hamid) and all other users(@pskink and @Titus) for your patience and kindness!! – J Sol Aug 03 '16 at 11:07
1

For Start, Create a class called ClassA that hold your list items and implement getId() method on it;

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

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

then create an array of your class in your class:

ArrayList<ClassA> list = new ArrayList();

change extends ArrayAdabter with extends BaseAdapter and implement getItemId(int position) method like this:

@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;
    }

use non static viewHolder in your listDataAdapter class. for more info visit this post

Edit:
ViewHolder class hold your listView items, to put them on the correct position.

public class ViewHolder {

    public TextView yourTextView;
    public ImageView yourImage;


  }
Community
  • 1
  • 1
Hamid
  • 1,493
  • 2
  • 18
  • 32
  • thank you so much, but now i'm totally confused. So i should not use the SimpleCursorAdapter. I did the changes you wrote and look for more info, but I've got still errors. I'm really desperate. – J Sol Aug 02 '16 at 22:51
  • 1
    ViewHolder class added , and have been used in getView() method – Hamid Aug 02 '16 at 23:16
  • yes but if i try to write ClassA it shows mistakes so i change it and if i write getView class like you do it shows mistakes too.. It shows `newViewHolder = new NewViewHolder();` and `newViewHolder = (NewViewHolder)new_view.getTag();` are incompatible types and can't resolve `newViewHolder.kod` and` ViewHolder.setTag` I edited my question to show my code. – J Sol Aug 02 '16 at 23:34
  • @JanSoldát look at this sample :http://www.mysamplecode.com/2012/07/android-listview-cursoradapter-sqlite.html – Hamid Aug 02 '16 at 23:52
  • But its SimpleCursorAdapter, I'm sorry but I don't see how to connected with my problem. – J Sol Aug 03 '16 at 08:05
  • So i can get the listview and i can start a pre-define activity when i click on listview item. So my question is how to fill this activity with data from database based on click listview item. And i'm really a beginner so please tell me it like I'm the dumbest person you know. – J Sol Aug 03 '16 at 09:13