将一个列表视图中的数据动态添加到另一个列表视图中

Dynamic adding data in one listview based into another listview

我正在尝试根据来自另一个 lisview1 的 selected 项目将数据添加到 listview2 中,但是不知何故每次我 select 来自 listview1 的一个项目我的应用程序都会崩溃,有人可以吗帮帮我?

Java CLASS

    package com.petridis.medral;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class Equipe extends ListActivity {

    // Progress Dialog
    private ProgressDialog pDialog;

    // php read comments script

    // localhost :
    // testing on your device
    // put your local ip instead, on windows, run CMD > ipconfig
    // or in mac's terminal type ifconfig and look for the ip under en0 or en1
    // private static final String READ_COMMENTS_URL =
    // "http://xxx.xxx.x.x:1234/webservice/comments.php";

    // testing on Emulator:
    private static final String READ_COMMENTS_URL = "http://192.168.0.14:1234/webservice/comments.php";

    // testing from a real server:
    // private static final String READ_COMMENTS_URL =
    // "http://www.mybringback.com/webservice/comments.php";

    // JSON IDS:
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_NOME = "funcionarios";
    private static final String TAG_TITLE = "Funcionario";


    //Declarar search
    EditText inputSearch;

    // Array de JSON para buscar dados
    private JSONArray mComments = null;

    // manages all of our comments in a list.
    private ArrayList<HashMap<String, String>> mCommentList;

    // Cria um array list

    //Cria um array adapter
    ArrayAdapter<String> adapter;
    ArrayList listaSelecionada = new ArrayList();;
    private StableArrayAdapter adapterZ;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.team_build);
        // Crio uma listview e vinculo com o XML        
        ListView listview = (ListView) findViewById(R.id.list2);        
        String[] values = new String[] {};
        ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < values.length; ++i) {
          list.add(values[i]);
        }

        StableArrayAdapter adapterZ = new StableArrayAdapter(this, R.layout.single_post, list);
        listview.setAdapter(adapterZ);
        }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        // loading the comments via AsyncTask
        new LoadComments().execute();
    }

    public void addComment(View v) {
        Intent i = new Intent(Equipe.this, Menu.class);
        startActivity(i);
    }

    public void updateJSONdata() {

        mCommentList = new ArrayList<HashMap<String, String>>();

        JSONParser jParser = new JSONParser();

        JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);

        try {

            mComments = json.getJSONArray(TAG_NOME);

            // Looping para pegar resultados
            for (int i = 0; i < mComments.length(); i++) {
                JSONObject c = mComments.getJSONObject(i);

                // Pegar o conteudo do tag
                String title = c.getString(TAG_TITLE);

                // Criar o HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                map.put(TAG_NOME, title);

                // adding HashList to ArrayList
                mCommentList.add(map);

                // annndddd, our JSON data is up to date same with our array
                // list
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * Inserts the parsed data into the listview.
     */
    private void updateList() {
        // For a ListActivity we need to set the List Adapter, and in order to
        // do
        // that, we need to create a ListAdapter. This SimpleAdapter,
        // will utilize our updated Hashmapped ArrayList,
        // use our single_post xml template for each item in our list,
        // and place the appropriate info from the list to the
        // correct GUI id. Order is important here.
        ListAdapter adapter = new SimpleAdapter(this, mCommentList,
                R.layout.single_post, new String[] { TAG_NOME },
                new int[] { R.id.title });


        // I shouldn't have to comment on this one:
        setListAdapter(adapter);

        // Optional: when the user clicks a list item we
        // could do something. However, we will choose
        // to do nothing...
        ListView lv = getListView();
        inputSearch = (EditText) findViewById(R.id.inputSearch);
        inputSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2,
                    int arg3) {
                // When user changed the Text
                Equipe.this.adapter.getFilter().filter(cs);
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                    int arg2, int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub

            }

        });
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                HashMap item = mCommentList.get(position);
                Toast.makeText(Equipe.this, item + "selected", Toast.LENGTH_LONG).show();
                listaSelecionada.add("Teste");
                adapterZ.notifyDataSetChanged();


            }
        });
    }

    private class StableArrayAdapter extends ArrayAdapter<String> {

        HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();

        public StableArrayAdapter(Context context, int textViewResourceId,
            List<String> objects) {
          super(context, textViewResourceId, objects);
          for (int i = 0; i < objects.size(); ++i) {
            mIdMap.put(objects.get(i), i);
          }
        }

        @Override
        public long getItemId(int position) {
          String item = getItem(position);
          return mIdMap.get(item);
        }

        @Override
        public boolean hasStableIds() {
          return true;
        }

      }

    public class LoadComments extends AsyncTask<Void, Void, Boolean> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Equipe.this);
            pDialog.setMessage("Loading Comments...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected Boolean doInBackground(Void... arg0) {
            // we will develop this method in version 2
            updateJSONdata();
            return null;

        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            pDialog.dismiss();
            // we will develop this method in version 2
            updateList();
        }
    }

}

