0

I'm working on application where user keys in his friends' personal details and save into SQLite Database. Then the user can view his friends' information in another page(activity). But when the user need to view his friend's info, it's not displayed in the 2nd activity. The information need to be retrieved from the database table. How do I do that?

Here are the codes -
First activity -

public class PersonalInformation extends Activity
{
    EditText txtLikes, txtDislikes, txtType, txtDate;
    Button btnView, btnBack;
    Spinner nameSpinner;    

    ArrayAdapter<String> adapter;
    String friends[] = {"Kanak Priya", "Joanne Liew", "Melissa Haiting", "Michelle Lam", "Teo Kin Hua", "David Yeo", "Nur Ashiqin", "Stephanie"};

    final Context context = this;

    private int namesSpinnerId;        

    LikesDBAdapter likeDB = new LikesDBAdapter(this);
    DislikesDBAdapter dlikeDB = new DislikesDBAdapter(this);


    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.info);

        nameSpinner = (Spinner) findViewById(R.id.nameSpinner);

        adapter = new ArrayAdapter<String>(this,
                R.layout.spinner_text, friends);
        nameSpinner.setAdapter(adapter);

        /*BuddyDBAdapter buddyDB = new BuddyDBAdapter(this);
    //  buddyDB.open();

        Cursor friendsCursor = buddyDB.getAllNames();
        startManagingCursor(friendsCursor); 

        String[] from = new String[]{BuddyDBAdapter.KEY_NAME};
        int[] to = new int[]{R.id.name};

        SimpleCursorAdapter friendsCursorAdapter = new SimpleCursorAdapter(this, R.layout.spinner_text, friendsCursor, from, to);
        friendsCursorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        nameSpinner = (Spinner)findViewById(R.id.nameSpinner);
        nameSpinner.setAdapter(friendsCursorAdapter);
        //buddyDB.close();


        nameSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
            {
                 @Override
                 public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
                 {
                     Cursor c = (Cursor)parent.getItemAtPosition(pos);
                     namesSpinnerId = c.getInt(c.getColumnIndexOrThrow(BuddyDBAdapter.KEY_ROWID));
                 }

                @Override
                public void onNothingSelected(AdapterView<?> parent)
                {
                    // TODO Auto-generated method stub

                }
            });
        //buddyDB.close();
*/      
        Button btnSave = (Button) findViewById(R.id.btnSave);
        btnSave.setOnClickListener(new View.OnClickListener()
            {

                @Override
                public void onClick(View v)
                {
                    likeDB.open();
                    long like_id;

                    nameSpinner = (Spinner) findViewById(R.id.nameSpinner);
                    String NameValue = nameSpinner.getSelectedItem().toString();

                    txtLikes = (EditText) findViewById(R.id.txtLikes);
                    String LikeValue = txtLikes.getText().toString();



                    like_id = likeDB.insertLikes(LikeValue, NameValue);
                    likeDB.close();

                    dlikeDB.open();
                    long dlike_id;

                    nameSpinner = (Spinner) findViewById(R.id.nameSpinner);
                    String NamesValue = nameSpinner.getSelectedItem().toString();

                    txtDislikes = (EditText) findViewById(R.id.txtDislikes);
                    String DislikeValue = txtDislikes.getText().toString();

                    dlike_id = dlikeDB.insertDislikes(DislikeValue, NamesValue);
                    dlikeDB.close();

                    txtDate = (EditText) findViewById(R.id.txtDate);
                    txtType = (EditText) findViewById(R.id.txtType);                    
                    txtLikes = (EditText) findViewById(R.id.txtLikes);
                    txtDislikes = (EditText) findViewById(R.id.txtDislikes);

                    if(txtDate.getText().toString().length() == 0 || txtType.getText().toString().length() == 0 || 
                            txtLikes.getText().toString().length() == 0 || txtDislikes.getText().toString().length() == 0)

                    {
                        txtDate.setError("Please key in the date");
                        txtType.setError("Please key in category");
                        txtLikes.setError("Please key in their likes");
                        txtDislikes.setError("Please key in their dislikes");
                    }
                    else
                    {
                        Toast.makeText(getBaseContext(), "Your information is saved successfully! :D", Toast.LENGTH_LONG).show();
                    }                                                   
                }
            });

        btnBack = (Button) findViewById(R.id.btnMain);
        btnBack.setOnClickListener(new View.OnClickListener()
            {

                @Override
                public void onClick(View arg0)
                {
                    finish();

                }
            });

        btnView = (Button) findViewById(R.id.btnView);
        btnView.setOnClickListener(new View.OnClickListener()
            {

                @Override
                public void onClick(View v)
                {
                    nameSpinner = (Spinner) findViewById(R.id.nameSpinner);
                    EditText txtDate = (EditText) findViewById(R.id.txtDate);
                    EditText txtType = (EditText) findViewById(R.id.txtType);
                    EditText txtLikes = (EditText) findViewById(R.id.txtLikes);
                    EditText txtDislikes = (EditText) findViewById(R.id.txtDislikes);

                    Intent i = new Intent(PersonalInformation.this, SavedInfo.class);                   
                    Bundle b = new Bundle();
                    b.putString("name", nameSpinner.getSelectedItem().toString());
                    b.putString("date", txtDate.getText().toString());
                    b.putString("category", txtType.getText().toString());
                    b.putString("likes", txtLikes.getText().toString());
                    b.putString("dislikes", txtDislikes.getText().toString());
                    i.putExtras(b);
                    startActivity(i);
                }
            });

        EditText txtDate = (EditText) findViewById(R.id.txtDate);
        txtDate.setHint("birthdate or wedding date");
        txtDate.setFilters(new InputFilter[] {
                new InputFilter() {

                    @Override
                    public CharSequence filter(CharSequence source, int start,
                            int end, Spanned dest, int dstart, int dend)
                    {
                        if(source.equals(""))
                        {
                            return source;
                        }
                        if(source.toString().matches("[0-9 -]+"))
                        {
                            return source;
                        }
                        return "";
                    }

                }
            });

        EditText txtType = (EditText) findViewById(R.id.txtType);
        txtType.setHint("birthday or wedding");
        txtType.setFilters(new InputFilter[] {
                new InputFilter() {

                    @Override
                    public CharSequence filter(CharSequence source, int start,
                            int end, Spanned dest, int dstart, int dend)
                    {
                        if(source.equals(""))
                        {
                            return source;
                        }
                        if(source.toString().matches("[birthday wedding Birthday Wedding BIRTHDAY WEDDING]+"))
                        {
                            return source;
                        }
                        return "";
                    }

                }
            });

        EditText txtLikes = (EditText) findViewById(R.id.txtLikes);
        txtLikes.setHint("e.g. Skating, Photography separate by comma");
        txtLikes.setFilters(new InputFilter[] {
                new InputFilter() {

                    @Override
                    public CharSequence filter(CharSequence source, int start,
                            int end, Spanned dest, int dstart, int dend)
                    {
                        if(source.equals(""))
                        {
                            return source;
                        }
                        if(source.toString().matches("[a-z A-Z -]+"))
                        {
                            return source;
                        }
                        return "";
                    }

                }
            });

        EditText txtDislikes = (EditText) findViewById(R.id.txtDislikes);
        txtDislikes.setHint("e.g. Skating, Photography separate by comma");
        txtDislikes.setFilters(new InputFilter[] {
                new InputFilter() {

                    @Override
                    public CharSequence filter(CharSequence source, int start,
                            int end, Spanned dest, int dstart, int dend)
                    {
                        if(source.equals(""))
                        {
                            return source;
                        }
                        if(source.toString().matches("[a-z A-Z -]+"))
                        {
                            return source;
                        }
                        return "";
                    }

                }
            });


    }
}

