BusraD
BusraD

Reputation: 41

How can I pass database records to second activity and display in it with listview?

I'm new to android and java. Let me explain my project. I'm writing an Android application. I want to create a database and insert,delete, modify datas from textviews. And display these datas using ListView another activity. My first question is, how to send these datas another activity? Second, I found some codes:

List<Comment> values = datasource.getAllComments();
ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this, android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);

And after these codes, inserting records codes are written. For me this is wrong because there is no record and how to take datas with getAllComments method, please explain this. Third, how to insert datas to database better way -if there is a way- I am trying to say, I'm invoking my insertion method from MainActivity like:

Contact contact = dbOperations.addContact(editName.getText().toString(), editSurname.getText().toString(), editPhone.getText().toString(), editEmail.getText().toString());

but I don't want get parameters like this. If I take parameter contact and write my code like:

ContentValues values = new ContentValues();
values.put(DBHelper.colName, contact.getName());
values.put(DBHelper.colSurname, contact.getSurname());
values.put(DBHelper.colPhone, contact.getPhone());
values.put(DBHelper.colEmail, contact.getEmail());

How should I take parameters (invoke insertion method) with textviews in MainActivity? I read an article about it and i found this code:

db.addContact(new Contact("Srinivas", "9199999999"));

addContact method takes contact parameter, so how does he write String value, if this code is true.

Fourth and last question is,

my logcat error:

08-26 19:21:06.639    9661-9661/? I/art﹕ Not late-enabling -Xcheck:jni (already on) 08-26 19:21:06.663    9661-9668/? E/art﹕ Failed writing handshake bytes (-1 of 14): Broken pipe 08-26 19:21:06.663    9661-9668/? I/art﹕ Debugger is no longer active 08-26 19:21:06.705    9661-9661/? D/AndroidRuntime﹕ Shutting down VM 08-26 19:21:06.705    9661-9661/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: busra.contactdb, PID: 9661
    java.lang.RuntimeException: Unable to start activity ComponentInfo{busra.contactdb/busra.contactdb.ContactActivity}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
     Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
            at android.app.ListActivity.onContentChanged(ListActivity.java:243)
            at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:382)
            at android.app.Activity.setContentView(Activity.java:2145)
            at busra.contactdb.ContactActivity.onCreate(ContactActivity.java:43)
            at android.app.Activity.performCreate(Activity.java:5990)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 08-26 19:26:06.781    9661-9661/? I/Process﹕ Sending signal. PID: 9661 SIG: 9

I don't know what the problem is. This line:

at busra.contactdb.ContactActivity.onCreate(ContactActivity.java:43)

point this code:

setContentView(R.layout.activity_contact);

I am getting a null pointer exception on setAdapter method. And this my ContactActivity:

public class ContactActivity extends Activity{

public static final String SEND_NAME= "";
public static final String SEND_SURNAME= "";
public static final String SEND_PHONE= "";
public static final String SEND_EMAIL= "";

DatabaseOperations dbOperations;
List values = new ArrayList();

@Override
    protected void onCreate(Bundle savedInstanceState) {


    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_contact);

    findViewAllIDs();

    dbOperations = new DatabaseOperations(this);
    dbOperations.openDB();


    values = dbOperations.getAllContacts();
    ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,values);


    list.setAdapter(adapter);

    View v = findViewById(R.id.listButton);
    v.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            if (arg0.getId() == R.id.listButton) {
                //define new intent to DisplayActivity

                Intent intent = new Intent(ContactActivity.this, DisplayActivity.class);
                String sendName = values.get(0).toString();
                intent.putExtra(SEND_NAME, sendName);


                String sendSurname = values.get(1).toString();
                intent.putExtra(SEND_SURNAME, sendSurname);


                String sendPhone = values.get(2).toString();
                intent.putExtra(SEND_PHONE, sendPhone);


                String sendEmail = values.get(3).toString();
                intent.putExtra(SEND_EMAIL, sendEmail);


                //start the second activity
                startActivity(intent);
            }
        }
    });


    btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            add();
        }
    });

    btnDelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            delete();
        }
    });
    btnModify.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // modify();
        }
    });

}

