如何比较两个arraylist元素?一个arraylist的元素出现在另一个arraylist或不是。 [英] How to compare two arraylist elements? Elements of one arraylist is present in another arraylist or not.

查看:64
本文介绍了如何比较两个arraylist元素?一个arraylist的元素出现在另一个arraylist或不是。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  package  com.example.productiveplus; 
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class FindNearByShop extends 活动{



BluetoothAdapter mBluetoothAdapter;
ArrayList< BluetoothDevice> DeviceList = new ArrayList< BluetoothDevice>();
ArrayList< String> DeviceListName = new ArrayList< String>();
ArrayAdapter< String> DeviceAdapter;


ArrayList< String> ShopIds = new ArrayList< String>();
ArrayList< String> ShopNames = new ArrayList< String>();
ArrayList< String> NewListName = new ArrayList< String>();


字符串 SOAP_ACTION = http://tempuri.org/GetShopList;
字符串 METHOD_NAME = GetShopList;

ListView lv;

BroadcastReceiver mReceiver = null;

ArrayList< Intent> intents = new ArrayList< Intent>();


@覆盖
受保护 void onCreate(Bundle savedInstanceState){
// TODO Auto生成的方法存根
super .onCreate(savedInstanceState);
setContentView(R.layout.findnearbyshop);
lv =(ListView)findViewById(R.id.lv);
new GetAllShop()。execute();

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled())
{
Intent enableBluetooth = new 意图(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0 );
}

DeviceList.clear();
DeviceListName.clear();

尝试
{

mReceiver = new BroadcastReceiver()
{
@ Override
public void onReceive(上下文上下文,意图意图)
{

String action = intent.getAction();

if (BluetoothDevice.ACTION_FOUND.equals(action))
{

BluetoothDevice device = intent .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

if (DeviceListName.indexOf(device.getName())== - 1
{
intents.add(intent);
DeviceList.add(device);
DeviceListName.add(device.getName()+ * + intent.getShortExtra( BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE));
DeviceAdapter.notifyDataSetChanged();

}

}
}
};

IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver,filter);
mBluetoothAdapter.startDiscovery();
/ * if(!mBluetoothAdapter.isDiscovering())
{
mBluetoothAdapter。 startDiscovery();
Log.d(开始,发现);
} * /



}
catch (例外e1)
{
Toast.makeText(FindNearByShop。 this ,e1.toString(),Toast.LENGTH_SHORT).show();
}




for int i = 0; i< ShopNames.size(); i ++)
{
if (DeviceListName.contains(ShopNames) .get(i)))
{
NewListName.add(DeviceListName.get(i));
Toast.makeText(FindNearByShop。 this ,NewListName.toString(),Toast.LENGTH_SHORT).show();

}
else
{
Toast.makeText(FindNearByShop。 this 条件错误,Toast.LENGTH_SHORT).show() ;

}
}

DeviceAdapter = new ArrayAdapter< String>(FindNearByShop。 this ,android.R.layout.simple_list_item_1,NewListName);
lv.setAdapter(DeviceAdapter);


}


class GetAllShop extends AsyncTask< Void,Void,String>
{
ProgressDialog pdia;
@覆盖
受保护 void onPreExecute(){
// TODO自动生成的方法存根
super .onPreExecute();
pdia = new ProgressDialog(FindNearByShop。 this );
pdia.setCanceledOnTouchOutside(false);
pdia.setMessage( Please Wait ......!);
pdia.show();
}

@覆盖
受保护 String doInBackground(Void ... params){
// TODO自动生成的方法存根
尝试
{
SoapObject request = new SoapObject(getString(R.string.namespace),METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(getString(R.string.url));
androidHttpTransport.call(SOAP_ACTION,envelope);
SoapPrimitive resultstr =(SoapPrimitive)envelope.getResponse();
return resultstr.toString();

}
catch (例外e)
{
Log.e( 错误,e.toString());
return 错误: + e.toString();
}


}
@覆盖
protected void onPostExecute( String result){
// TODO自动生成的方法存根
super .onPostExecute(结果);
尝试
{
字符串 rows [] = result.split ( );
ShopIds.clear();
ShopNames.clear();

for int i = 1; i< rows.length; i ++ )
{
Log.d( rows,rows [i] );
字符串 coloms [] = rows [i] .split( );
ShopIds.add(coloms [ 0 ]);
ShopNames.add(coloms [ 1 ]);
}
// ArrayAdapter< String> dataAdapter = new ArrayAdapter< String>(BrowseByShop.this,android.R.layout.simple_list_item_1,shopnames);
// lstShop.setAdapter(dataAdapter);

// Toast.makeText(FindNearByShop.this,ShopNames.toString( ),Toast.LENGTH_SHORT)。show();
}
catch (例外情况)
{
Toast.makeText(FindNearByShop。 this ,ex.getMessage(),Toast.LENGTH_SHORT).show();
}
pdia.dismiss();


}

}

}







这是获取附近蓝牙设备的代码。并在alistview中列出。 Asyntask类用于从数据库中获取shopname。



我想要做的就是我想要比较两个arraylist元素。



