如何将Arraylist作为值传递给Hash映射,即传递给map.put(" param",Arraylist)。

时间:2016-04-02 06:46:03

标签: android arraylist hashmap

我必须将arraylist(包含三个值)传递给哈希映射。 在我的代码中,我有mChatList作为arraylist。我必须将此值传递给哈希映射。

HashMap<String, String> map = new HashMap<String, String>(); map.put("param1", "mChatList"); map.put("param2", "value2"); map.put("param3", "value3");

我收到错误&#34;错误的第二类型参数&#34;即我们必须使用字符串作为值。 我如何将arraylist作为值传递给hashmap。

这是我的代码..

package com.example.android.bluetoothchat;

import android.app.ActionBar;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.android.common.logger.Log;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;


public class BluetoothChatFragment extends Fragment {

    private static final String TAG = "BluetoothChatFragment";

    // Intent request codes
    private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
    private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
    private static final int REQUEST_ENABLE_BT = 3;

    // Layout Views
   private ListView mConversationView;

    private Button mSendButton;
    private String readMessage;

    private String mConnectedDeviceName = null;

    private ArrayAdapter<String> mConversationArrayAdapter;

    private StringBuffer mOutStringBuffer;

    private BluetoothAdapter mBluetoothAdapter = null;

    private BluetoothChatService mChatService = null;

