-2

I'm working on an Android app for Students where students can attempt and view their test.

I'm displaying a test to student in a listview in an Activity. I also want to display the total and obtained marks of student.

That's my ArrayAdapter's getView function.

public View getView(int position, View convertView, ViewGroup parent) { 
   Text_Questions questions = getItem(position);
   ViewHolder v = null;
   View view = convertView;
   try {
        if (convertView == null) {
            v = new ViewHolder();
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.text_questions_list_item, parent, false);
            v.title = (TextView)convertView.findViewById(R.id.title);
            v.marks = (TextView)convertView.findViewById(R.id.marks);
            v.answer = (TextView)convertView.findViewById(R.id.answer);
            v.std_answer = (TextView)convertView.findViewById(R.id.std_answer);
            convertView.setTag(v);
        }
        else {
            v = (ViewHolder) convertView.getTag();
        }
        v.title.setText("Q: "+questions.getTitle());
        v.std_answer.setText("Ans: "+ questions.getStd_answer());
        v.answer.setText("Correct: " + questions.getAnswer());
        if(questions.getAnswer().toLowerCase().equals(questions.getStd_answer().toLowerCase())){
            v.marks.setText(""+questions.getMarks() + "/" + questions.getMarks());
        }else{
            v.marks.setText("0/" + questions.getMarks());
        }
        return convertView;
    }catch (Exception e) {
        return null;
    }
}

While setting an item to ListView I want to pass that question's marks to my Activity. I didn't found any solution for this. Any idea?

Thanks for Your help in advance

1 Answers1

1

You can create a public method in your Activity as follows:

public void setMarks(int marks){
    this.marks = marks
}

Then in your ArrayAdapter you can do the following:

private YourActivity yourActivity;

public YourArrayAdapter(YourActivity yourActivity) {

    this.yourActivity = yourActivity;

}

Then in your getView():

yourActivity.setMarks(marks);
sri
  • 744
  • 7
  • 20
  • Thanks, Your solution worked. But I have one issue, I'm calling `myActivity.setMarks(marks)` in `getView()` but `getView()` call himself twice for every item. – Muhammad Taimoor Sultani Jul 07 '17 at 09:04
  • 1
    I'm glad that the solution worked. However for your query of getView() getting called multiple times, I would suggest you to ask a separate question so that the current question does not go off topic. Also, please accept the answer if you feel that the solution to the current question worked. Thanks :). Also, please go through the following : https://stackoverflow.com/questions/2872996/best-way-to-handle-multiple-getview-calls-from-inside-an-adapter – sri Jul 07 '17 at 09:28