在listview中填充数据时出现空指针异常

时间:2013-08-20 14:51:41

标签: android sql-server-2008 android-listview nullpointerexception

我是Android开发新手。我试图创建一个应用程序,在该应用程序中检索来自sql server的数据并在列表视图中显示。 我用edittext和复选框创建了一个自定义列表视图。 问题是来自服务器的数据不在listview中。我试图解决很多次,但每次出现相同的问题,即ResultSet为空。 我的代码是.........

Model.java的代码

public class Model {

 private String name;
    private boolean selected;
    private String score;

    public Model(String name) { 
       this.name = name;  
       selected = false;
        score="";          
   }
    public String getName() { 
        return name;    
        }

    public void setName(String name) { 
        this.name = name; 
        }

    public boolean isSelected() {   
        return selected;    
        }

    public void setSelected(boolean selected) {    
     this.selected = selected;    
     }

    public String getScore() {     
    return score;    
    }

    public void setScore(String score) {
        this.score = score;  
        }
    }

适配器类的代码

public class MyAdapter extends ArrayAdapter<Model> {

private final List<Model> list;   
private final Activity context;

public MyAdapter(Activity context, List<Model> list)
{
   super(context, R.layout.row, list);  
   this.context = context;       
   this.list = list;   
    }

static class ViewHolder
{        
    protected TextView text; 
    protected CheckBox checkbox;        
    protected EditText scores;    
}

@Override   
public View getView(int position, View convertView, ViewGroup parent)
{        
    View view = null;   
    if (convertView == null)
    {            
        LayoutInflater inflator = context.getLayoutInflater(); 

        view = inflator.inflate(R.layout.row, null); 

        final ViewHolder viewHolder = new ViewHolder(); 
        viewHolder.text = (TextView) view.findViewById(R.id.label);    
        viewHolder.scores=(EditText) view.findViewById(R.id.txtAddress);      
        viewHolder.scores.addTextChangedListener(new TextWatcher()
        {  
            public void onTextChanged(CharSequence s, int start, int before, int count) {      
                Model element=(Model)viewHolder.scores.getTag();    
                element.setScore(s.toString());        
            }        
            public void beforeTextChanged(CharSequence s, int start, int count,int after)
            {       
            }      
            public void afterTextChanged(Editable s)
            {                              
            }
            });         
        viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check);  
        viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {   
                Model element = (Model) viewHolder.checkbox.getTag();       
                element.setSelected(buttonView.isChecked());           
                }         
            }); 
        viewHolder.checkbox.setTag(list.get(position));      
        viewHolder.scores.setTag(list.get(position));
        view.setTag(viewHolder);   
    }
    else
    {
        view = convertView; 
        ((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));  
        ((ViewHolder) view.getTag()).scores.setTag(list.get(position));   
        }                 
        ViewHolder holder = (ViewHolder) view.getTag();     
        holder.text.setText(list.get(position).getName());    
        holder.scores.setText(list.get(position).getScore());      
        holder.checkbox.setChecked(list.get(position).isSelected());     
        return view;

 } 

}

MainActivity.java

public class MainActivity extends Activity { 
ListView listView;
 Button btnSave;
 Connection connect;
    ArrayAdapter<Model> adapter;
    List<Model> list = new ArrayList<Model>();

    public void initilize(){

         connect=CONN("sa","cbo@morc","KULDEEP","122.160.255.218:1433");
    }


    @SuppressLint("NewApi")
    private Connection CONN(String user,String pass,String db,String server){
     StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
     StrictMode.setThreadPolicy(policy);
     Connection conn=null;
     String connUrl=null;
     try{
     Class.forName("net.sourceforge.jtds.jdbc.Driver");
     connUrl="jdbc:jtds:sqlserver://" + server + ";" + "databaseName=" + db + ";user=" + user + ";password=" + pass + ";";
     conn=DriverManager.getConnection(connUrl);
     }catch(SQLException se){
         Log.e("ERROR", se.getMessage());
     }catch(ClassNotFoundException cl){
         Log.e("ERROR", cl.getMessage());
     }catch(Exception e){
         Log.e("ERROR", e.getMessage());
     }

     return conn;

       }

    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        listView = (ListView) findViewById(R.id.my_list);
        btnSave = (Button)findViewById(R.id.btnSave);
        adapter = new MyAdapter(this,getModel());
        listView.setAdapter(adapter);
        if(list.isEmpty()){
            Toast.makeText(getApplicationContext(), "kuldeep", Toast.LENGTH_LONG).show();
        }

        btnSave.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                for (int i = 0; i < list.size(); i++) {
                    Toast.makeText(getBaseContext(), "Name : "+list.get(i).getName() +" Selected: "+list.get(i).isSelected()+"address: "+list.get(i).getScore().toString(), Toast.LENGTH_SHORT).show();

                }
            }
        });
    }


    private List<Model> getModel() {
        ResultSet rs;
        try{
        Statement smt=connect.createStatement();
        rs=smt.executeQuery("select * from friends1");
        while(rs.next()){
            //Toast.makeText(getApplicationContext(), "0000", Toast.LENGTH_LONG).show();
            list.add(new Model(rs.getString("name")));
        }
        }catch(Exception e){
            e.printStackTrace();
        }
                return list;
    }
}

main.xml中

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ListView
    android:id="@+id/my_list"
    android:layout_width="fill_parent"
    android:layout_height="250px" />
    <Button 
    android:text="Save" 
    android:id="@+id/btnSave" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"/>

    </LinearLayout>

row.xml

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
    android:id="@+id/label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@+id/label"
    android:textSize="30sp"/>

    <CheckBox
    android:id="@+id/check"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
    <EditText 
    android:text=""
    android:id="@+id/txtAddress"
    android:layout_width="150px"
    android:layout_height="wrap_content"/>
    </LinearLayout>

如果有人请建议我这个问题的正确解决方案是什么... 如何在rs中获得价值。

logcat按摩。

08-20 14:33:41.173: W/System.err(717): java.lang.NullPointerException
08-20 14:33:41.173: W/System.err(717):  at com.kuldeep.mylistedittext.MainActivity.getModel(MainActivity.java:92)
08-20 14:33:41.173: W/System.err(717):  at com.kuldeep.mylistedittext.MainActivity.onCreate(MainActivity.java:69)
08-20 14:33:41.173: W/System.err(717):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-20 14:33:41.183: W/System.err(717):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
08-20 14:33:41.183: W/System.err(717):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
08-20 14:33:41.183: W/System.err(717):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)

08-20 14:33:41.183:W / System.err(717):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:931)

1 个答案:

答案 0 :(得分:1)

视图持有者方法应如下面的代码: -

 if (convertView == null) {
         convertView = mInflater.inflate(R.layout.list_item_icon_text,
                 parent, false);
         holder = new ViewHolder();
         holder.text = (TextView) convertView.findViewById(R.id.text);
         holder.icon = (ImageView) convertView.findViewById(R.id.icon);

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

更改获取视图的代码。

更多尝试以下链接: -

http://vsvydenko.blogspot.in/2011/06/android-use-viewholder.html

How to implement a view holder?