    private ArrayList<ChatItem> mChatList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        // Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        mChatList = new ArrayList<ChatItem>();//this is my arraylist

        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) {
            FragmentActivity activity = getActivity();
            Toast.makeText(activity, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            activity.finish();
        }
    }


    @Override
    public void onStart() {
        super.onStart();

        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            // Otherwise, setup the chat session
        } else if (mChatService == null) {
            setupChat();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mChatService != null) {
            mChatService.stop();
        }
    }

    @Override
    public void onResume() {
        super.onResume();


        if (mChatService != null) {
            // Only if the state is STATE_NONE, do we know that we haven't started already
            if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
                // Start the Bluetooth chat services
                mChatService.start();
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_bluetooth_chat, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        mConversationView = (ListView) view.findViewById(R.id.in);
       mSendButton = (Button) view.findViewById(R.id.button_send);
    }


    private void setupChat() {
        Log.d(TAG, "setupChat()");

        // Initialize the array adapter for the conversation thread
        mConversationArrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.message);
       // textView = (TextView) viewfindViewById(R.id.textview);
        mConversationView.setAdapter(mConversationArrayAdapter);

        mSendButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Send a message using content of the edit text widget
                View view = getView();
                if (null != view) {

                HashMap<String, String> map = new HashMap<String, String>();
                map.put("param1", mChatList);
                map.put("param2", "value2");
                map.put("param3", "value3");

                new HTTPHelper(getActivity(), "http://oursite.com/awards.php", map, "Wait", HTTPHelper.TYPE_OKHTTP, new HTTPHelper.ResponseListener() {
                    @Override
                    public void handleResponse(String response) {
                        // TODO Auto-generated method stub
                        // Parse Response
                    }

                    @Override
                    public void handleError(Exception error) {
                        // TODO Auto-generated method stub
                        // Handle Exception
                    }
                });
            }
            }
        });

        mChatService = new BluetoothChatService(getActivity(), mHandler);


    }


    private void ensureDiscoverable() {
        if (mBluetoothAdapter.getScanMode() !=
                BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }
    }


    private void setStatus(int resId) {
        FragmentActivity activity = getActivity();
        if (null == activity) {
            return;
        }
        final ActionBar actionBar = activity.getActionBar();
        if (null == actionBar) {
            return;
        }
        actionBar.setSubtitle(resId);
    }


    private void setStatus(CharSequence subTitle) {
        FragmentActivity activity = getActivity();
        if (null == activity) {
            return;
        }
        final ActionBar actionBar = activity.getActionBar();
        if (null == actionBar) {
            return;
        }
        actionBar.setSubtitle(subTitle);
    }

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            FragmentActivity activity = getActivity();
            switch (msg.what) {
                case Constants.MESSAGE_STATE_CHANGE:
                    switch (msg.arg1) {
                        case BluetoothChatService.STATE_CONNECTED:
                            setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
                            mConversationArrayAdapter.clear();
                            break;
                        case BluetoothChatService.STATE_CONNECTING:
                            setStatus(R.string.title_connecting);
                            break;
                        case BluetoothChatService.STATE_LISTEN:
                        case BluetoothChatService.STATE_NONE:
                            setStatus(R.string.title_not_connected);
                            break;
                    }
                    break;

                case Constants.MESSAGE_READ:
                    byte[] readBuf = (byte[]) msg.obj;
                    // construct a string from the valid bytes in the buffer
                    readMessage = new String(readBuf, 0, msg.arg1);
                    mConversationArrayAdapter.add(mConnectedDeviceName + ":  " + readMessage);
                    mChatList.add(new ChatItem(readMessage, new Date().toString(), mConnectedDeviceName));/**this is my arraylist.this i have to use it in hash map.**/
                    break;
                case Constants.MESSAGE_DEVICE_NAME:
                    // save the connected device's name
                    mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME);
                    if (null != activity) {
                        Toast.makeText(activity, "Connected to "
                                + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                    }
                    break;
                case Constants.MESSAGE_TOAST:
                    if (null != activity) {
                        Toast.makeText(activity, msg.getData().getString(Constants.TOAST),
                                Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        }
    };

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CONNECT_DEVICE_SECURE:
                // When DeviceListActivity returns with a device to connect
                if (resultCode == Activity.RESULT_OK) {
                    connectDevice(data, true);
                }
                break;
            case REQUEST_CONNECT_DEVICE_INSECURE:
                // When DeviceListActivity returns with a device to connect
                if (resultCode == Activity.RESULT_OK) {
                    connectDevice(data, false);
                }
                break;
            case REQUEST_ENABLE_BT:
                // When the request to enable Bluetooth returns
                if (resultCode == Activity.RESULT_OK) {
                    // Bluetooth is now enabled, so set up a chat session
                    setupChat();
                } else {
                    // User did not enable Bluetooth or an error occurred
                    Log.d(TAG, "BT not enabled");
                    Toast.makeText(getActivity(), R.string.bt_not_enabled_leaving,
                            Toast.LENGTH_SHORT).show();
                    getActivity().finish();
                }
        }
    }


    private void connectDevice(Intent data, boolean secure) {
        // Get the device MAC address
        String address = data.getExtras()
                .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
        // Get the BluetoothDevice object
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        // Attempt to connect to the device
        mChatService.connect(device, secure);
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.secure_connect_scan: {
                // Launch the DeviceListActivity to see devices and do scan
                Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
                startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
                return true;
            }
            case R.id.insecure_connect_scan: {
                // Launch the DeviceListActivity to see devices and do scan
                Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
                startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
                return true;
            }
            case R.id.discoverable: {

                ensureDiscoverable();
                return true;
            }
        }
        return false;
    }

}

EDIT! :我有这样的HTTPHELPER类..

HTTPHelper.java

package com.example.android.bluetoothchat;

import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;


@SuppressWarnings("deprecation")
public class HTTPHelper {

    public static final int TYPE_NORMAL = 1;
    public static final int TYPE_VOLLEY = 2;
    public static final int TYPE_OKHTTP = 3;

    private ProgressDialog mDialog;
    private String progressMessage;

    private Context context;
    private String url;
    private Map<String, String> params;
    private int type;
    private ResponseListener responseCallback;
    private boolean isPOST;


