运行此活动后,应用未响应 - java

新的活动UI加载但没有响应,运行onStop()之后触发了Submit()

带有复选框的列表视图受自定义适配器的约束。触摸“提交”按钮后,将触发一个意图,该意图将我带到HomeActivity,并且触发了onStop()方法,该方法随后返回调用Submit方法。所有提交方法都是在新线程下创建的,这会干扰UI。
包com.example.cadur.teacher;

    public class Attendace extends AppCompatActivity {
    DatabaseReference dref;

    ArrayList<String> list=new ArrayList<>();
    ArrayList<DeatailAttandance> deatailAttandances;
    private MyListAdapter myListAdapter;
    private ProgressDialog pb;
    String year,branch,subject,emailId,pre,abs,rollno,file_name,dat,dat1,roll_str,rollno_present="",rollno_absent="";
    int pre_int,abs_int;
    ListView listview;
    FirebaseDatabase database;

    DatabaseReference myRef;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences sp=getSharedPreferences("login",MODE_PRIVATE);
        final String s=sp.getString("Password","");
        final String s1=sp.getString("username","");
        year=sp.getString("Year","");
        branch=sp.getString("Branch","");
        subject=sp.getString("Subject","");
        final String attend="Attandence";
        emailId=sp.getString("emailId","");
        if (s!=null&&s!="" && s1!=null&&s1!="") {
        setContentView(R.layout.activity_attendace);
            deatailAttandances=new ArrayList<>();
            listview = findViewById(R.id.list);
            TextView detail=findViewById(R.id.lay);
            detail.setText(year+"   "+branch+"   "+" "+subject);
            pb =new ProgressDialog(Attendace.this);
            pb.setTitle("Connecting Database");
            pb.setMessage("Please Wait....");
            pb.setCancelable(false);
            pb.show();
            database=FirebaseDatabase.getInstance();
        myRef=database.getReference(year+"/"+branch);
        myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot ds:dataSnapshot.getChildren()) {
                try {
                abs = ds.child("Attandence").child(subject).child("Absent").getValue().toString();
                pre = ds.child("Attandence").child(subject).child("Present").getValue().toString();
                rollno = ds.getKey().toString();
                deatailAttandances.add(new DeatailAttandance(rollno,pre,abs));
                myListAdapter=new MyListAdapter(Attendace.this,deatailAttandances);
                listview.setAdapter(myListAdapter);
                pb.dismiss();
                }catch (NullPointerException e){
                    pb.dismiss();
                Intent intent=new Intent(Attendace.this, Login.class);
                startActivity(intent);
                finish();
            }
            }
            count();
        }
            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
            }
        });

            Button selectAll=findViewById(R.id.selectall);
            selectAll.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                myListAdapter.setCheck();
                count();
                }
            });

            Button submit_attan=findViewById(R.id.submit_attan);
            submit_attan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent =new Intent(Attendace.this,HomeActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
            });


        Button count=findViewById(R.id.count);
        count.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View parentView = null;
                int counter=0;
                for (int i = 0; i < listview.getCount(); i++) {
                    parentView = getViewByPosition(i, listview);
                    CheckBox checkBox=parentView.findViewById(R.id.ch);
                    if(checkBox.isChecked()){
                        counter++;
                    }
                }
                Toast.makeText(Attendace.this,""+counter,Toast.LENGTH_SHORT).show();
            }
        });
        }else{
            SharedPreferences.Editor e = sp.edit();
            e.putString("Password", "");
            e.putString("username", "");
            e.commit();
            Intent i=new Intent(Attendace.this,MainActivity.class);
            startActivity(i);
            finish();
        }
    }

    @Override
    protected void onStop() {
        Attendace.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                submit();
            }
        });
        finish();
        super.onStop();
    }

    public void submit(){
        View parentView = null;
        final Calendar calendar = Calendar.getInstance();
        dat=new SimpleDateFormat("dd_MMM_hh:mm").format(calendar.getTime());
        dat1=new SimpleDateFormat("dd MM yy").format(calendar.getTime());
        file_name=year+"_"+branch+"_"+dat;
        rollno_present=rollno_present+""+year+"  "+branch+" "+subject+"\n    "+dat+"\n\nList of present Students\n";
        rollno_absent=rollno_absent+"\n List of absent Students\n";
        for (int i = 0; i < listview.getCount(); i++) {
            parentView = getViewByPosition(i, listview);
            roll_str = ((TextView) parentView.findViewById(R.id.text1)).getText().toString();
            String pre_str = ((TextView) parentView.findViewById(R.id.text22)).getText().toString();
            String abs_str = ((TextView) parentView.findViewById(R.id.text33)).getText().toString();
            pre_int=Integer.parseInt(pre_str);
            abs_int=Integer.parseInt(abs_str);
            CheckBox checkBox=parentView.findViewById(R.id.ch);
            if(checkBox.isChecked()){
                pre_int++;
                myRef.child(roll_str).child("Attandence").child(subject).child("Present").setValue(""+pre_int);
                myRef.child(roll_str).child("Attandence").child(subject).child("Date").child(dat1).setValue("P");
                rollno_present=rollno_present+"\n"+roll_str+"\n";
            }else{
                abs_int++;
                myRef.child(roll_str).child("Attandence").child(subject).child("Absent").setValue(""+abs_int);
                myRef.child(roll_str).child("Attandence").child(subject).child("Date").child(dat1).setValue("A");
                rollno_absent=rollno_absent+"\n"+roll_str+"\n";
            }
        }
//        Toast.makeText(Attendace.this,"Attendance Updated Successfully",Toast.LENGTH_SHORT).show();
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                generateNoteOnSD(Attendace.this,file_name,rollno_present+""+rollno_absent);
            }
        });
    }

    public void count(){
        View parentView = null;
        int counter=0;
        for (int i = 0; i < listview.getCount(); i++) {
            parentView = getViewByPosition(i, listview);
            CheckBox checkBox=parentView.findViewById(R.id.ch);
            if(checkBox.isChecked()){
                counter++;
            }
        }
        Toast.makeText(Attendace.this,""+counter,Toast.LENGTH_SHORT).show();
    }

    private View getViewByPosition(int pos, ListView listview1) {
        final int firstListItemPosition = listview1.getFirstVisiblePosition();
        final int lastListItemPosition = firstListItemPosition + listview1.getChildCount() - 1;

        if (pos < firstListItemPosition || pos > lastListItemPosition) {
            return listview1.getAdapter().getView(pos, null, listview1);
        } else {
            final int childIndex = pos - firstListItemPosition;
            return listview1.getChildAt(childIndex);
        }
    }


    public void generateNoteOnSD(Context context, String sFileName, String sBody) {
        try
        {
            File root = new File(Environment.getExternalStorageDirectory(),year+"_"+branch+"_Attendance");
            if (!root.exists())
            {
                root.mkdirs();
            }

            File gpxfile = new File(root, file_name+".doc");
            FileWriter writer = new FileWriter(gpxfile,true);
            writer.append(sBody+"\n");
            writer.flush();
            writer.close();
//            Toast.makeText(Attendace.this,"File Generated",Toast.LENGTH_SHORT).show();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}

参考方案

只需使用

submit();

而不是使用

Attendace.this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            submit();
        }
    });