2nd activity

public class SavedInfo extends Activity
{
    final Context context = this;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.saved_info);

        Bundle b = this.getIntent().getExtras();
        String name = b.getString("name");
        String date = b.getString("date");
        String category = b.getString("category");
        String likes = b.getString("likes");
        String dislikes = b.getString("dislikes");

        ((TextView)findViewById(R.id.textName)).setText(name);
        ((TextView)findViewById(R.id.textDate)).setText(date);
        ((TextView)findViewById(R.id.textType)).setText(category);
        ((TextView)findViewById(R.id.textLikes)).setText(likes);
        ((TextView)findViewById(R.id.textDislikes)).setText(dislikes);

        Button btnEdit = (Button) findViewById(R.id.btnEdit);
        btnEdit.setOnClickListener(new View.OnClickListener()
            {

                @Override
                public void onClick(View v)
                {
                    Intent backIntent = new Intent(context, PersonalInformation.class);
                    startActivity(backIntent);

                }
            });

        Button btnBack = (Button) findViewById(R.id.btnMain);
        btnBack.setOnClickListener(new View.OnClickListener()
            {

                @Override
                public void onClick(View v)
                {
                    Intent menuIntent = new Intent(context, MainPage.class);
                    startActivity(menuIntent);
                }
            });
    }

}

