user1951083
user1951083

Reputation: 261

Passing data (from database) to next activity

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!

Upvotes: 0

Views: 1799

Answers (3)

Manoj Seelan
Manoj Seelan

Reputation: 686

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().

Upvotes: 0

randomizer
randomizer

Reputation: 1649

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"));
...
}

Upvotes: 1

Abdelbari Anouar
Abdelbari Anouar

Reputation: 246

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.

Upvotes: 0

Related Questions