当前位置: 首页 > 知识库问答 >
问题:

从第二个活动返回后更新第一个活动中的Listview

白昊乾
2023-03-14

我在一个活动中有一个列表视图,在自定义适配器中有一个信息图标。当用户点击该信息按钮时,下一个活动将打开,当用户点击更新按钮时,在下一个活动中标记出勤率后,第二个活动应该完成,第一个活动列表视图应该更新。

我成功地做了什么:我已经成功地标记了出席情况并更改了listview的颜色,但我在关闭第二个活动并重新启动第一个活动后这样做了。通过这种方式,由于再次开始活动,listview会得到更新。

我无法做到的事情:我希望当用户点击更新按钮时,只有完成()会调用,用户返回到之前的第一个活动,并更新了listview。但是当我这样做时,listview不会得到更新。我必须返回并再次打开活动,然后listview得到更新,否则不会。我不想这样。我还尝试在onResume方法中通知第一个活动的适配器,以便当用户从第二个活动返回时,第一个活动listview适配器将因onResume方法而更新,但它不起作用。请帮助

我的Listview活动代码

public class TeacherWebserviceMainList extends Activity {
int attentedncemarkedCount = 0;
TextView addteacher;
DatabaseHandler databasehandler;
DetailsTeacherwebservice details;
String emis;

ArrayList<DetailsTeacherwebservice> addas = new ArrayList<DetailsTeacherwebservice>();
CustomAdapterTeacherWebservice cusadapter;
ArrayList<DetailsTeacherwebservice> teacherList;
private ListView listcontent = null;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.teacherwebservicemainlist );
    addteacher = (TextView) findViewById(R.id.addteachermenu);

    databasehandler = new DatabaseHandler(TeacherWebserviceMainList.this);
    listcontent = (ListView) findViewById(R.id.teacher_list);
    teacherList = databasehandler.teacherwebserviceList(emis);
    Rsults();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1) {
        if(resultCode == RESULT_OK) {
            String update = data.getStringExtra("update");
            if(update.equals("1"))
            {
                //cusadapter.
                CustomAdapterTeacherWebservice adapter = new CustomAdapterTeacherWebservice(this, addas);

                listcontent.setAdapter(adapter);
            }
        }
    }
}

private void Rsults() {
    addas.clear();
    //DatabaseHandler databaseHandler=new DatabaseHandler(this);
    //ArrayList<ArrayList<Object>> data =  databaseHandler.abcTeacherNew();

    for (int p = 0; p < teacherList.size(); p++) {
        details = new DetailsTeacherwebservice();
        //ArrayList<Object> baris = data.get(p);
        details.setId(teacherList.get(p).getId());
        details.setTeachername(teacherList.get(p).getTeachername());
        details.setTeachercnic(teacherList.get(p).getTeachercnic());
        details.setTeacherno(teacherList.get(p).getTeacherno());
        details.setTeachergender(teacherList.get(p).getTeachergender());
        details.setAttendance(teacherList.get(p).getAttendance());
        details.setTeacherattendancedetails(teacherList.get(p).getTeacherattendancedetails());
        details.setAttendancedatesince(teacherList.get(p).getAttendancedatesince());
        details.setAttendancetrasnferschool(teacherList.get(p).getAttendancetrasnferschool());
        addas.add(details);
    }
    cusadapter = new CustomAdapterTeacherWebservice(TeacherWebserviceMainList.this, addas);
    listcontent.setAdapter(cusadapter);
    listcontent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {


        }
    });
}

