两个活动之间的共享数组列表不起作用

Posted

技术标签:

【中文标题】两个活动之间的共享数组列表不起作用【英文标题】:Shared arraylist between two activity doesn't work 【发布时间】:2018-12-29 03:36:33 【问题描述】:

我有一个问题,当我在复选框中选择我的项目时(因此它被选中),数组已填充,但是当我单击“完成”时,称为新活动 GenreViewActivity,它调用了获取数组列表的方法之前的activity,但是它的ListView,布局是空的。我错了什么?

AccountActivity GenreViewActivity

AccountActivity.java:

package com.example.msnma.movienotifier;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class AccountActivity extends AppCompatActivity 

    private static ArrayList <String> itemsChkStr = new ArrayList<String();

public class Item 

        boolean checked;
        Drawable ItemDrawable;
        String ItemString;
        Item(/*Drawable drawable,*/ String t, boolean b)
        
            //ItemDrawable = drawable;
            ItemString = t;
            checked = b;
        

        public boolean isChecked()
        
            return checked;
        
    

    static class ViewHolder 
    
        CheckBox checkBox;
        ImageView icon;
        TextView text;
    

    public class ItemsListAdapter extends BaseAdapter 
    

        private Context context;
        private List<Item> list;

        ItemsListAdapter(Context c, List<Item> l) 
        
            context = c;
            list = l;
        

        @Override
        public int getCount() 
        
            return list.size();
        

        @Override
        public Object getItem(int position) 
        
            return list.get(position);
        

        @Override
        public long getItemId(int position) 
        
            return position;
        

        public boolean isChecked(int position) 
        
            return list.get(position).checked;
        

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) 
        
            View rowView = convertView;

            // reuse views
            ViewHolder viewHolder = new ViewHolder();
            if (rowView == null) 
                LayoutInflater inflater = ((Activity) 
                 context).getLayoutInflater();
                rowView = inflater.inflate(R.layout.row, null);

                viewHolder.checkBox = (CheckBox) 
                 rowView.findViewById(R.id.rowCheckBox);
                //viewHolder.icon = (ImageView) 
                   rowView.findViewById(R.id.rowImageView);
                viewHolder.text = (TextView) 
                   rowView.findViewById(R.id.rowTextView);
                rowView.setTag(viewHolder);
                 
                else 
                
                 viewHolder = (ViewHolder) rowView.getTag();
                

            //viewHolder.icon.setImageDrawable(list.get(position).ItemDrawable);
            viewHolder.checkBox.setChecked(list.get(position).checked);

            final String itemStr = list.get(position).ItemString;
            viewHolder.text.setText(itemStr);

            viewHolder.checkBox.setTag(position);

            /*
            viewHolder.checkBox.setOnCheckedChangeListener(
                    new CompoundButton.OnCheckedChangeListener() 
                @Override
                public void onCheckedChanged(CompoundButton 
                     compoundButton, boolean b) 
                
                    list.get(position).checked = b;

                    Toast.makeText(getApplicationContext(),
                            itemStr + "onCheckedChanged\nchecked: " + b,
                            Toast.LENGTH_LONG).show();
                
            );
            */

            viewHolder.checkBox.setOnClickListener(new 
                  View.OnClickListener() 
            
                @Override
                public void onClick(View view) 
                    boolean newState = !list.get(position).isChecked();
                    list.get(position).checked = newState;
                    Toast.makeText(getApplicationContext(),
                            itemStr + "setOnClickListener\nchecked: " + newState,
                            Toast.LENGTH_LONG).show();
                
            );

            viewHolder.checkBox.setChecked(isChecked(position));

            return rowView;
        
    

    Button btnLookup;
    Button btnDone;
    List<Item> items;
    ListView listView;
    ItemsListAdapter myItemsListAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account);
        listView = (ListView)findViewById(R.id.listview);
        btnLookup = (Button)findViewById(R.id.lookup);
        btnDone = (Button) findViewById(R.id.done);

        initItems();
        myItemsListAdapter = new ItemsListAdapter(this, items);
        listView.setAdapter(myItemsListAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener()

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) 
                Toast.makeText(AccountActivity.this,
                        ((Item)(parent.getItemAtPosition(position))).ItemString,
                        Toast.LENGTH_LONG).show();
            );

        //Arraylist di tipo stringa con elementi checked

        for (int i=0; i<items.size(); i++)
            if (items.get(i).isChecked())
                //str += i + "\n";
                itemsChkStr.add(items.get(i).ItemString);
            
        

        btnLookup.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                String str = "Check items:\n";

                for (int i=0; i<items.size(); i++)
                    if (items.get(i).isChecked())
                        //str += i + "\n";
                        str += items.get(i).ItemString;
                    
                

                /*
                int cnt = myItemsListAdapter.getCount();
                for (int i=0; i<cnt; i++)
                    if(myItemsListAdapter.isChecked(i))
                        str += i + "\n";
                    
                
                */

                Toast.makeText(AccountActivity.this,
                        str,
                        Toast.LENGTH_LONG).show();

            
        );
    

    private void initItems()
        items = new ArrayList<Item>();

        TypedArray arrayDrawable = getResources().obtainTypedArray(R.array.resicon);
        TypedArray arrayText = getResources().obtainTypedArray(R.array.restext);

        for(int i=0; i<arrayDrawable.length(); i++)
            //Drawable d = arrayDrawable.getDrawable(i);
            String s = arrayText.getString(i);
            boolean b = false;
            Item item = new Item(/*d,*/ s, b);
            items.add(item);
        

        arrayDrawable.recycle();
        arrayText.recycle();
    

    public void pressDoneButton(View view)
    
        //itemsChecks();
        Intent intent = new Intent(this, GenreViewActivity.class);
        //EditText editText = (EditText) findViewById(R.id.editText);
        //String message = editText.getText().toString();
        //intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent);
    

    /*public ArrayList <String> itemsChecks()
    
        ArrayList <String> arrGenre = new ArrayList<String>();
        for (int i=0; i<items.size(); i++)
            if (items.get(i).isChecked())
                arrGenre.add(items.get(i).toString());
            
        
        viewArray(arrGenre);

    */

    public static ArrayList <String> getSelectedString()
        return itemsChkStr;
    


    /*@Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account);
        Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(myToolbar);
        // Get a support ActionBar corresponding to this toolbar
        ActionBar ab = getSupportActionBar();

        // Enable the Up button
        ab.setDisplayHomeAsUpEnabled(true);

    

    public boolean onCreateOptionsMenu(Menu menu)
    
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_second, 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 void pressAccountButton(MenuItem item) 
        Intent intent = new Intent(this, AccountActivity.class);
        //EditText editText = (EditText) findViewById(R.id.editText);
        //String message = editText.getText().toString();
        //intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent);
    */