这里

1.DeviceListNameArrayList用于存储蓝牙设备按其蓝牙范围strignth排序的附近名称。



2.ShopNamesArrayList用于存储来自数据库的商店名称。



3.我使用arraylistNewListName来显示在列表视图中匹配BluetoothNames。





i想要比较DeviceListName和ShopNamesAraylist并且如果找到匹配则将其存储在NewListName。



但是当活动运行时,这段代码不会被执行..



  for  int  i = 0; i< ShopNames.size (); i ++)
{
if (DeviceListName .contains(ShopNames.get(i)))
{
NewListName.add(DeviceListName.get(i));
Toast.makeText(FindNearByShop。 this ,NewListName.toString(),Toast.LENGTH_SHORT).show();

}
else
{
Toast.makeText(FindNearByShop。 this 条件错误,Toast.LENGTH_SHORT).show() ;

}
}







这意味着没有Toast是出现这是if else阻止的一部分。



我尝试过:



我使用DeviceListName.contains(ShopNames.get(i)),因为我只是想找到蓝牙名称是否是商店名称的一部分。如果是,则在列表视图中显示。



请帮助我,因为我犯了任何错误。



提前感谢。

解决方案

建议:

Quote:



  for  int  i = 0; i< shopnames.size();> {
if (DeviceListName.contains(ShopNames.get(i)))
{
NewListName.add(DeviceListName.get(i));
Toast.makeText(FindNearByShop。 this ,NewListName.toString(),Toast.LENGTH_SHORT)。show();

}
else
{
Toast.makeText(FindNearByShop。 this < span class =code-string> Condition False,Toast.LENGTH_SHORT)。show();

}
}



将此代码设为函数n获得2个列表并返回第三个列表。它在测试时简化了一些事情。这样,您可以设置已知列表以查看附加内容。当我们看到函数所需的全部内容时,它有助于我们理解你的工作。



你应该学会尽快使用调试器。而不是猜测你的代码在做什么,现在是时候看到你的代码执行并确保它完成你期望的。



调试器允许你跟踪执行逐行检查变量,你会看到它有一个停止做你期望的点。

调试器 - 维基百科,免费的百科全书 [ ^ ]

掌握Visual Studio 2010中的调试 - A初学者指南 [ ^ ]

http: //docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html [ ^ ]

https://www.jetbrains.com/idea/help/debugging-your -first-java-application.html [ ^ ]



调试器将向您显示执行的内容,您应该很快了解原因。

 DeviceListName。 add (device.getName()+    * + intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE)); 

有问题。我将替换为上面一行代码。

DeviceListName。 add (device.getName());