我的列表适配器代码

 public class CustomAdapterTeacherWebservice extends BaseAdapter {

private static ArrayList<DetailsTeacherwebservice> searchArrayList;
DatabaseHandler databaseHandler;
private Context context;
private LayoutInflater mInflater;

public CustomAdapterTeacherWebservice(Context context, ArrayList<DetailsTeacherwebservice> results) {
    searchArrayList = results;
    mInflater = LayoutInflater.from(context);
    databaseHandler = new DatabaseHandler(context);
}

@Override
public int getCount() {
    return searchArrayList.size();
}

@Override
public Object getItem(int p) {
    return searchArrayList.get(p);
}

@Override
public long getItemId(int p) {
    return p;
}

public int getViewTypeCount() {

    return 500;
}



@Override
public int getItemViewType(int position) {

    return position;
}

@Override
public View getView(final int p, View v, ViewGroup parent) {
    ViewHolder holder;
    context = parent.getContext();
    if (v == null) {
        v = mInflater
                .inflate(R.layout.teacherwebserviceadapter, null);
        holder = new ViewHolder();

        holder.name = (TextView) v.findViewById(R.id.teacher_name);
        holder.cnic = (TextView) v.findViewById(R.id.teacher_cnic);
        holder.no = (TextView) v.findViewById(R.id.teacher_phone);
        holder.gender = (TextView) v.findViewById(R.id.gender);
        holder.status = (TextView) v.findViewById(R.id.status);
        holder.info = (ImageView) v.findViewById(R.id.edit);
        holder.l1 = (LinearLayout) v.findViewById(R.id.main);


        v.setTag(holder);
    } else {
        holder = (ViewHolder) v.getTag();
    }

    holder.name.setText(searchArrayList.get(p).getTeachername());
    holder.cnic.setText(searchArrayList.get(p).getTeachercnic());
    holder.no.setText(searchArrayList.get(p).getTeacherno());
    holder.gender.setText(searchArrayList.get(p).getTeachergender());
    holder.status.setText(searchArrayList.get(p).getAttendance());
    if (searchArrayList.get(p).getAttendance().equals("Absent"))
    {
        holder.l1.setBackgroundColor(Color.parseColor("#DB674D"));
    }
    if (searchArrayList.get(p).getAttendance().equals("Present"))
    {
        holder.l1.setBackgroundColor(Color.parseColor("#7EB674"));
    }
    if (searchArrayList.get(p).getAttendance().equals("Transfer Out"))
    {
        holder.l1.setBackgroundColor(Color.parseColor("#FBE87C"));
    }
    if (searchArrayList.get(p).getAttendance().equals("Resigned"))
    {
        holder.l1.setBackgroundColor(Color.parseColor("#4FC3F7"));
    }
    holder.info.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent view_order_intent = new Intent(context, Teacherwebservicemainlistupdate.class);
            view_order_intent.putExtra("ID", searchArrayList.get(p).getId());
            view_order_intent.putExtra("tname", searchArrayList.get(p).getTeachername());
            view_order_intent.putExtra("tgender", searchArrayList.get(p).getTeachergender());
            view_order_intent.putExtra("tcnic", searchArrayList.get(p).getTeachercnic());
            view_order_intent.putExtra("tno", searchArrayList.get(p).getTeacherno());
            view_order_intent.putExtra("tatt", searchArrayList.get(p).getAttendance());
            view_order_intent.putExtra("tattdetails", searchArrayList.get(p).getTeacherattendancedetails());
            view_order_intent.putExtra("tattdatesince", searchArrayList.get(p).getAttendancedatesince());
            view_order_intent.putExtra("tatttrasnferout", searchArrayList.get(p).getAttendancetrasnferschool());
            //context.startActivity(view_order_intent);
            ((Activity)context).startActivityForResult(view_order_intent, 1);
        }
    });
    return v;
}

static class ViewHolder {
    TextView name, cnic, no, gender,status;
    ImageView info;
    LinearLayout l1;

}

在适配器代码中,当单击“信息”按钮时,另一个活动开始,用户可以在其中更新考勤。