GenreViewActivity:

package com.example.msnma.movienotifier;


import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class GenreViewActivity extends AppCompatActivity 

    //AccountActivity aa = new AccountActivity();

    private ListView lv;
    @Override
    public void onCreate(Bundle saveInstanceState) 
        super.onCreate(saveInstanceState);
        setContentView(R.layout.activity_genre_view);
        lv = findViewById(R.id.listview);

        // Instanciating an array list (you don't need to do this,
        // you already have yours).
        ArrayList<String> your_array_list; //= new ArrayList<String>();
        /*your_array_list.add("foo");
        your_array_list.add("bar");*/

        your_array_list = AccountActivity.getSelectedString();





        // This is the array adapter, it takes the context of the activity as a
        // first parameter, the type of list view as a second parameter and your
        // array as a third parameter.
        ArrayAdapter<String> arrayAdapter1 = new ArrayAdapter<String>(
                this,
                android.R.layout.simple_list_item_1,
                your_array_list);

        lv.setAdapter(arrayAdapter1);


    


    /*@Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_genre_view);
    */

activity_genre_view.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_
    android:orientation="vertical"
    tools:context=".GenreViewActivity">

 <TextView
     android:layout_
     android:layout_
     android:layout_gravity="center_horizontal"
     android:text="Genre"
     android:textStyle="bold" />
 <!--android:autoLink="web"-->

 <ListView
     android:id="@+id/listview"
     android:layout_
     android:layout_ />

</LinearLayout>

【问题讨论】:

你能清理一下你的代码吗?删除注释掉的代码 @user47845 你需要在checkBox.setOnClickListener Method下面添加这行itemsChkStr.add(list.get(position).ItemString); 【参考方案1】:

使用putStringArrayListExtra来传递ArrayList。

public void pressDoneButton(View view)
    
        //itemsChecks();
        Intent intent = new Intent(this, GenreViewActivity.class);
        intent.putStringArrayListExtra("your_list",itemsChkStr);
        startActivity(intent);
    

并使用intent.getStringArrayListExtra("your_list"); 获取ArrayList。

在您的 GenreViewActivity...

if(getIntent()!=null)
your_array_list = getIntent().getStringArrayListExtra("your_list");

【讨论】:

真的是:)【参考方案2】:

当然会是空的。您仅在开始之前填充静态数组 itemsChkStr,然后您尝试进行检查。您需要在每次检查操作后更新您的静态检查列表。

【讨论】:

以上是关于两个活动之间的共享数组列表不起作用的主要内容,如果未能解决你的问题,请参考以下文章

两个实体之间的共享主键不起作用

我的共享首选项存储列表视图的数据并检索它不起作用

在两个活动之间使用相机图像处理意图并将其传递给 Google Maps API 上的标记不起作用

共享元素转换在父片段和子片段之间不起作用(嵌套片段)

在目标之间共享 UserDefault 不起作用

使用 GLFW3 在 OpenGL 上下文之间共享纹理不起作用