package com.example.productiveplus;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class FindNearByShop extends Activity{

	

	BluetoothAdapter mBluetoothAdapter;
	ArrayList<BluetoothDevice> DeviceList = new ArrayList<BluetoothDevice>();
	ArrayList<String> DeviceListName = new ArrayList<String>();
	ArrayAdapter<String> DeviceAdapter;
	
	
	ArrayList<String> ShopIds = new ArrayList<String>();	
	ArrayList<String> ShopNames = new ArrayList<String>();
	ArrayList<String> NewListName = new ArrayList<String>();
	
	
	String SOAP_ACTION = "http://tempuri.org/GetShopList";
	String METHOD_NAME = "GetShopList";
	
	ListView lv;
	
	BroadcastReceiver mReceiver = null;
	
	ArrayList<Intent> intents = new ArrayList<Intent>();
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.findnearbyshop);
		lv = (ListView)findViewById(R.id.lv);
		new GetAllShop().execute();
		
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
	     if(!mBluetoothAdapter.isEnabled())
	     {
	         Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
	         startActivityForResult(enableBluetooth, 0);
	     }
	     
	     DeviceList.clear();
		 DeviceListName.clear();
		
		 try
			{
		 		
			    mReceiver = new BroadcastReceiver() 
		        { 
			    	@Override
		             public void onReceive(Context context, Intent intent) 
		             {
			    		 
		                 String action = intent.getAction(); 
		                 
		                 if (BluetoothDevice.ACTION_FOUND.equals(action))  
		                 {
		                 	
		                     BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
		                     
		                     if(DeviceListName.indexOf(device.getName()) == -1)
		                     {
		                    	 	intents.add(intent);
		                        	DeviceList.add(device);
		                        	DeviceListName.add(device.getName() + " * " + intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE));
		                        	DeviceAdapter.notifyDataSetChanged();
		                     	 	
		                     }
		                
		                 }
		             }    
		         };
		     
		         IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		         registerReceiver(mReceiver, filter);
		         mBluetoothAdapter.startDiscovery();
		         /*if(!mBluetoothAdapter.isDiscovering())
		         {
		        	 mBluetoothAdapter.startDiscovery();
		        	 Log.d("start","discovery");
		         }*/
		         
		   
			}
			catch(Exception e1)
			{
				Toast.makeText(FindNearByShop.this,e1.toString(), Toast.LENGTH_SHORT).show();
			}
		 
		 
		 

		 	for(int i=0 ; i<ShopNames.size(); i++ )
	   	 	{
	   		 if(DeviceListName.contains(ShopNames.get(i)))
	       	 {
	   			 NewListName.add(DeviceListName.get(i));
	   			Toast.makeText(FindNearByShop.this, NewListName.toString() ,Toast.LENGTH_SHORT).show();
	       	 		
	       	 }
	   		 else
	   		 {
	   			Toast.makeText(FindNearByShop.this, "Condition False" ,Toast.LENGTH_SHORT).show();
	       	 	 
	   		 }
	   	 	}
		
		     DeviceAdapter= new ArrayAdapter<String>(FindNearByShop.this, android.R.layout.simple_list_item_1, NewListName );
			 lv.setAdapter(DeviceAdapter);
		
	
	}
	
	
	class GetAllShop extends AsyncTask<Void,Void, String>
	{
		ProgressDialog pdia;
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			pdia = new ProgressDialog(FindNearByShop.this);
			pdia.setCanceledOnTouchOutside(false);
	        pdia.setMessage("Please Wait...!");
	        pdia.show(); 
		}

		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			try
			{
				SoapObject request = new SoapObject(getString(R.string.namespace), METHOD_NAME);
				SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    	        envelope.dotNet=true;
    	        envelope.setOutputSoapObject(request);
    	        HttpTransportSE androidHttpTransport = new HttpTransportSE(getString(R.string.url));
    	        androidHttpTransport.call(SOAP_ACTION, envelope);
    	        SoapPrimitive resultstr = (SoapPrimitive)envelope.getResponse();
			    return resultstr.toString();
				
			}
			catch(Exception e)
			{
				Log.e("Error ", e.toString());
				return "Error : " + e.toString();
			}

			
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			try
			{
				String rows[]= result.split(":");
				ShopIds.clear();
				ShopNames.clear();
				
				for(int i =1; i<rows.length;i++)
	    		{
					Log.d("rows",rows[i]);
	    			String coloms[]=rows[i].split("~");
	    			ShopIds.add(coloms[0]);
	    			ShopNames.add(coloms[1]);  			
	     		}
				 // ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(BrowseByShop.this, android.R.layout.simple_list_item_1,shopnames);
				 // lstShop.setAdapter(dataAdapter); 
				
				//Toast.makeText(FindNearByShop.this, ShopNames.toString() ,Toast.LENGTH_SHORT).show();
			}
			catch(Exception ex)
			{
				Toast.makeText(FindNearByShop.this, ex.getMessage() ,Toast.LENGTH_SHORT).show();	
			}
    		pdia.dismiss();
			
			
		}
		
	}
	
}




This is the code for fetching the nearby bluetooth device. and lists it in alistview. A Asyntask class is for fetching shopname from database.

all i wants to do is i wants to compare two arraylist elements.

here
1. "DeviceListName" ArrayList is used to store bluetooth device Names that is nearby in sorted order by its bluetooth range strignth.

2. "ShopNames" ArrayList is used to store shop names that comes from Database.

3. i used arraylist "NewListName" to display the matched BluetoothNames in list view.


i wants to compare "DeviceListName" and "ShopNames" Araylist and if match is found then store it on "NewListName".

but when the activity runs, this block of code doesn't executed..

for(int i=0 ; i<ShopNames.size(); i++ )
	   	 	{
	   		 if(DeviceListName.contains(ShopNames.get(i)))
	       	 {
	   			 NewListName.add(DeviceListName.get(i));
	   			Toast.makeText(FindNearByShop.this, NewListName.toString() ,Toast.LENGTH_SHORT).show();
	       	 		
	       	 }
	   		 else
	   		 {
	   			Toast.makeText(FindNearByShop.this, "Condition False" ,Toast.LENGTH_SHORT).show();
	       	 	 
	   		 }
	   	 	}




It means No Toast is appearing that is a part of if else block.

What I have tried:

I used "DeviceListName.contains(ShopNames.get(i))", as i just wants to find is the bluetooth name is a part of the shopname or not. if yes then display it in list view.

please help me as i made any mistakes.

thanks in advance.

解决方案

Advice:

Quote:


for(int i=0 ; i<shopnames.size();> 	{
	   		 if(DeviceListName.contains(ShopNames.get(i)))
	       	 {
	   			 NewListName.add(DeviceListName.get(i));
	   			Toast.makeText(FindNearByShop.this, NewListName.toString() ,Toast.LENGTH_SHORT).show();
	       	 		
	       	 }
	   		 else
	   		 {
	   			Toast.makeText(FindNearByShop.this, "Condition False" ,Toast.LENGTH_SHORT).show();
	       	 	 
	   		 }
	   	 	}


Make this code a function that get 2 lists and return a third list. it simplify things when it come to testing. This way you can set known lists to see what append. And it help us to understand what you do as we see all what is needed for the function.

You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]

the debugger will show you what is executed or not and you should understand the why pretty soon.


DeviceListName.add(device.getName() + " * " + intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE));

there was the problem. i replaced above line of code with this below one.

DeviceListName.add(device.getName());


这篇关于如何比较两个arraylist元素?一个arraylist的元素出现在另一个arraylist或不是。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