无法在ListView android中查看项目

无法在ListView android中查看项目,android,android-layout,listview,broadcastreceiver,android-service,Android,Android Layout,Listview,Broadcastreceiver,Android Service,我想在列表视图中动态显示项目。在我的例子中,项目来自服务。服务广播该项,活动接收该项并填充该项的数组,我使用该数组填充列表视图 你能帮我知道我做错了什么吗 这是我的密码: public class MacaddressInfo extends AppCompatActivity { ArrayList<String> listofMac=new ArrayList<String>(); ArrayAdapter<String> adapter;

我想在列表视图中动态显示项目。在我的例子中,项目来自服务。服务广播该项,活动接收该项并填充该项的数组,我使用该数组填充列表视图

你能帮我知道我做错了什么吗

这是我的密码:

public class MacaddressInfo extends AppCompatActivity {
    ArrayList<String> listofMac=new ArrayList<String>();
    ArrayAdapter<String> adapter;
    ListView lv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_macaddress_info);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("intMAC"));
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            handleMessage(intent);
        }
    };

    private void handleMessage(Intent msg){
        if(msg != null) {
            Bundle data = msg.getExtras();
            String res = data.getString("result");
            Log.d("macaddinfo", "macaddress info is: " + res);

            listofMac.add(res);

            lv = (ListView)findViewById(R.id.lstMac);
            adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,listofMac);
            setListAdapter(adapter);

            Log.i("handlemessage", "Array count is: " + listofMac.size() + " ListView count is: " + lv.getCount());

        }
    }

    protected ListView getListView() {
        if (lv == null) {
            lv = (ListView) findViewById(R.id.lstMac);
        }
        return lv;
    }

    protected void setListAdapter(ListAdapter adapter) {
        getListView().setAdapter(adapter);
    }

}
调用服务的代码

public class MainActivity extends AppCompatActivity {
    ArrayList<String> listItems=new ArrayList<String>();
    ArrayAdapter<String> adapter;
    int clickCounter=0;
    ListView lv;
    EditText txtIP;
    Button btnAdd,btnUpdate,btnDel;
    int itemPos;