这是单击按钮时的更新活动代码:

  update.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        DetailsTeacherwebservice schoolinfo = new DetailsTeacherwebservice();
                schoolinfo.setTeachername(teachername.getText().toString());
                schoolinfo.setTeacherno(teacherno.getText().toString());
                schoolinfo.setTeachercnic(teachercnic.getText().toString());
                schoolinfo.setTeachergender(teachergender.getText().toString());
                schoolinfo.setAttendance(teachergroupstr);
                schoolinfo.setTeacherattendancedetails(absentgrpstr);
                schoolinfo.setAttendancedatesince(txtDate.getText().toString());
                schoolinfo.setAttendancetrasnferschool(transferOutSchool.getText().toString());
                databasehandler.updateteacherwebservice(schoolinfo, emis, identity);
                Toast.makeText(Teacherwebservicemainlistupdate.this, "Updated Successfully", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent();
                intent.putExtra("update", "1");
                setResult(RESULT_OK, intent);
                finish();

            }
        }
    });

我可以在单击更新按钮时再次启动listview活动,但这会更改单击的列表项的索引,即因为活动再次启动。然而,我想要的是,如果我点击了第10项,那么当下一个活动打开并且用户更新出席情况时,它将返回到相同索引位置上的上一个活动,这样用户就不必再次滚动以返回第10项

共有3个答案

彭修筠
2023-03-14

您必须在 onResume 方法中的适配器中设置数据

 @Override
    protected void onResume() {
        super.onResume();
    }
欧阳乐生
2023-03-14

以下是两个示例,第一个示例中ListView的源是List(在本例中使用自定义适配器),第二个示例中的源是游标(使用SimpleCursorAdapter)

许多人陷入的陷阱只是使用以下内容更新列表:-

    myList = method();
    myAdapter.notifyDataSetChanged();

据猜测,那是你掉进的陷阱。

什么时候应该使用列表的方法来改变它(例如< code>clear、< code>add、< code>addAll、< code>remove)。

我相信这就解释了原因-Java是“通过引用传递”还是“通过值传递”?

/**
 * Build or rebuild the List of TaskData's, instantiate the
 * Custom Array Adapter if needed and also notify the adapter
 * if the List may have been changed.
 */
private void prepTasksCustomArrayList() {
    // Determine if the adpater needs to be notified of changes
    boolean notify_dataset_changed = (mCsr != null && mCustomArrayAdapter != null);

    // If the List is not null then assume that it has changed
    // otherwise just get the List
    if (mTasks != null) {
        mTasks.clear();
        mTasks.addAll(dbhlpr.getAllTasks());
    } else {
        mTasks = dbhlpr.getAllTasks();
    }
    // If the adapter is null then instantiate it
    if (mCustomArrayAdapter == null) {
        mCustomArrayAdapter = new CustomArrayAdapter(
                this,
                R.layout.taskdata_item,
                mTasks);
    }
    // Notify the adapter that the List has changed
    if (notify_dataset_changed) {
        mCustomArrayAdapter.notifyDataSetChanged();
    }
}

笔记

    < li >这用于设置和更改/更新适配器所连接的< code>ListView。 < li >只需在代码中的适当位置调用该方法,例如在onCreate、onResume、onItemClick/LongClick之后的活动中。 < ul > < li >例如,在onCreate中:- < Li > < code > mTaskList = this . findviewbyid(r . id . task list);//ListView < Li > < code > prepTasksCustomArrayList() < Li > < code > mtasklist . setadapter(mCustomArrayAdapter) < li >并且在< code>onresume中(连同< code>onCreate中的3行) < Li > < code > prepTasksCustomArrayList()
/**
 * Build or rebuild the List via Cursor using the bespoke layout
 */
private void prepCursorListBespoke() {
    boolean swapcursor = (mCsr != null && mCursorAdapter2 != null);
    if (mCursorAdapter2 == null) {
        mCursorAdapter2 = new SimpleCursorAdapter(this,R.layout.taskdata_item,mCsr,
                new String[]{ Datasource.TASKS_ID_COL,
                        Datasource.TASKS_TYPE_COL,
                        Datasource.TASKS_NAME_COL,
                        Datasource.TASKS_OWNER_COL,
                        Datasource.TASKS_EXPIRATION_COL},
                new int[]{R.id.task_id,
                        R.id.task_type,
                        R.id.task_name,
                        R.id.task_owner,
                        R.id.task_expiration},
                0);
    }
    if (swapcursor) {
        mCursorAdapter2.swapCursor(mCsr);
    }
}