team_build.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:weightSum="100"
        android:background="#fff" >

        <LinearLayout
            android:id="@+id/top_layover"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:background="@drawable/blue_gradient"
            android:orientation="horizontal" >

            <EditText android:id="@+id/inputSearch"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="Procurar funcionarios"
            android:inputType="textVisiblePassword"/>

        </LinearLayout>

        <LinearLayout
            android:id="@+id/ListView_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/bottom_layover"
            android:layout_below="@+id/top_layover"
            android:weightSum="1" >

                <RelativeLayout
                android:id="@+id/rl_ListView1"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="0.5" >

                <ListView
                    android:id="@android:id/list"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="#fff"
                    android:divider="@android:color/transparent"
                    android:scrollbars="none" />
                </RelativeLayout>
                <RelativeLayout
                android:id="@+id/rl_ListView2"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:background="#333"
                android:layout_weight="0.5" >

                <ListView
                    android:id="@+id/list2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="#fff"
                    android:divider="@android:color/transparent"
                    android:layout_toRightOf="@+id/list2"
                    android:scrollbars="none" />
                </RelativeLayout>
                </LinearLayout>        


        <LinearLayout
            android:id="@+id/bottom_layover"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:background="@drawable/blue_gradient"
            android:orientation="horizontal"
            android:weightSum="2" >

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:orientation="vertical" >
            </LinearLayout>

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:orientation="vertical" >

                <Button
                    android:id="@+id/post_comment"
                    style="@style/WhiteText"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="right"
                    android:background="@drawable/black_button"
                    android:onClick="addComment"
                    android:text="@string/post_comment" />
            </LinearLayout>
        </LinearLayout>
            <LinearLayout
                android:id="@+id/content"
                android:layout_width="match_parent"
                android:layout_height="match_parent" >
            </LinearLayout>

    </RelativeLayout>

single_post.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:weightSum="100"
    android:background="#f0f0f0"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:background="@drawable/post_border_style"
        android:orientation="vertical" >

        <LinearLayout
            android:id="@+id/box"
            android:layout_width="match_parent"
            android:layout_weight="50"
            android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:background="@drawable/post_background_style"
            android:orientation="horizontal" >

            <LinearLayout
                android:id="@+id/box"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="2dp"
                android:orientation="vertical"
                android:padding="5dp" >

                <TextView
                    android:id="@+id/title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="bottom"
                    android:paddingBottom="2dip"
                    android:paddingLeft="5dp"
                    android:paddingTop="6dip"
                    android:textColor="#333"
                    android:textSize="16sp"
                    android:textStyle="bold" />


            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.petridis.medral"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.petridis.medral.Login"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.petridis.medral.Menu"
            android:label="@string/app_name" >
        </activity>
        <activity
            android:name="com.petridis.medral.Equipe"
            android:label="@string/app_name"
            android:windowSoftInputMode="stateHidden" >
        </activity>
    </application>

</manifest>

LOGCAT