并删除finish()

当回复有时是一个对象有时是一个数组时,如何在使用改造时解析JSON回复? - java

我正在使用Retrofit来获取JSON答复。这是我实施的一部分-@GET("/api/report/list") Observable<Bills> listBill(@Query("employee_id") String employeeID); 而条例草案类是-public static class…

java.net.URI.create异常 - java

java.net.URI.create("http://adserver.adtech.de/adlink|3.0") 抛出java.net.URISyntaxException: Illegal character in path at index 32: http://adserver.adtech.de/adlink|3.0 虽然n…

春天的多属性文件 - java

我在spring中加载属性文件: <context:property-placeholder location="classpath:foo.properties"/> 但是,如果我尝试在另一个上下文文件中加载另一个文件,则会出现错误。 java大神给出的解决方案 如果您需要覆盖属性,则可以执行以下操作:<context…

在Map中,如果我们使用现有键进行修改,则不会获得ConcurrentModificationException - java

我有以下代码,我希望从情况2的情况下抛出ConcurrentModificationException,但它运行成功。据我所知,如果我对地图中的单个键执行相同的操作,则不会抛出异常,因为here但是当我重现这种具有两个案例的多个密钥的场景时,通过新密钥修改。通过现有密钥进行修改。情况1: Map<String,String> mp = new H…

我正在尝试从用户那里获取输入并将其传输到文本文件 - java

我正在尝试编写一个聊天机器人,以便从用户那里学到答案,为此,我需要将答案保存到一个文本文件中,稍后再阅读。在代码中,它允许我编写问题,然后不创建文本文件并给出错误。有人可以告诉我我在做什么错。谢谢所有帮助。public static void main(String[] args) { // TODO Auto-generated method stub S…