    APIService mservice;
    boolean mBound = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        txtIP = (EditText)findViewById(R.id.txtIP);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        lv = (ListView)findViewById(R.id.lstItems);
        adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,listItems);
        setListAdapter(adapter);

        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
                txtIP.setText(listItems.get(position));
                itemPos = position;
                Log.d("onlongclickpos", "long click pos is: " + position);
                return true;
            }
        });
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MainActivity.this,MacaddressInfo.class);
                startActivity(intent);
                mservice.AddMacAddress("TestMAC");
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        // Bind to LocalService
        Intent intent = new Intent(this, APIService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // Unbind from the service
        if (mBound) {
            unbindService(mConnection);
            mBound = false;
        }
    }

    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className,
                                       IBinder service) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            APIService.LocalBinder binder = (APIService.LocalBinder) service;
            mservice = binder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };
    public void addItems(View v) {
        txtIP = (EditText)findViewById(R.id.txtIP);
        String strItem = txtIP.getText().toString();
        listItems.add(strItem);
        adapter.notifyDataSetChanged();

    }
    public void updateItem(View v) {
        //txtIP = (EditText)findViewById(R.id.txtIP);
        String strItem = txtIP.getText().toString();
        //Toast.makeText(this,"pos is " + lv.getCheckedItemPosition(),Toast.LENGTH_LONG).show();
        int pos = itemPos;
        if(pos > -1) {
            adapter.remove(listItems.get(pos));
            adapter.insert(strItem, pos);
        }
        adapter.notifyDataSetChanged();

    }
    public void delItem(View v) {
        //int pos = lv.getCheckedItemPosition();
        int pos = itemPos;
        if(pos>-1)
        {
            adapter.remove(listItems.get(pos));
        }
        adapter.notifyDataSetChanged();
    }

    protected ListView getListView() {
        if (lv == null) {
            lv = (ListView) findViewById(R.id.lstItems);
        }
        return lv;
    }

    protected void setListAdapter(ListAdapter adapter) {
        getListView().setAdapter(adapter);
    }

    protected ListAdapter getListAdapter() {
        ListAdapter adapter = getListView().getAdapter();
        if (adapter instanceof HeaderViewListAdapter) {
            return ((HeaderViewListAdapter)adapter).getWrappedAdapter();
        } else {
            return adapter;
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
public类MainActivity扩展了AppCompatActivity{
ArrayList listItems=新的ArrayList();
阵列适配器;
int clickCounter=0;
ListView lv;
编辑文本txtIP;
按钮btnAdd、btnUpdate、btnDel;
int itemPos;
APIService mservice;
布尔mBound=false;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar Toolbar=(Toolbar)findViewById(R.id.Toolbar);
设置支持操作栏(工具栏);
txtIP=(EditText)findViewById(R.id.txtIP);
FloatingActionButton fab=(FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
Snackbar.make(查看“替换为您自己的操作”,Snackbar.LENGTH\u LONG)
.setAction(“Action”,null).show();
}
});
lv=(ListView)findViewById(R.id.lstItems);
adapter=newarrayadapter(这是android.R.layout.simple\u list\u item\u 1,listItems);
setListAdapter(适配器);
lv.setOnItemLongClickListener(新的AdapterView.OnItemLongClickListener(){
@凌驾
公共布尔值长单击(AdapterView父对象、视图v、整型位置、长id){
setText(listItems.get(position));
itemPos=位置;
Log.d(“onlongclickpos”,“longClickPOS为:+位置”);
返回true;
}
});
lv.setOnItemClickListener(新的AdapterView.OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父对象、视图、整型位置、长id){
Intent Intent=新Intent(MainActivity.this,MacaddressInfo.class);
星触觉(意向);
mservice.AddMacAddress(“TestMAC”);
}
});
}
@凌驾
受保护的void onStart(){
super.onStart();
//绑定到本地服务
Intent Intent=新Intent(这个,APIService.class);
bindService(intent、mConnection、Context.BIND\u AUTO\u CREATE);
}
@凌驾
受保护的void onStop(){
super.onStop();
//解除服务绑定
如果(mBound){
解除绑定服务(mConnection);
mBound=假;
}
}
专用ServiceConnection mConnection=新ServiceConnection(){
@凌驾
ServiceConnected上的公共无效(ComponentName类名称,
IBinder服务){
//我们已经绑定到LocalService,强制转换IBinder并获取LocalService实例
APIService.LocalBinder=(APIService.LocalBinder)服务;
mservice=binder.getService();
mBound=true;
}
@凌驾
ServiceDisconnected上的公共无效(组件名称arg0){
mBound=假;
}
};
公共无效附加项(视图五){
txtIP=(EditText)findViewById(R.id.txtIP);
String strItem=txtIP.getText().toString();
添加(strItem);
adapter.notifyDataSetChanged();
}
公共无效更新项(视图v){
//txtIP=(EditText)findViewById(R.id.txtIP);
String strItem=txtIP.getText().toString();
//Toast.makeText(这个“pos是”+lv.getCheckedItemPosition(),Toast.LENGTH\u LONG.show();
int pos=itemPos;
如果(位置>-1){
移除(listItems.get(pos));
适配器。插入件(条纹,位置);
}
adapter.notifyDataSetChanged();
}
公共作废文件(视图五){
//int pos=lv.getCheckedItemPosition();
int pos=itemPos;
如果(位置>-1)
{
移除(listItems.get(pos));
}
adapter.notifyDataSetChanged();
}
受保护的ListView getListView(){
if(lv==null){
lv=(ListView)findViewById(R.id.lstItems);
}
返回lv;
}
受保护的无效setListAdapter(ListAdapter适配器){
getListView().setAdapter(适配器);
}
受保护的ListAdapter getListAdapter(){
ListAdapter=getListView().getAdapter();
if(HeadServiceWListAdapter的适配器实例){
return((HeaderViewListAdapter)适配器).getWrappedAdapter();
}否则{
返回适配器;
}
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(右菜单菜单菜单主菜单);
返回true;
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
//处理操作栏项目单击此处。操作栏将
//自动处理Home/Up按钮上的点击,只要
//在AndroidManifest.xml中指定父活动时。
int id=item.getItemId();
//noinspection SimplifiableIf语句
if(id==R.id.action\u设置){
返回true;
}
返回super.onOptionsItemSelected(项目);
}
}

首先尝试在
onCreate
中分配和初始化视图和适配器,然后在
handleMessage
中,您可以添加到列表并调用
适配器。notifyDataSetChanged()
通知适配器更新列表视图

