view的空指针异常,listview加载数据底部添加按钮

listview数据加载后底部添加按钮:

先写一个xml文件,里面添加按钮控件,如下listbutton。xml,按钮居中对齐的哦。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:gravity="center_vertical|center_horizontal"
    android:layout_gravity="center_vertical|center_horizontal"
    android:orientation="horizontal" >
   
  <Button
     android:id="@+id/lastButton"
     android:layout_width="wrap_content"
     android:layout_height="30px"
     android:gravity="center_vertical"
     android:layout_marginTop="5px"
     android:text="上一页"
     android:onClick="lastPageDate"/>
 
  <TextView
      android:id="@+id/counTe"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:gravity="center_vertical"
      android:text=""
      />
 
  <Button
     android:id="@+id/nextButton"
     android:layout_width="wrap_content"
     android:layout_height="30px"
     android:layout_gravity="center_vertical"
     android:layout_marginTop="5px"
     android:layout_marginLeft="10px"
     android:text="下一页"
     android:onClick="nextPageDate"/>
</LinearLayout>

 

 

 

放listview的那个xml就不展示了,因为很简单,只是在界面里加一个listview。不过必须设置android:layout_width="fill_parent",否则按钮无法居中。

下面就是后台代码了。

MainActivity。java。

 

package com.example.dbconnectiontest;

/*必须引用apache.http相关类来创建HTTP连接*/
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.security.auth.PrivateCredentialPermission;

import org.apache.http.Header;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.example.dbconnectiontest.entity.people;
import com.example.dbconnectiontest.jsonto.JsonToList;

import android.R.integer;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
/* 必须引用java.io与java.util相关类来读写文件*/

public class MainActivity extends Activity {

 private static final String TAG = "MainActivity";
 private static final String URL2 = "http://192.168.1.101:8080/BootStarpImage/getList.action";
 static int index = 1;//存放页码
 static int indexCount = 5;//存放总页码
 Button seButton,lastButton,nextButton;//获取数据按钮,上一页,下一页按钮
 TextView counTextView;//显示页码
 ListView lView;//listview
 View buView; //获取listview底部按钮的xml
 private int[] lay = new int[4];//存放实体类对象的text数组
 private List data = new ArrayList();//存放获取到的数据
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  seButton = (Button)findViewById(R.id.btnOne);
  seButton.setOnClickListener(new clicklist());
  lView = (ListView)findViewById(R.id.listview);
  /**
   * 在listview底部添加按钮
   */
  buView = getLayoutInflater().inflate(R.layout.listbutton, null);
  lView.addFooterView(buView);
  
  /**
   * 必须放在lview后面,先添加listview才能找到listview上的控件,否则抛出空指针异常
   */
  lastButton = (Button)findViewById(R.id.lastButton);
  nextButton = (Button)findViewById(R.id.nextButton);
  counTextView = (TextView)findViewById(R.id.counTe);
 }
 