12-21 19:34:51.627: D/ProgressBar(1453): setProgress = 0
12-21 19:34:51.627: D/ProgressBar(1453): setProgress = 0, fromUser = false
12-21 19:34:51.627: D/ProgressBar(1453): mProgress = 0mIndeterminate = false, mMin = 0, mMax = 10000
12-21 19:34:51.688: D/request!(1453): starting
12-21 19:34:51.698: D/ProgressBar(1453): updateDrawableBounds: left = 0
12-21 19:34:51.698: D/ProgressBar(1453): updateDrawableBounds: top = 0
12-21 19:34:51.698: D/ProgressBar(1453): updateDrawableBounds: right = 72
12-21 19:34:51.698: D/ProgressBar(1453): updateDrawableBounds: bottom = 72
12-21 19:34:51.908: D/Login attempt(1453): {"message":"Login successful!","success":1}
12-21 19:34:51.908: D/Login Successful!(1453): {"message":"Login successful!","success":1}
12-21 19:34:53.550: D/AbsListView(1453): Get MotionRecognitionManager
12-21 19:34:53.560: D/AbsListView(1453): Get MotionRecognitionManager
12-21 19:34:53.570: D/ProgressBar(1453): setProgress = 0
12-21 19:34:53.570: D/ProgressBar(1453): setProgress = 0, fromUser = false
12-21 19:34:53.570: D/ProgressBar(1453): mProgress = 0mIndeterminate = false, mMin = 0, mMax = 10000
12-21 19:34:53.600: D/AbsListView(1453): onVisibilityChanged() is called, visibility : 4
12-21 19:34:53.600: D/AbsListView(1453): unregisterIRListener() is called 
12-21 19:34:53.600: D/AbsListView(1453): onVisibilityChanged() is called, visibility : 4
12-21 19:34:53.600: D/AbsListView(1453): unregisterIRListener() is called 
12-21 19:34:53.600: D/AbsListView(1453): onVisibilityChanged() is called, visibility : 0
12-21 19:34:53.600: D/AbsListView(1453): unregisterIRListener() is called 
12-21 19:34:53.600: D/AbsListView(1453): onVisibilityChanged() is called, visibility : 0
12-21 19:34:53.600: D/AbsListView(1453): unregisterIRListener() is called 
12-21 19:34:53.630: D/ProgressBar(1453): updateDrawableBounds: left = 0
12-21 19:34:53.630: D/ProgressBar(1453): updateDrawableBounds: top = 0
12-21 19:34:53.630: D/ProgressBar(1453): updateDrawableBounds: right = 72
12-21 19:34:53.630: D/ProgressBar(1453): updateDrawableBounds: bottom = 72
12-21 19:34:53.660: D/AbsListView(1453): unregisterIRListener() is called 
12-21 19:34:53.660: D/AbsListView(1453): unregisterIRListener() is called 
12-21 19:34:53.820: D/AbsListView(1453): unregisterIRListener() is called 
12-21 19:34:53.820: D/AbsListView(1453): unregisterIRListener() is called 
12-21 19:34:53.870: D/AbsListView(1453): unregisterIRListener() is called 
12-21 19:34:53.870: D/AbsListView(1453): unregisterIRListener() is called 
12-21 19:34:53.880: E/ViewRootImpl(1453): sendUserActionEvent() mView == null
12-21 19:34:55.111: D/AndroidRuntime(1453): Shutting down VM
12-21 19:34:55.111: W/dalvikvm(1453): threadid=1: thread exiting with uncaught exception (group=0x41d35ac8)
12-21 19:34:55.121: E/AndroidRuntime(1453): FATAL EXCEPTION: main
12-21 19:34:55.121: E/AndroidRuntime(1453): java.lang.NullPointerException
12-21 19:34:55.121: E/AndroidRuntime(1453):     at com.petridis.medral.Equipe.onItemClick(Equipe.java:199)
12-21 19:34:55.121: E/AndroidRuntime(1453):     at android.widget.AdapterView.performItemClick(AdapterView.java:301)
12-21 19:34:55.121: E/AndroidRuntime(1453):     at android.widget.AbsListView.performItemClick(AbsListView.java:1525)
12-21 19:34:55.121: E/AndroidRuntime(1453):     at android.widget.AbsListView$PerformClick.run(AbsListView.java:3297)
12-21 19:34:55.121: E/AndroidRuntime(1453):     at android.widget.AbsListView.run(AbsListView.java:4348)
12-21 19:34:55.121: E/AndroidRuntime(1453):     at android.os.Handler.handleCallback(Handler.java:725)
12-21 19:34:55.121: E/AndroidRuntime(1453):     at android.os.Handler.dispatchMessage(Handler.java:92)
12-21 19:34:55.121: E/AndroidRuntime(1453):     at android.os.Looper.loop(Looper.java:137)
12-21 19:34:55.121: E/AndroidRuntime(1453):     at android.app.ActivityThread.main(ActivityThread.java:5306)
12-21 19:34:55.121: E/AndroidRuntime(1453):     at java.lang.reflect.Method.invokeNative(Native Method)
12-21 19:34:55.121: E/AndroidRuntime(1453):     at java.lang.reflect.Method.invoke(Method.java:511)
12-21 19:34:55.121: E/AndroidRuntime(1453):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
12-21 19:34:55.121: E/AndroidRuntime(1453):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
12-21 19:34:55.121: E/AndroidRuntime(1453):     at dalvik.system.NativeStart.main(Native Method)

您声明了您的适配器两次。一个在 class 级别,另一个在 onCreate 中的功能级别。当您尝试在列表项上访问它时,单击它会尝试访问在 class 级别声明的适配器,该适配器从未实例化,因此返回 null。

改变

StableArrayAdapter adapterZ = new StableArrayAdapter(this, R.layout.single_post, list);

adapterZ = new StableArrayAdapter(this, R.layout.single_post, list);