0

I am a beginner in android development, I am trying to add an list item value from a different activity, i wrote a code where I am able to add an list item from within the activity, but not from outside the activity

TestDatabaseActivity.java

package com.laith.sql;

import java.util.List;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;

public class TestDatabaseActivity extends ListActivity {
private CommentsDataSource datasource;
public ArrayAdapter<Comment> adapter;
private EditText insert_et;
public Comment comment;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sqlite);

    insert_et =(EditText)findViewById(R.id.editText1);
    datasource = new CommentsDataSource(this);
    datasource.open();

    List<Comment> values = datasource.getAllComments();

    // Use the SimpleCursorAdapter to show the
    // elements in a ListView
    adapter = new ArrayAdapter<Comment>(this,
            android.R.layout.simple_list_item_1, values);
    setListAdapter(adapter);
}

// Will be called via the onClick attribute
// of the buttons in main.xml
public void onClick(View view) {
    ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) getListAdapter();
    comment = null;
    switch (view.getId()) {
    case R.id.add:
                    MySingleton mys = MySingleton.getInstance();

        String test = mys.getInstance().getMyStrings();
        addComment(test);
        break;
    case R.id.delete:
        if (getListAdapter().getCount() > 0) {
            comment = (Comment) getListAdapter().getItem(0);
            datasource.deleteComment(comment);
            adapter.remove(comment);
        }
        break;
    }
    adapter.notifyDataSetChanged();
}

@Override
protected void onResume() {
    datasource.open();
    super.onResume();
}

@Override
protected void onPause() {
    datasource.close();
    super.onPause();
}

/// method used to add a comment from a different directory 
public void addComment(String LastComment)
{
    // code here to be called by another activity

                ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>)getListAdapter();
        comment = datasource.createComment(LastComment);
        adapter.add(comment);
        adapter.notifyDataSetChanged();
           // am getting a null value for comment when I call the function from another activity


}

}

Test button in another activity

public Button.OnClickListener Test_button = new Button.OnClickListener() 
 {
     public void onClick(View v)
     {
         String verify_string="test";
         MySingleton mys = MySingleton.getInstance();
         mys.setMyStrings(verify_string);

         TestDatabaseActivity tdba = new TestDatabaseActivity();
         tdba.addComment(mys.getMyStrings());
     }
 };

Please help ! :)

Thank you

<--------------------------- working solution ---------------------------------------------> new class created

  public class ConnectToDB 
{
private CommentsDataSource datasource;

public void addCommentToDB(Context context, String new_comment)
{
    datasource = new CommentsDataSource(context);
    datasource.open();
    datasource.createComment(new_comment);  
}

}

onResume edited

protected void onResume() {
    datasource.open();
    values = datasource.getAllComments();
    adapter = new ArrayAdapter<Comment>(this,
            android.R.layout.simple_list_item_1, values);
    setListAdapter(adapter);
    adapter.notifyDataSetChanged();

    super.onResume();
}
Tunaki
  • 132,869
  • 46
  • 340
  • 423
HeWhoProtects
  • 477
  • 1
  • 10
  • 21
  • Why do you need to add to the `ListView` from another `Activity`? Why aren't you adding to the `ListView`'s data source? – Tyler Treat Apr 04 '12 at 21:27
  • Look basically what am trying to do is after i have scanned a QRCODE in another activity, I like the app to keep a history of it in a sqlite database and add an item to the listview activity when the scanned results is available. – HeWhoProtects Apr 04 '12 at 23:43
  • Very, VERY BAD METHODS!!! Full refactoring is needed here! Why do u need to create new activity without launching of it? – pleerock Apr 05 '12 at 00:04
  • wait but then that means I have to have addComment in a separate class? – HeWhoProtects Apr 05 '12 at 00:12
  • Yes! separate your application module from your activity. Move your addComment method to singleton class. But be sure if your datasource be available there – pleerock Apr 05 '12 at 00:18
  • I shall get on it tomorrow and refactor the application, thanks for the help, I am still a noob in android development, I shall post the final solution tomorrow :) good night – HeWhoProtects Apr 05 '12 at 00:38

2 Answers2

1

Should work like you do it in the onClick part:

public void addComment(String LastComment)
{
    ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) getListAdapter();
    comment = datasource.createComment(LastComment);
    adapter.add(comment);
    adapter.notifyChange();
}
zapl
  • 63,179
  • 10
  • 123
  • 154
  • I did this on the first go, while debugging am getting a null value for adapter. getListAdapter() might be getting the listAdapter related to the other activity, which does it's not exist in this case. – HeWhoProtects Apr 04 '12 at 21:47
  • That's happening if you call `addComment()` of your Activity before it is created. You need to find a way to pass the data at the right time and to the right instance of your Activity etc. Depends on what the sending part looks like. – zapl Apr 04 '12 at 21:53
0

Use android bundles, put extra values from your activity to another.

Or just create one singleton and use it instance from both of your activities. Create one field, for example listViewStrings, storage in there your strings, and get them from another activity (by accessing to single (singleton's) instance)

create a new class:

public class MySingleton {
// ----------------------------------------------------------------------
// Properties
// ----------------------------------------------------------------------

private String[] myStrings;

// ----------------------------------------------------------------------
// Public methods
// ----------------------------------------------------------------------

public void setMyStrings(String[] myStrings) {
          this.myStrings = myStrings;
}

public String[] getMyStrings() {
          return myStrings;
}

// ----------------------------------------------------------------------
// Singleton object
// ----------------------------------------------------------------------

private static MySingleton instance = new MySingleton();

/**
 * Close public access to the constructor
 */
private MySingleton() {
}

/**
 * Gets object's singleton instance
 * 
 * @return singleton instance
 */
public static MySingleton getInstance() {
    return instance;
}

}

And use in the first activity:

MySingleton mys = MySingleton.getInstance();
mys.setMyStrings(new String[] {"element1", "element2", "element3"});

And in the second:

MySingleton mys = MySingleton.getInstance();
String[] mySavedStrings = ys.getMyStrings();
pleerock
  • 18,322
  • 16
  • 103
  • 128
  • I am still getting a null value for comment where comment = datasource.createComment(LastComment); in addComment function – HeWhoProtects Apr 04 '12 at 23:49
  • update your code; where did you use singleton? add code of your second activity – pleerock Apr 04 '12 at 23:56
  • it will let me set the string from second activity and get the string using listActivity( manually using the add button inside list activity), however it will not let me add an new item from second activity and am not sure why – HeWhoProtects Apr 05 '12 at 00:10
  • @Pleerock You should use context. [link](http://stackoverflow.com/a/3827166/581365) – mutkan Jul 02 '12 at 14:04