/**
 {"people":[{"firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" }, { "firstName": "Jason", "lastName":"Hunter", "email": "bbbb"},{ "firstName": "Elliotte","lastName":"Harold", "email": "cccc" }]}
 */
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }
 
 class clicklist implements OnClickListener{

  @Override
  public void onClick(View v) {
   String urlString = URL2 + "?index=1";
   String string = httpToServiceSelectData(urlString);
   listToData(string);
   /**
    * 查询总页码
    */
//   urlString = "";
//   string = httpToServiceSelectData(urlString);
      setPageButton(v);此处必须传入v及view,否则后续报出关于view的空指针
  }

 }

 /**
  * 请求数据 传入一个url
  * @param urlString
  */
 private String httpToServiceSelectData(String urlString) {
  HttpClient client=new DefaultHttpClient(); 
        //创建一个GET请求
        HttpGet httpGet=new HttpGet(urlString);
        //向服务器发送请求并获取服务器返回的结果  
        HttpResponse response;
  try {
   response = client.execute(httpGet);
   int staCode = response.getStatusLine().getStatusCode();
   if(staCode == 200){
    //返回的结果可能放到InputStream,http Header中等。
    String string  = EntityUtils.toString(response.getEntity(),HTTP.UTF_8);
    return string;//返回读取到的数据,用其它方法进行转换成实体
   }else if(staCode == 404)
    Toast.makeText(getApplicationContext(), "服务器异常,请稍候再试。", Toast.LENGTH_SHORT).show();
   else if (staCode == 500)
    Toast.makeText(getApplicationContext(), "读取数据失败,请稍候查询。", Toast.LENGTH_SHORT).show();
  } catch (ClientProtocolException e1) {
   e1.printStackTrace();
  } catch (IllegalStateException e1) {
   e1.printStackTrace();
  } catch (IOException e1) {
   e1.printStackTrace();
  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;
 }
 
 /**
  * 将查询到的数据添加到listview中
  * @param string 返回的字符串(转成过的)
  */
 private void listToData(String string) {
  JsonToList jToList = new JsonToList();
  List<people> li = jToList.returnListView(string);此处调用的是一个java类中的方法,自己写的,代码就几行。要的在下面
  for (people ent : li) {
   Map<String, String> map = new HashMap<String, String>();
   map.put("id", ent.getId()+"");
   map.put("firstName", ent.getFirstName());
   map.put("lastName", ent.getLastName());
   map.put("email", ent.getEmail());
   data.add(map);
  }
  SimpleAdapter sAdapter = new SimpleAdapter(MainActivity.this, data, R.layout.listview, new String[]{"id","firstName","lastName","email"}, new int[]{R.id.ids,R.id.firstName,R.id.lastName,R.id.email});
  sAdapter.notifyDataSetChanged();//增加或删除操作进行后调用该方法,更改listview中的数据,否则会一直往listview下方添加
  lView.setAdapter(sAdapter);
 }
 
 //设置页码信息,以及按钮的是否可点击
 private void setPageButton(View view) {
  counTextView.setText(index + "/" + indexCount);//设置页码数
  if(index == 1)
   lastButton.setClickable(false);
  else
   lastButton.setClickable(true);
  if(index == indexCount)
   nextButton.setClickable(false);
  else
   nextButton.setClickable(true);
 }
 
 @Override
 protected void onDestroy() {
  super.onDestroy();
 }
 
 //点击过按钮过后,加载数据时按钮不可用
 public void setButtonAll(Button lastButton,Button nextButton) {
  lastButton.setClickable(false);
  nextButton.setClickable(false);
 }
 /**
  * 上一页按钮点击事件
  * @param view
  */
 public void lastPageDate(View view) {
//  setButtonAll(lastButton,nextButton);
  if (index > 1) {
   index--;
//   String url = "";
//   String string = httpToServiceSelectData(url);
//   listToData(string);//设置数据
   setPageButton(view);
  }
 }
 
 /**
  * 下一页按钮点击事件
  * @param view
  */
 public void nextPageDate(View view) {
//  setButtonAll(lastButton,nextButton);
  if (index < indexCount) {
   index++;
//   String url = "";
//   String string = httpToServiceSelectData(url);
//   listToData(string);//设置数据
   Toast.makeText(MainActivity.this, index+"", Toast.LENGTH_SHORT).show();//此处的index必须+“”,转换为字符串,否则报错
   System.out.println(index++);
   setPageButton(view);
  }
 }
}


 

 

 

JsonToList。java

 

public class JsonToList {
 public List<people> returnListView(String string) {
  java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<people>>(){}.getType();
  Gson gson = new Gson();
  List<people> list = gson.fromJson(string, type);
  return list;
 }
}

 

 

 

下面来看一下关于view的错误。例如上面的setPageButton(View view)方法变为setPageButton()就会报错。

 

view的空指针异常,listview加载数据底部添加按钮_第1张图片

你可能感兴趣的:(ListView)