Please help me how to retrieve data from database table into the 2nd activity as TextView
I'll appreciate any help provided. Thanks in advance! =)

14
  • arent you getting the data displayed in the second activity? Commented Sep 27, 2012 at 8:13
  • oh, I should've said that, after the user keys in his friend's details and view the info there are details displayed in the 2nd activity. But if the user goes back to 1st activity and choose his same friend and view the info he keyed in, the data is not there plus it should be displayed from the database table. let me know if you understand or dont understand what i mean. thanks Commented Sep 27, 2012 at 8:16
  • are you getting any warning/error in the logcat the second time? Commented Sep 27, 2012 at 8:23
  • there is no error or warning in the LogCat. I didn't code in the 2nd activity in retrieving data from database table and I'm not sure how to do it. Commented Sep 27, 2012 at 8:34
  • And, data should be retrieved from the database table where the data is inserted from the 1st activity Commented Sep 27, 2012 at 8:35

1 Answer 1

1

If I understand correctly, what you need, following is a code snippet to extract results from the SQLite database for a query. Hoping this will help you:

// Access Database to fetch info
try {
    newDB = myDbHelper.getReadableDatabase();

    String query = "SELECT * FROM tbl_name WHERE...... = ";
    Cursor c = newDB.rawQuery(query,null);

    if (c != null ) {
        if (c.moveToFirst()) {
            do {
                Bean infoBean = new infoBean();
                infoBean.firstName = c.getString(c.getColumnIndex("firstName"));
                infoBean.lastName = c.getInt(c.getColumnIndex("lastName"));
                infoBean.id = c.getInt(c.getColumnIndex("_id"));

                // Do something here to display information in TextView

            } while (c.moveToNext());
        } 
    }           
} catch (SQLiteException se) {
    Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} 

myDbHelper.close();
Sign up to request clarification or add additional context in comments.

6 Comments

Hi, thanks for your answer. May I know what & why is Bean used for?
@MiyayayayaMi : Basically a java bean is just a standard 1) All properties private (use getters/setters) 2) A public no-argument constructor 3) Implements Serializable. So there is basically no syntactic difference between a regular class and a java bean. A class defines a java bean if it follows the above standards.
oh right, it's a Java Bean. But it can be used in Android coding too?
Should I type in the codes in DBAdapter or in the 2nd activity?
Yes it can be used in Android. The classes defined using above standards allows libraries to programatically do things with class instances that you would define using a predefined way. You should write the code in 2nd Activity and then setText for the TextView once you retrieve the values from the cursor.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.