笔记

  • preCursorListBespoke方法的使用方式与示例1相同。
  • 可以使用
  • 消息通知,而不是swapCursor
    • 我使用swapCursor因为它更具描述性)。

    大致说来,我已经应用了上面的列表示例,下面的更改可能会起作用。

    i、 e.RsultsonResume(添加)调用,它将通知适配器数据已更改。

    代码尚未经过测试,因为没有足够的代码。(a)没有< code>DatabaseHandler类的代码,b)没有< code > DetailsTeacherwebservice 类的代码)。因此,可能会有错误。

    查找< code>//...注释应该跟在后面,说明做了什么/改变了什么。

    public class MainActivity extends Activity {
        int attentedncemarkedCount = 0;
        TextView addteacher;
        DatabaseHandler databasehandler;
        DetailsTeacherwebservice details;
        String emis;
    
        ArrayList<DetailsTeacherwebservice> addas = new ArrayList<DetailsTeacherwebservice>();
        CustomAdapterTeacherWebservice cusadapter;
        ArrayList<DetailsTeacherwebservice> teacherList;
        private ListView listcontent = null;
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.teacherwebservicemainlist);
            addteacher = (TextView) findViewById(R.id.addteachermenu);
    
            databasehandler = new DatabaseHandler(TeacherWebserviceMainList.this);
            listcontent = (ListView) findViewById(R.id.teacher_list);
            //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            //MOVED  On ItemClickListener block FROM Rsults to here.
            listcontent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position,
                                        long id) {
    
    
                }
            });
            //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    
            teacherList = databasehandler.teacherwebserviceList(emis);
            Rsults();
        }
    
        
        // Probably don't even need onActivityResult
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == 1) {
                if (resultCode == RESULT_OK) {
                    String update = data.getStringExtra("update");
                    if (update.equals("1")) {
                        //cusadapter.
                        //CustomAdapterTeacherWebservice adapter = new CustomAdapterTeacherWebservice(this, addas);
                        //+++++++++++++++++++++++++++++++++++
                        // Commented out
                        //listcontent.setAdapter(adapter);
                    }
                }
            }
        }
    
        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        // Added onResume to call Rsults
        @Override
        public void onResume() {
            super.onResume();
            Rsults();
        }
    
        private void Rsults() {
            
            //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            // ADDED 4 lines to see if the notifyDataSetChanged is required
            boolean notifydschg_needed = false;
            if (cusadapter != null) {
                notifydschg_needed = true;
            }
            //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            // YOU NEED TO GET THE TEACHER LIST AGAIN AS THE DB HAS CHANGED
            teacherList = databasehandler.teacherwebserviceList(emis);
            
            addas.clear();
            //DatabaseHandler databaseHandler=new DatabaseHandler(this);
            //ArrayList<ArrayList<Object>> data =  databaseHandler.abcTeacherNew();
    
            for (int p = 0; p < teacherList.size(); p++) {
                details = new DetailsTeacherwebservice();
                //ArrayList<Object> baris = data.get(p);
                details.setId(teacherList.get(p).getId());
                details.setTeachername(teacherList.get(p).getTeachername());
                details.setTeachercnic(teacherList.get(p).getTeachercnic());
                details.setTeacherno(teacherList.get(p).getTeacherno());
                details.setTeachergender(teacherList.get(p).getTeachergender());
                details.setAttendance(teacherList.get(p).getAttendance());
                details.setTeacherattendancedetails(teacherList.get(p).getTeacherattendancedetails());
                details.setAttendancedatesince(teacherList.get(p).getAttendancedatesince());
                details.setAttendancetrasnferschool(teacherList.get(p).getAttendancetrasnferschool());
                addas.add(details);
            }
            
            //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            //Just create the adapter and attach it to the listview once
            if (cusadapter == null) {
                cusadapter = new CustomAdapterTeacherWebservice(TeacherWebserviceMainList.this, addas);
                listcontent.setAdapter(cusadapter);
            }
            //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            // Notify the adapter that the data has been changed 
            if(notifydschg_needed) {
                cusadapter.notifyDataSetChanged();
            }
        }
    }
    