另外,在做了一些工作之后,制作
listOfMac
static最终解决了这个问题。我想以前在日志中发生的事情是你拿着的
public class APIService extends Service {
    private final IBinder mBinder = new LocalBinder();

    public class LocalBinder extends Binder {
        APIService getService() {
            // Return this instance of LocalService so clients can call public methods
            return APIService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    public void AddMacAddress(String str)
    {
        Log.d("APIService","message is: " + str);
        Intent intent = new Intent("intMAC");
        intent.putExtra("result",str);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
        Log.d("APIService", "intent broadcasted");
    }
}
public class MainActivity extends AppCompatActivity {
    ArrayList<String> listItems=new ArrayList<String>();
    ArrayAdapter<String> adapter;
    int clickCounter=0;
    ListView lv;
    EditText txtIP;
    Button btnAdd,btnUpdate,btnDel;
    int itemPos;

    APIService mservice;
    boolean mBound = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        txtIP = (EditText)findViewById(R.id.txtIP);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        lv = (ListView)findViewById(R.id.lstItems);
        adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,listItems);
        setListAdapter(adapter);

        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
                txtIP.setText(listItems.get(position));
                itemPos = position;
                Log.d("onlongclickpos", "long click pos is: " + position);
                return true;
            }
        });
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MainActivity.this,MacaddressInfo.class);
                startActivity(intent);
                mservice.AddMacAddress("TestMAC");
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        // Bind to LocalService
        Intent intent = new Intent(this, APIService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // Unbind from the service
        if (mBound) {
            unbindService(mConnection);
            mBound = false;
        }
    }

    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className,
                                       IBinder service) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            APIService.LocalBinder binder = (APIService.LocalBinder) service;
            mservice = binder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };
    public void addItems(View v) {
        txtIP = (EditText)findViewById(R.id.txtIP);
        String strItem = txtIP.getText().toString();
        listItems.add(strItem);
        adapter.notifyDataSetChanged();

    }
    public void updateItem(View v) {
        //txtIP = (EditText)findViewById(R.id.txtIP);
        String strItem = txtIP.getText().toString();
        //Toast.makeText(this,"pos is " + lv.getCheckedItemPosition(),Toast.LENGTH_LONG).show();
        int pos = itemPos;
        if(pos > -1) {
            adapter.remove(listItems.get(pos));
            adapter.insert(strItem, pos);
        }
        adapter.notifyDataSetChanged();

    }
    public void delItem(View v) {
        //int pos = lv.getCheckedItemPosition();
        int pos = itemPos;
        if(pos>-1)
        {
            adapter.remove(listItems.get(pos));
        }
        adapter.notifyDataSetChanged();
    }

    protected ListView getListView() {
        if (lv == null) {
            lv = (ListView) findViewById(R.id.lstItems);
        }
        return lv;
    }

    protected void setListAdapter(ListAdapter adapter) {
        getListView().setAdapter(adapter);
    }

    protected ListAdapter getListAdapter() {
        ListAdapter adapter = getListView().getAdapter();
        if (adapter instanceof HeaderViewListAdapter) {
            return ((HeaderViewListAdapter)adapter).getWrappedAdapter();
        } else {
            return adapter;
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
public class MacAddressActivity extends AppCompatActivity {
    // Static variables shared at class-level
    private static final ArrayList<String> listofMac = new ArrayList<String>();
    private static boolean mRegistered;

    private ArrayAdapter<String> adapter;
    private ListView lv;

    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            handleMessage(intent);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_macaddress_info);

        lv = (ListView) findViewById(R.id.lstMac);
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listofMac);
        lv.setAdapter(adapter);

        // fab code

    }

    @Override
    protected void onStart() {
        super.onStart();
        // prevent from registering again
        if (!mRegistered) {
            LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("intMAC"));
            mRegistered = true;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        // Should be unregistered, but uncommenting this makes it stop working
        /*
        if (mRegistered) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
            mRegistered = false;
        }
        */
    }

    private void handleMessage(Intent msg) {
        if (msg != null) {
            Bundle data = msg.getExtras();
            String res = data.getString("result");
            Log.d("macaddinfo", "macaddress info is: " + res);

            listofMac.add(res);
            adapter.notifyDataSetChanged();

            Log.i("handlemessage", "Array count is: " + listofMac.size() + " ListView count is: " + lv.getCount());

        }
    }
}