将数据添加到现有列表视图

时间:2013-11-01 13:31:17

标签: android listview baseadapter

我使用以下代码创建了listview

public class homeScreen extends Activity{
    ArrayList<SingleRow> list;
    boolean flag = false;
    String space = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        final Context c = this;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.homescreen);

        //putting actual values in array
        list = new ArrayList<SingleRow>();
        Resources res = c.getResources();
        String[] titles = res.getStringArray(R.array.titles);
        int[] images = {R.drawable.error,R.drawable.ic_launcher,R.drawable.ic_launcher};

        //putting single row in arraylist
        for(int i = 0;i<3;i++){
            list.add(new SingleRow(titles[i], images[i]));
        }

        final ListView list1 = (ListView)findViewById(R.id.spacelist);
        final MySimpleAdapter adapter = new MySimpleAdapter(this,list);
        list1.setAdapter(adapter);
        space = getIntent().getStringExtra("spaceName");
        if(null! = space){
            adapter.addView(space);
        }

        list1.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
                Resources res = c.getResources();
                String[] titles = res.getStringArray(R.array.titles); 

                 if((titles[position]).equalsIgnoreCase("My Ideas")){
                      Intent i = new Intent(homeScreen.this, privateSpaceList.class);
                      startActivity(i);

                 } else if((titles[position]).equalsIgnoreCase("Create New Space")){
                     Intent i = new Intent(homeScreen.this, createNewSpace.class);
                     startActivity(i);
                 }
            }
        });

    }
}

行类:

class SingleRow{

    String title;
    int image;
    public SingleRow(String title,int image) {
        this.title = title;
        this.image = image;
    }
}

适配器:

 class MySimpleAdapter extends BaseAdapter{

    ArrayList<SingleRow> list;
    private Context context;
    public MySimpleAdapter(Context c,ArrayList<SingleRow> list) {
        this.context = c;
        this.list = list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int i) {
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    public void addView(String space) {
        int rows = this.getCount();
        list.add(rows, new SingleRow(space,R.drawable.ic_launcher));
        notifyDataSetChanged();
    }

    @Override
    public View getView(int i, View view, ViewGroup viewgroup) {
        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row = inflater.inflate(R.layout.single_row,viewgroup,false);
        TextView title = (TextView)row.findViewById(R.id.label);
        ImageView image = (ImageView)row.findViewById(R.id.imageView);
        SingleRow temp = list.get(i);
        title.setText(temp.title);
        image.setImageResource(temp.image);
        return row;
    }   
}

创建新空间的代码

public class createNewSpace extends Activity{
    Button add;
    TextView sname,pname;
    ListView plist;
    int success;
    Jparser jsonParser = new Jparser();
    JSONObject json;
    private ProgressDialog pDialog;
    ArrayList<String> usersList;
    ArrayList<String> spaceUsers;
    private static String url_users = "http://10.0.2.2/phpdata/getting_allusers.php";
    private static String url_create_space = "http://10.0.2.2/phpdata/create_space.php";
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_USERS = "users";
    private static final String TAG_UNAME = "firstName";

    // products JSONArray
    JSONArray users = null;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.createnewspace);

        sname=(TextView)findViewById(R.id.spaceName);
        pname=(TextView)findViewById(R.id.participents);
        plist=(ListView)findViewById(R.id.participantlist);
        add=(Button)findViewById(R.id.button1);
        // Hashmap for ListView
        usersList= new ArrayList<String>();
        spaceUsers=new ArrayList<String>();

        add.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                new getAllUsers().execute();
            }
        });
        plist.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                // TODO Auto-generated method stub
                String users[]=usersList.toArray(new String[usersList.size()]);
                Toast.makeText(getApplicationContext(), "User "+users[arg2]+ " added to space "+sname.getText(), Toast.LENGTH_SHORT).show();        
                spaceUsers.add(users[arg2]);
            }
        });
        // Loading users in Background Thread
    }
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.menuspace, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        return MenuChoice(item);
    }


    private boolean MenuChoice(MenuItem item)
    {
        switch(item.getItemId())
        {
            case R.id.create:
                new createSpace().execute();
                return true;

        }
        return false;
        }

    class createSpace extends AsyncTask<String, String, String> {

            /**
             * Before starting background thread Show Progress Dialog
             * */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }


        @Override
        protected String doInBackground(String... arg0) {
            // TODO Auto-generated method stub      
            for(int i=0;i<spaceUsers.size();i++)
            {   
                String sname1 = sname.getText().toString();
                String uname = spaceUsers.get(i);

                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("sname", sname1));
                params.add(new BasicNameValuePair("uname", uname));


            // getting JSON Object
            JSONObject json = jsonParser.makeHttpRequest(url_create_space,
                    "POST", params);
            Log.d("Create Response", json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    // successfully inserted user details
                    Intent is = new Intent(getApplicationContext(), homeScreen.class);
                    is.putExtra("spaceName", sname1);
                    startActivity(is);
                    // closing this screen
                    finish();
                } else {
                }
            } catch (JSONException e) {
                e.printStackTrace();
                }
            }
            return null;
            }

        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
        }
    }

    class getAllUsers extends AsyncTask<String, String, String> {


        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... arg0) {
            // TODO Auto-generated method stub
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON Object
            json = jsonParser.makeHttpRequest(url_users,"GET", params);
            // check log cat from response
            Log.d("Create Response", json.toString());

            // getting value of success tag
            try {
            success = json.getInt(TAG_SUCCESS);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;    
        }

      protected void onPostExecute(String file_url) {

          if (success == 1) {
                // Getting Array of users
                try{
                JSONArray users=json.getJSONArray(TAG_USERS);
                // looping through All Products
                for (int i = 0; i < users.length(); i++) {
                    Log.d("check", "success");
                    JSONObject c = users.getJSONObject(i);

                    // Storing each json item in variable
                    String name = c.getString(TAG_UNAME);
                    Log.d("name....",name);
                    // adding HashList to ArrayList
                    usersList.add(name);
                }
            } catch(JSONException e)
            {
                e.printStackTrace();
            }
          }
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                         plist.setAdapter(new ArrayAdapter<String>(createNewSpace.this,android.R.layout.simple_list_item_1,usersList)); 
                }
            });
    }
    }

}

现在我想将Item添加到此现有列表中。 我正在使用意图从另一个活动中获取数据。 现在有一个项目被添加。但下次被替换。 请帮忙。 提前谢谢。

2 个答案:

答案 0 :(得分:1)

您应该在适配器之外移动数据的创建:

list=new ArrayList<SingleRow>();
//putting actual values in array
Resources res=c.getResources();
String[] titles=res.getStringArray(R.array.titles);
int[] images={R.drawable.error,R.drawable.ic_launcher,R.drawable.ic_launcher};

//putting single row in arraylist
for(int i=0;i<3;i++){
    list.add(new SingleRow(titles[i], images[i]));
}

将list变量传递给适配器并在那里存储对它的引用。然后,您只需更新列表变量中的数据,然后在适配器上调用notifyDataSetChanged()

修改:您似乎希望存储space值,然后在HomeScreen活动中检索它们。如果我正确了解您的应用流程,那么createNewSpace类应该将空间存储在SharedPreferences中。然后在HomeScreen活动中,您应该从SharedPreferences中检索它们并显示它们。

答案 1 :(得分:0)

您可以向适配器添加数据并调用notifyDataSetChanged()。或者,您可以创建新的适配器和listView.setAdapter(adapter)该适配器。