    /**
     * This is the method used for POST request.
     * @param context - Current activity context.
     * @param url - URL of the target.
     * @param params - Parameters in the form of HashMap<Key, Value>.
     * @param progressMessage - Progress message to be shown.
     * @param type - Type could be TYPE_NORMAL or TYPE_VOLLEY or TYPE_NORMAL
     * @param responseCallback - Callback for response
     * 
     * 
     */
    public HTTPHelper(Context context, String url, Map<String, String> params, String progressMessage, int type, ResponseListener responseCallback){
        // TODO Auto-generated constructor stub
        this.context = context;
        this.url = url;
        this.progressMessage = progressMessage;
        this.params = params;
        this.type = type;
        this.responseCallback = responseCallback;
        isPOST = true;

        if(progressMessage!=null&&progressMessage.trim().length()>1){
            showProgress(this.progressMessage);
        }

        if(isNetworkAvailable(context)){
            initiateRequest();
        }else{
            dismissProgress();
            showToast("Internet is required");
        }
    }


    public HTTPHelper(Context context, String url, String progressMessage, int type, ResponseListener responseCallback){
        // TODO Auto-generated constructor stub
        this.context = context;
        this.url = url;
        this.progressMessage = progressMessage;
        this.type = type;
        this.responseCallback = responseCallback;
        isPOST = false;

        if(progressMessage!=null&&progressMessage.trim().length()>1){
            showProgress(this.progressMessage);
        }

        if(isNetworkAvailable(context)){
            initiateRequest();
        }else{
            dismissProgress();
            showToast("Internet is required");
        }
    }

    private void initiateRequest() {
        // TODO Auto-generated method stub
        switch (type) {
        case TYPE_NORMAL:
            requestNormal();
            break;

        case TYPE_VOLLEY: 
            if(isPOST)
                requestVolleyPost();
            else
                requestVolleyGet();
            break;

        case TYPE_OKHTTP:
            requestOKHttp();
            break;

        default:
            break;
        }
    }

    private void requestNormal(){
        // TODO Auto-generated method stub
        new AsyncTask<Void, Void, String>(){

            @Override
            protected String doInBackground(Void... pa) {
                // TODO Auto-generated method stub
                String response = "";
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                if(isPOST){
                    for (String key : params.keySet()) {
                        nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));
                    }
                }
                if(url.startsWith("https://"))
                    response = sendHttpsRequest(nameValuePairs);
                else
                    response = sendHttpRequest(nameValuePairs);
                return response;
            }

