0

On my first activity I have a ListView getting data from a database (SQLite). I can display the description on the ListView (e.g Buy christmas presents, Buy turkey, ...).

public class OpenHelper extends SQLiteOpenHelper {

 public static final String NAME = "oef.db";
 public static final int VERSION = 1; 

public OpenHelper(Context context) {
    super(context, NAME, null, VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    onUpgrade(db, 1, VERSION);  
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    String sqlCreateTodo = "CREATE TABLE TODOS (_id INTEGER PRIMARY KEY AUTOINCREMENT, description TEXT, reason TEXT, image TEXT)";
    db.execSQL(sqlCreateTodo);

    String sqlInsertTodo = "INSERT INTO TODOS (description, reason, image) VALUES(?,?,?)";
    db.execSQL(sqlInsertTodo, new Object[] { "Buy Christmas presents.", "Family", "ic_launcher" });
    db.execSQL(sqlInsertTodo, new Object[] { "Buy turkey.", "Family", "ic_launcher" });
    db.execSQL(sqlInsertTodo, new Object[] { "Buy beer.", "Me", "ic_launcher" });
    db.execSQL(sqlInsertTodo, new Object[] { "Buy more beer.", "Me", "ic_launcher" });
    db.execSQL(sqlInsertTodo, new Object[] { "Buy tree.", "Family", "ic_launcher" });
}
}

First problem: I also would like to show the image and reason on my MainActivity. (Image - description - reason)

public class MainActivity extends ListActivity implements LoaderCallbacks<Cursor>{

private static final int TEST_LOADER = 0;
private SimpleCursorAdapter adapter;

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

    String[] from = new String[] { "description" };
    int[] to = new int[] { android.R.id.text1 };
    adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, null, from, to, 0);
    setListAdapter(adapter);

    getLoaderManager().initLoader(TEST_LOADER, null, this); 

    //listtest.setOnItemClickListener(new AdapterView.OnItemClickListener() {       
    //ListView listtest = (ListView) findViewById(R.id.list);   
    ListView lv = getListView();
    lv.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> adapter, View view, int position, long id){
            Intent intent = new Intent(MainActivity.this, Detail.class);
            intent.putExtra("id", id);
            startActivity(intent);

           // startActivityForResult(intent, 0);
        }
    });
}

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    if (id == TEST_LOADER){
    SQLiteCursorLoader cursorLoader = new SQLiteCursorLoader(this, new OpenHelper(this), "SELECT _id, description FROM TODOS", null);   
        return cursorLoader;
    }
    return null;
}

@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
    adapter.swapCursor(arg1);
}

@Override
public void onLoaderReset(Loader<Cursor> arg0) {
    adapter.swapCursor(null);
}
}

Second problem: When clicking on an item from the ListView, I want to pass the data of that item onto the second activity. Displaying the image, description and reason in the controls. (e.g When clicked on the first row --> myDescription text = Buy christmas presents, myReason tex = family, myImage = set the background image)

    <ImageView
        android:id="@+id/myImage"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:contentDescription="@string/hello_world"
        android:layout_marginTop="5dp"
        android:layout_centerHorizontal="true"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/myDescription"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

    <TextView
        android:id="@+id/myReason"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/myDescription"
        android:layout_below="@+id/myDescription"
        android:layout_marginTop="57dp"
        android:text="@string/hello_world" />

Second activity:

public class Detail extends Activity {

public static String[] DESCRIPTION = null;

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

    Bundle b = new Bundle();
    b = getIntent().getExtras();
    long id = b.getLong("id");

    TextView t = new TextView(this); 
    t =(TextView)findViewById(R.id.myDescription);
    t.setText(String.valueOf(id));

/*      TextView t = new TextView(this); 
    t =(TextView)findViewById(R.id.myDescription);
    t.setText("Show description");    */  

    TextView t1 = new TextView(this); 
    t1 =(TextView)findViewById(R.id.myReason);
    t1.setText("Show reason");      

    //Show the correct image
    ImageView image = new ImageView(this);
    image = (ImageView)findViewById(R.id.myImage);
    // .... image.setBackground
    //image.setBackgroundResource(R.drawable.ic_launcher);     
}

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

For the second problem I probably need to query the database? Thanks guys!

user1951083
  • 261
  • 1
  • 5
  • 20
  • What are you doing with this database? In onCreate you create your tables, onUpgrade usually deals with upgrading the database version, and dealing with the changes. You don't add stuff from there. [Here](http://www.vogella.com/tutorials/AndroidSQLite/article.html#databasetutorial) is a tutorial. As for depicting a lot of stuff in your listview, [this](http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/) might help you. – Yordan Lyubenov Jan 15 '14 at 09:38
  • To pass the data to another activity, you can use "intent.putExtra("item", value);" like you are already doing with the id. – randomizer Jan 15 '14 at 09:38
  • @YordanLyubenov This is how I've seen it at school.. Thanks for the links! – user1951083 Jan 15 '14 at 09:45
  • @randomizer Can you be a little more specific? I've tried to send the description but never succeeded. – user1951083 Jan 15 '14 at 09:46
  • I've added an answer regarding passing the data. – randomizer Jan 15 '14 at 10:50

3 Answers3

1

You can create a Hashmap to use it as an adapter for your listview.

ArrayList<HashMap<String, String>> yourlist = new ArrayList<HashMap<String, String>>();
HashMap<String,String> hm = new HashMap<String,String>();
hm.put("description",description);
yourlistview.add(hm);

If you want to show an image, just make sure you have an imageview in your xml, so you can do something like this:

String[] from = { "image","some text","some other text" }; 
//Id(s of the views in your listviewlayout
int[] to = { R.id.image,R.id.sometext,R.id.someothertext};
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), yourlist, R.layout.listview_layout, from, to);

In your itemclick event you can acces the item like this:

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              
       HashMap<String, String> map = (HashMap<String, String>) yourlistview.getItemAtPosition(position);
       yourlistview.getItemAtPosition(position);
       Intent intent = new Intent(MainActivity.this, Detail.class);
       intent.putExtra("description", map.get("description"));
...
}
randomizer
  • 1,619
  • 3
  • 15
  • 31
  • With "yourlistview" to which one are you referring? The one in XML or ListView lv = getListView(); Getting an error on lv.add(hm); --> The method add(HashMap) is undefined for the type ListView – user1951083 Jan 15 '14 at 11:08
  • You should create an arraylist to hold the items, I forgot to add the line, I updated the answer. – randomizer Jan 15 '14 at 11:09
  • Thanks that solved it! hm.put("description", description); What stands the second description for? – user1951083 Jan 15 '14 at 11:20
  • That would be the variable that you want to add to the hashmap, like the value from an inputfield, ... – randomizer Jan 15 '14 at 12:24
0

You can create an object holding the data and then pass the entire object to the second activity. You can take a look here to pass objects between activities.

Community
  • 1
  • 1
Abdelbari Anouar
  • 246
  • 3
  • 10
0

Since you are using CursorAdapter, the list view contains the cursor which holds the items you have queried from the database and stored in the adapter. So, lv.getItemAtPosition(position) inside your listitemclicklistener will return you the cursor pointing to the item at selected 'position'. From the cursor you can get the required values using cursor.getString().

Manoj Seelan
  • 686
  • 5
  • 5