0

What I want to do is that every time the 'add' button is clicked, a new word is added to the class 'test' through a listview. What I have done so far would only add one word to a textview. But what I want is whenever the add button is clicked, a new word gets added to the listview. How do I do that? Here's my code:

public class MainActivity extends Activity {

private EditText mainedit1;
private TextView maintext1;
private Button   mainadd1;
private Button   maindone1;
@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    maindone1=(Button) findViewById(R.id.maindone);
    mainedit1=(EditText)findViewById(R.id.mainedit1);
    maintext1=(TextView)findViewById(R.id.maintext1);
    mainadd1=(Button)findViewById(R.id.mainadd);

    mainadd1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            String test1 = mainedit1.getText().toString();

            getSharedPreferences("my_prefs",      Context.MODE_PRIVATE).edit().putString("word", test1).commit();
            Toast.makeText(getApplicationContext(),"Word added",Toast.LENGTH_SHORT).show();
            mainedit1.setText(null);
        }
    });

 maindone1.setOnClickListener( new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         Intent intent = new Intent(MainActivity.this,test.class);
         startActivity(intent);


     }
 });
}
}

Test class:

public class test extends Activity {
TextView testtext;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fortest);
    testtext=(TextView)findViewById(R.id.testtext);


    getSharedPreferences("my_prefs", Context.MODE_PRIVATE).getString("word", null);
    String Word1 = getSharedPreferences("my_prefs",MODE_PRIVATE).getString("word",null).toString();
    testtext.setText(Word1);
}
}

Please if you know, show me how to by trying the code.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Metalloid66
  • 119
  • 10

2 Answers2

1

It looks like you are overriding content under key: "word" each time you click the button. You should get current value, update it with new word and then add.

Replace:

getSharedPreferences("my_prefs", Context.MODE_PRIVATE).edit().putString("word", test1).commit();

with:

String currentString = etSharedPreferences("my_prefs", Context.MODE_PRIVATE).getString("word", "");
getSharedPreferences("my_prefs", Context.MODE_PRIVATE).edit().putString("word", currentString + ", "+test1).commit();

and please move content from the second listener to first one and remove second one.

questioner
  • 2,283
  • 3
  • 26
  • 35
  • And how do i make a listview that receives these words ??? as you see it's adding the words written in the edittext to only one textview , thus only one word could be received or shown. I want them all to be shown. Edited the question. – Metalloid66 Apr 27 '15 at 20:31
  • The code you wrote adds all the words to only one textview , and that's not what i desire . What i want is that all the words get arranged in a listview , giving the users the ability to delete them . In your case , the user cant delete one words . She has to delete the whole thing . – Metalloid66 Apr 27 '15 at 20:41
  • Please help me through it . – Metalloid66 Apr 27 '15 at 20:50
0

You should use a fragment to hold the list view. And have your activity hold that fragment. This way you aren't trying to pass all that data from one activity to the next, you can just add it within the same activity where it's being shown.

So you'd end up with a MainActivity like:

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new WidgetFragment())
                .commit();
    }
}


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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
 }
}

Fragment Class:

public class WidgetFragment extends Fragment {

private ArrayAdapter<String> widgetAdapter;

public WidgetFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Add this line in order for this fragment to handle menu events.
    setHasOptionsMenu(true);



}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.widgetfragment, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_refresh) {
        FetchWidgetData widgetTask = new FetchWidgetData();
        widgetTask.execute("50131");
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // Create some dummy data for the ListView.  Here's a sample weekly forecast
    String[] data = {
            "Dummy Data",
            "Just an Example",
            "Delete at anytime",
            "Project 4",
            "Project 5",
            "Filler Data",
    };
    List<String> listData = new ArrayList<String>(Arrays.asList(data));

    // Now that we have some dummy forecast data, create an ArrayAdapter.
    // The ArrayAdapter will take data from a source (like our dummy forecast) and
    // use it to populate the ListView it's attached to.
    widgetAdapter =
            new ArrayAdapter<String>(
                    getActivity(), // The current context (this activity)
                    R.layout.list_item_widget, // The name of the layout ID.
                    R.id.list_item_widget_textview, // The ID of the textview to populate.
                    listData);

    View rootView = inflater.inflate(R.layout.fragment_main, container, false);

    // Get a reference to the ListView, and attach this adapter to it.
    ListView listView = (ListView) rootView.findViewById(R.id.listview_widget);
    listView.setAdapter(widgetAdapter);

    //!!!You can add your button click listener here. And put the following line inside it to add data to your list adapter!!!
    widgetAdapter.add("whatever whatever whatever"); //appends to end of list
    widgetAdapter.clear(); //to reset/clear the whole thing.
    widgetAdapter.remove(widgetAdapter.getItem(index); //removes the desired object. Note - remove takes object not an index.

    return rootView;
}

}

Edit: Key List View Steps.

1) Create a reference to the root view where your list view lives

View rootView = inflater.inflate(R.layout.fragment_main, container, false);

2) Create an Adapter to hold the data.

widgetAdapter =
            new ArrayAdapter<String>(
                    getActivity(), // The current context (this activity)
                    R.layout.list_item_widget, // The name of the layout ID.
                    R.id.list_item_widget_textview, // The ID of the textview to populate.
                    new ArrayList<String>);

3) Create a reference to the listview itself

ListView listView = (ListView) rootView.findViewById(R.id.listview_widget);

4) Set the listview adapter

ListView.setAdapter(widgetAdapter);

5) Add data to your adapter

widgetAdapter.add("Whatever");

Edit: example static method to add to your Main Activity class assuming you have the list adapter declared as a static class variable,

public static void addWordToList(String word){
   listAdapter.add(word); //LIST ADAPTER MUST BE STATIC OR THERE MAY BE NO INSTANCE OF IT
   }
}

then you can call this from inside your test activity by doing

MainActivity.addWordToList("Whatever word you want to add");
thurst0n
  • 155
  • 1
  • 1
  • 12
  • 1
    You can use this to add your own words with widgetAdapter.add("your own words here"). When the user adds words are they immediately taken to the next activity or are those words just saved for when/if they ever do go to the list view? If you want a listview then you'll have to do some variation of what I have above. i'll put the key listview steps in an edit above. – thurst0n Apr 27 '15 at 21:07
  • Ok so from what I can tell your options are to either use different data structure in your shared preferences such as http://stackoverflow.com/a/10815983/4808342 for an array or http://stackoverflow.com/a/3877242/4808342 for a hashmap and then once your in your test class you can easily iterate through those and setup your listAdapter, OR you can setup a public static method in your test class to add the words to the adapter that way, which I added in my last edit. I'm not a professional either ;-) – thurst0n Apr 27 '15 at 21:16
  • You need to create the XMLS or change the code according to what your XML names are. If you'd like you can look at my project code and see if that helps but unfortunately I don't have time to make it specific to your code :/ Here is my repo https://github.com/thurst0n/Archie Don't make everything public like I did. Keep it private with getters and setters. – thurst0n Apr 27 '15 at 21:26
  • I just updated my Stackoverflow profile with some contact information, feel free to email me and we''ll figure something out, maybe skype or something :D Finals next week though so I'll be busy until May 8th probably. – thurst0n Apr 27 '15 at 21:36