汝和裕
2023-03-14

为列表项添加此代码单击:

 Intent i = new Intent(context, YourAcitivityName.class);
     i.putExtra("position",p);
    startActivityForResult(i, 1);

在更新按钮中添加此代码:

Intent intent = new Intent();
intent.putExtra("update", "1");
intent.putExtra("position",getIntent().getIntExtra("position",0));
setResult(RESULT_OK, intent);        
finish();

当您从活动返回到实现列表视图的活动时,此方法称为:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1) {
         if(resultCode == RESULT_OK) {
             String update = data.getStringExtra("update");
             if(update.equals("1"))
             {
               // add your code to update list view
                 teacherList = databasehandler.teacherwebserviceList(emis);
                 Rsults();
                  YourAdapterClassName adapter = new YourAdapterClassName(this, arrList);

                  listView.setAdapter(adapter);
               listView.smoothScrollToPosition(getIntent().getIntExtra("position",0));
              }
         }     
    }
} 
 类似资料:
  • 次要活动(通过意图向主活动发送“endpoint”字符串): 主活动(从次要活动获取字符串): 在Fragment类上,我试图在TextView上显示数据: 如何修复它并将字符串从一个活动发送到另一个活动上的片段? 下面是XML:

  • 我刚开始使用Xamarin和VisualStudio2017在C#中为Android开发。与Windows生态系统完全不同的范例…Target是一个商业应用程序,将有特定的受众,但在我深入了解之前,我只是试图学习绳子,理解概念和程序… 因此,我从最简单的app开始,使用空白模板。这将创建一个项目,其中包含一个活动(mainactivity.cs)、两个资源(resources\layout\mai

  • 我有第一活动,它通过意图调用第二活动 在SecondActivity完成后,我希望SecondActivity向FirstActivity发送一些变量。然后调用finsih(),它将返回到第一个活动。如何使SecondActivity发送变量并在FirstActivity中获得结果?

  • 我想按下mainactivity中的一个按钮,该按钮将启动一个包含片段的新活动的意图。我写了一个主要的活动。带有main活动和第二个_活动按钮的xml。带有片段的xml。当我单击按钮时,第二个活动将由于xml中的片段而崩溃。我已经添加了一个标志,但它没有帮助。该应用程序的想法是通过按下主活动中的按钮,在第二个活动中获取谷歌地图。 我希望你能帮助我:/ 主要活动: 亚活性: activity_mai

  • 活动1:我有一个图像视图,其中从相机和画廊拍摄的图像被设置,它工作正常。在这个活动中有一个右键单击按钮,它将重定向到第二个活动。 活动2:在这个活动中,我有四个选择 保存 活动3:从上述四个选项中,第三个活动相应地工作。现在我不知道如何将第一个活动中拍摄的图像传递给第三个活动。 我的努力:在从相机拍摄的第一张活动图片中: 在第二个活动SaveVia中: 在第三个名为“保存”的活动中:

  • 下面的第一个代码块是我的主要活动,我在其中创建了第二个活动的意图。在这个活动中,我将在列表视图中显示费用,因为它还没有完全实现,所以我暂时忽略了它。我想做的就是启动第二个活动,让用户输入详细信息,然后按下一个按钮将活动添加到列表视图中。@override公共布尔onOptionsItemSelected(MenuItem item){int id=item.getItemId(); 这是用户输入数