public void add(){
         ArrayAdapter adapter1 = (ArrayAdapter) list.getAdapter();
      // dbOperations.addContact(new Contact());


          Contact contact = dbOperations.addContact(editName.getText().toString(),
                  editSurname.getText().toString(),editPhone.getText().toString(),
                  editEmail.getText().toString());

          adapter1.add(contact);
          adapter1.notifyDataSetChanged();

}
public void delete(){
    Contact contact = null;
      ArrayAdapter adapter1 = (ArrayAdapter) list.getAdapter();
      if(list.getAdapter().getCount() > 0){
          contact = (Contact) list.getAdapter().getItem(0);
          dbOperations.deleteContact(contact);
          adapter1.remove(contact);
          adapter1.notifyDataSetChanged();
      }
}
public void modify () {
       Contact contact = null;
      // ArrayAdapter adapter1 = (ArrayAdapter) getListAdapter();
      if (getListAdapter().getCount() > 0) {
          contact = (Contact) getListAdapter().getItem(0);
          dbOperations.modifyContact(contact);

          adapter1.notifyDataSetChanged();
      }

And I'm invoking ListView in second layout xml from ContactActivity. list = (ListView) findViewById(android.R.id.list); is this true ? EDIT: I solved my problem but I couldn't find any solution unfortunately. How can I pass database records to second activity and display in it ?

activity_contact.xml

<?xml version= "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    tools:context=". MainActivity">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="15sp"
        android:text="@string/name"/>
    <EditText
        android:id="@+id/editName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:layout_gravity="end"
        android:singleLine="true">
        <requestFocus/>
    </EditText>



    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Surname"
        android:textSize="17sp"/>
    <EditText
        android:id="@+id/editSurname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:layout_gravity="end"
        android:singleLine="true">

    </EditText>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Phone"
        android:textSize="17sp"/>

    <EditText
        android:id="@+id/editPhone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="phone"
        android:layout_gravity="bottom"
        android:singleLine="true">

    </EditText>


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/email"
        android:textSize="17sp"/>

    <EditText
        android:id="@+id/editEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:layout_gravity="bottom"
        android:singleLine="true">

    </EditText>

    <Button
        android:id="@+id/add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/add"
        android:textColor="#000066"
        android:textStyle="bold"
        android:textSize="15sp"
        android:layout_gravity="center_horizontal"/>

    <Button
        android:id="@+id/delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/delete"
        android:textColor="#000066"
        android:textStyle="bold"
        android:textSize="15sp"
        android:layout_gravity="center_horizontal"/>
    <Button
        android:id="@+id/modify"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/modify"
        android:textColor="#000066"
        android:textStyle="bold"
        android:textSize="15sp"
        android:layout_gravity="center_horizontal"/>
    <Button
        android:id="@+id/listButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/list"
        android:textColor="#000066"
        android:textStyle="bold"
        android:textSize="15sp"
        android:layout_gravity="center_horizontal"/>
    <TextView
        android:id="@+id/count_records"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textSize="13sp"/>

</LinearLayout>

list_contact_info.xml

<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

   <ListView
    android:id="@android:id/list"
    android:layout_width="wrap_content"
    android:layout_height="467dp"> </ListView>

    <Button
        android:id="@+id/back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btnBack"
        android:textColor="#000066"
        android:textStyle="bold"
        android:textSize="15sp"
        android:layout_gravity="right|bottom"
        >
    </Button> 
     </FrameLayout>

Any help is appreciated.

Upvotes: 1

Views: 3463

Answers (1)

Richard R
Richard R

Reputation: 967

Oha, lot of different problems here. Let's start with your first question: If you want data to be sent from one activity to another, you should think about creating a class that can be instanciated. The instance (Java object) holds all data and can be accessed from different activities.

So if you are dealing with comments, you should create a comments class like this:

public class Comment implements Parcelable {

    private int commentId;
    private String commentTitle;
    private String commentText;

    // constructor
    public Comment() {

    } 

    // setters
    public void setCommentId(int id) {
        this.commentId = id;
    }

    public void setCommentTitle(String title) {
        this.commentTitle = title;
    }

    public void setCommentText(String text) {
        this.commentText = text;
    }

    // getters
    public int getCommentId() {
        return commentId;
    }

    public String getCommentTitle() {
        return commentId;
    }

    public String getCommentText() {
        return commentId;
    }

    // 99.9% of the time you can just ignore this
    public int describeContents() {
        return 0;
    }

    // write your object's data to the passed-in Parcel
    public void writeToParcel(Parcel out, int flags) {
        out.writeInt(commentId);
        out.writeString(commentTitle);
        out.writeString(commentText);
    }

    // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
    public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() {
        public Comment createFromParcel(Parcel in) {
            return new Comment(in);
        }

        public Comment[] newArray(int size) {
            return new Comment[size];
        }
    };

    // example constructor that takes a Parcel and gives you an object populated with it's values
    private Comment(Parcel in) {
        commentId = in.readInt();
        commentTitle = in.readString();
        commentText = in.readString();
    }

}

Then in your first acitivity you create a instance of the Comment class like this

Comment newComment = new Comment();

and fill it with whatever content you like:

newComment.setCommentTitle("My first comment");
newComment.setCommentText("Here goes my comment text...");

Now you can pass this Comment object to your next activity like this:

Intent i = new Intent(getActivity(), SecondActivity.class);
i.putExtra("newCommentKey", newComment); 
startActivity(i);

And in your second activity inside your onCreate() method you call:

Intent i = getIntent();
Comment myComment = (Comment ) i.getParcelableExtra("newCommentKey");

And thet can get all the content via the getters, e.g.:

String titleOfComment = myComment.getCommentTitle();

Good luck!

Upvotes: 1

Related Questions