            @Override
            protected void onPostExecute(String result) {
                // TODO Auto-generated method stub
                dismissProgress();
                responseCallback.handleResponse(result);
            };

        }.execute();
    }

    private String sendHttpRequest(List<NameValuePair> nameValuePairs) {
        // TODO Auto-generated method stub
        String inputLine;
        String response = "";
        try{
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs);

            URL url1 = new URL(url);
            HttpURLConnection request = (HttpURLConnection) url1.openConnection();

            request.setUseCaches(false);
            request.setDoOutput(true);
            request.setDoInput(true);

            request.setRequestMethod("POST");
            OutputStream post = request.getOutputStream();
            entity.writeTo(post);
            post.flush();

            BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream()));
            while ((inputLine = in.readLine()) != null) {
                response += inputLine;
            }
            post.close();
            in.close();
        } catch (Exception e) {
            responseCallback.handleError(e);
        }

        return response;
    }

    private String sendHttpsRequest(List<NameValuePair> nameValuePairs){
        // TODO Auto-generated method stub
        String inputLine;
        String response = "";
        try{
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs);

            URL url1 = new URL(url);
            HttpsURLConnection request = (HttpsURLConnection) url1.openConnection();

            request.setUseCaches(false);
            request.setDoOutput(true);
            request.setDoInput(true);

            request.setRequestMethod("POST");
            OutputStream post = request.getOutputStream();
            entity.writeTo(post);
            post.flush();

            BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream()));
            while ((inputLine = in.readLine()) != null) {
                response += inputLine;
            }
            post.close();
            in.close();
        } catch (Exception e) {
            responseCallback.handleError(e);
        }

        return response;
    }

    private void requestVolleyGet() {
        // TODO Auto-generated method stub
        RequestQueue mRequestQueue = Volley.newRequestQueue(context);

        StringRequest mRequest = new StringRequest(Method.GET, url, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                // TODO Auto-generated method stub
                dismissProgress();
                responseCallback.handleResponse(response);
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                // TODO Auto-generated method stub
                dismissProgress();
                responseCallback.handleError(error);
            }
        });
        mRequest.setShouldCache(true);
        mRequestQueue.add(mRequest);
    }

    private void requestVolleyPost() {
        // TODO Auto-generated method stub
        RequestQueue mRequestQueue = Volley.newRequestQueue(context);

        StringRequest mRequest = new StringRequest(Method.POST, url, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                // TODO Auto-generated method stub
                dismissProgress();
                responseCallback.handleResponse(response);
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                // TODO Auto-generated method stub
                dismissProgress();
                responseCallback.handleError(error);
            }
        }){
            @Override
            public Map<String, String> getParams() throws AuthFailureError {
                // TODO Auto-generated method stub
                Log.e("Params", params.toString());
                return params;
            }
        };

        mRequest.setShouldCache(true);
        mRequestQueue.add(mRequest);
    }

    public void requestOKHttp(){

        new AsyncTask<Void, Void, String>() {

            @Override
            protected String doInBackground(Void... par) {
                // TODO Auto-generated method stub
                String result="";
                OkHttpClient client = new OkHttpClient();
                Request request = null;
                FormEncodingBuilder feb;
                if(isPOST){
                    feb = new FormEncodingBuilder();
                    for (String key : params.keySet()) {
                        feb.add(key, params.get(key));
                    }
                    request = new Request.Builder()
                    .url(url)
                    .post(feb.build())
                    .build();
                }else{
                    request = new Request.Builder()
                    .url(url)
                    .build();
                }

                try {
                    com.squareup.okhttp.Response response = client.newCall(request).execute();
                    result = response.body().string();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    responseCallback.handleError(e);
                }
                return result;
            }

            @Override
            protected void onPostExecute(String result) {
                // TODO Auto-generated method stub
                dismissProgress();
                responseCallback.handleResponse(result);
            }
        }.execute();
    }


    public void showProgress(String message){
        // TODO Auto-generated method stub
        mDialog = new ProgressDialog(context);
        mDialog.setMessage(message);
        mDialog.show();
    }

    public void showToast(String msg){
        // TODO Auto-generated method stub
        Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
    }

    public void dismissProgress(){
        // TODO Auto-generated method stub
        if(mDialog!=null&&mDialog.isShowing())
            mDialog.dismiss();
    }



    private static int TYPE_WIFI = 1;
    private static int TYPE_MOBILE = 2;
    private static int TYPE_NOT_CONNECTED = 0;

    public static boolean isNetworkAvailable(Context context) {

        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public static int getConnectivityStatus(Context context) {

        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (null != activeNetwork) {
            if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
                return TYPE_WIFI;

            if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
                return TYPE_MOBILE;
        } 
        return TYPE_NOT_CONNECTED;
    }

    public static String getConnectivityStatusString(Context context) {

        int conn = getConnectivityStatus(context);
        String status = null;
        if (conn == TYPE_WIFI) {
            status = "Wifi enabled";
        } else if (conn == TYPE_MOBILE) {
            status = "Mobile data enabled";
        } else if (conn == TYPE_NOT_CONNECTED) {
            status = "Not connected to Internet";
        }
        return status;
    }

    public static String mNewtWorkState = "No network available";
    public static String mTimeOutConnection = "Connection timed out Please Try again later";

    public interface ResponseListener{

        void handleResponse(String result);

        void handleError(Exception error);
    }

}

1 个答案:

答案 0 :(得分:0)

你应该有map

Map<String, ArrayList<ChatItem>> map = new HashMap<>();
map.put("param", arrayList);