2016-05-26 1 views
-2

Я хочу выделить определенную строку в виде списка на основе определенного условия, являющегося true.I пробовал следующий код, и я получаю исключение Null Pointer.Изменить цвет строки в списке, если выполняется определенное условие?

public class BillsCustomList extends ArrayAdapter<String> 
{ 
    private String[] doc_no; 
    private String[]date; 
    private String[] cust_name; 
    private String[] cust_number; 
    private String[] item_count; 
    private String[]total_wt; 
    private String[]total; 
    private String[]balance; 
    private String[]bill_type; 
    private String[]status; 

    private Activity context; 

    public BillsCustomList(Activity context, String[] doc_no, String[] date, String[] cust_name,String[] cust_number, 
          String[] item_count,String[] total_wt,String[] total,String[] balance,String[] bill_type,String[] status) 
    { 
     super(context, R.layout.bills_list_view, doc_no); 
     this.context =context; 
     this.doc_no=doc_no; 
     this.date = date; 
     this.cust_name = cust_name; 
     this.cust_number = cust_number; 
     this.item_count= item_count; 
     this.total_wt = total_wt; 
     this.total = total; 
     this.balance = balance; 
     this.bill_type = bill_type; 
     this.status = status; 

    } 

    @Override 
    public View getView(int position, View listViewItem, ViewGroup parent) 
    { 
     if (null == listViewItem) { 
      LayoutInflater inflater = context.getLayoutInflater(); 
      listViewItem = inflater.inflate(R.layout.bills_list_view, null, true); 
     } 
     TextView textViewDocno = (TextView) listViewItem.findViewById(R.id.textViewInvNo); 
     TextView textViewDt = (TextView) listViewItem.findViewById(R.id.textViewDt); 
     TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName); 
     TextView textViewNumber = (TextView) listViewItem.findViewById(R.id.textViewNumber); 
     TextView textViewCount = (TextView) listViewItem.findViewById(R.id.textViewCount); 
     TextView textViewTotwt = (TextView) listViewItem.findViewById(R.id.textViewTotwt); 
     TextView textViewTot = (TextView) listViewItem.findViewById(R.id.textViewTot); 
     TextView textViewBal = (TextView) listViewItem.findViewById(R.id.textViewBalanace); 
     TextView textViewBt = (TextView) listViewItem.findViewById(R.id.textViewBt); 
     TextView textViewStatus = (TextView) listViewItem.findViewById(R.id.textView_status); 
     LinearLayout ll = (LinearLayout) listViewItem.findViewById(R.id.ll_bills); 

     textViewDocno.setText(doc_no[position]); 
     textViewDt.setText(date[position]); 
     textViewName.setText(cust_name[position]); 
     textViewNumber.setText(cust_number[position]); 
     textViewCount.setText(item_count[position]); 
     textViewTotwt.setText(total_wt[position]); 
     textViewTot.setText(total[position]); 
     textViewBal.setText(balance[position]); 
     textViewBt.setText(bill_type[position]); 
     textViewStatus.setText(status[position]); 

     try 
     { 
      if (textViewStatus.getText().toString().equalsIgnoreCase("true")) 
      { 
       ll.setBackgroundColor(Color.RED); 

      } 

     }catch (NullPointerException e) 
     { 
      Log.d("NULL ERROR", "position"+position+e); 
     } 




     return listViewItem; 
    } 


} 

I have simple use case if the status is true make the row of a certain color.Else don't do anything.I get the following error when I try the above code.

NULL ERROR: position0java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference

я получаю эти нулевые исключения указатель на 0 и 1 position.Can кто-нибудь объяснить, почему это происходит и что будет правильный способ сделать это. Любая помощь или предложение приветствуются. Благодарю вас.

+0

использовать 'equals' вместо' equalsIgnoreCase' и повторить попытку. –

+0

@vrundpurohit Я пробовал равняться, но это не имело никакого значения. – AndroidNewBee

+0

if (status [position] .compareTo ("true") == 0) { listViewItem.setBackgroundColor() ... } – Nanoc

ответ

1

Может быть, вы gettign status[position] нуля для некоторых позиций, чтобы избежать этого изменить ваш код следующего

if(textViewStatus.getText()!=null){ 

    if (textViewStatus.getText().toString().equalsIgnoreCase("true")) 
    { 
     ll.setBackgroundColor(Color.RED); 

    }else{ 
     ll.setBackgroundColor("Different color"); 
    } 
}else{ 
     ll.setBackgroundColor("Different color"); 
} 
+0

Я пробовал это, но он меняет цвет первой и последней строки, когда только последняя строка статус прав. – AndroidNewBee

+0

@AndroidNewBee я отредактировал мой ответ, пожалуйста, проверьте – mdDroid

+0

Большое вам спасибо @mdDroid. – AndroidNewBee

0

Вы должны проверить позицию массива на массиве перед тем фоном изменения:

if (position < status.length() && status[position].equalsIgnoreCase("true")) 
    ll.setBackgroundColor(Color.RED); 
else 
    ll.setBackgroundResource(android.R.color.transparent); 

я надеюсь, что все массивы имеют одинаковую длину или логика ArrayAdapter не работает должным образом

1

Ну @mdDroid ответил на вопрос, но есть некоторые другой стандартный способ проверки нулевой строки.

TextUtils.isEmpty(CharSequence str) - Returns true if the string is null or 0-length.

if (!TextUtils.isEmpty(textViewStatus.getText()) && textViewStatus.getText().toString().equalsIgnoreCase("true")) 
    ll.setBackgroundColor(Color.RED); 
else 
    ll.setBackgroundResource(android.R.color.transparent); 

Лучший способ избежать NPE для строк в письменной форме условия как ниже

if ("true".equalsIgnoreCase(textViewStatus.getText().toString())) 
    ll.setBackgroundColor(Color.RED); 
else 
    ll.setBackgroundResource(android.R.color.transparent); 

happyCoding;