0

我使用以下代码创建了列表视图

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 添加到这个现有列表中。我正在使用意图从另一个活动中获取数据。现在添加了一个项目。但下一次将被替换。请帮忙。先感谢您。

4

2 回答 2

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]));
}

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

编辑:您似乎想存储这些space值,然后HomeScreen稍后在活动中检索它们。如果我正确理解了您的应用程序的流程,那么createNewSpace该类应该将空间存储在SharedPreferences中。然后在HomeScreen活动中,您应该从 SharedPreferences 中检索它们,并显示它们。

于 2013-11-01T13:39:21.993 回答
0

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

于 2013-11-01T13:44:02.123 回答