我制作了可以从jsp服务器读取特定数据库的android应用程序。 例如,服务器上有各种数据库表,如时间,温度,湿度等。我喜欢在申请时显示时间和温度。我尝试了很多,Server显示正确的值,但它总是显示“无法读取临时值”。 这是我的代码。
UserFunctions.java
public class UserFunctions {
private static String readURL = "http://myip:8080/read.do";
public String read_email;
ArrayList tempList = new ArrayList( );
tempVO vo = null;
public boolean read_flag = false;
public boolean list_read_flag = false;
public boolean list_date_flag = false;
public class HttpFunctions {
public ArrayList readTemp(String email)
{
r_flag = false;
read_email = email;
new ReadHttpTask().execute();
while(!read_flag);
return tempList;
}
class ReadHttpTask extends AsyncTask<Void, Void, String>
{
@Override
protected String doInBackground(Void... voids) {
// TODO Auto-generated method stub
try{
HttpPost request = new HttpPost(readURL);
Vector<NameValuePair> nameValue = new Vector<NameValuePair>();
nameValue.add(new BasicNameValuePair("email", input_email));
HttpEntity enty = new UrlEncodedFormEntity(nameValue, HTTP.UTF_8);
request.setEntity(enty);
HttpClient client = new DefaultHttpClient();
HttpResponse res = client.execute(request);
//get a value from server
HttpEntity entityResponse = res.getEntity();
BufferedReader reader = new BufferedReader(new InputStreamReader(res.getEntity().getContent(),"utf-8"));
StringBuilder builder = new StringBuilder();
String str;
while ((str = reader.readLine()) != null){
if( str!=null && str.length() > 6 )
{
if (str.substring(0, 2).equals("data")) {
vo = new tempVO();
}
if (str.substring(0, 5).equals("read:")) {
vo.setDATA ( str.substring(6, str.length()) );
list_read_flag = true;
}
if (str.substring(0, 5).equals("date:")) {
vo.setDATA_DATE ( str.substring(6, str.length()) );
list_date_flag = true;
}
if(list_read_flag && list_date_flag)
{
dataList.add(vo);
list_date_flag = false;
list_read_flag = false;
}
}
}
read_flag = true;
}catch(UnsupportedEncodingException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
return null;
}
}
MainActivity.java
public class MainActivity extends Activity {
TextView txtView;
ArrayList tempList = new ArrayList( );
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.temp);
txtView = (TextView)findViewById(R.id.readtempdate);
txtView = (TextView)findViewById(R.id.readtemp);
Bundle intentRead = getIntent().getExtras();
String read_email = intentRead.getString("email");
UserFunctions userFunction = new UserFunctions();
tempList = userFunction.readtemp(read_email);
if(tempList.isEmpty())
{
Toast.makeText(MainActivity.this, "Fail to read temp values", Toast.LENGTH_LONG).show();
}
if( tempList!=null && tempList.size() > 0 )
{
for( int i = 0; i < tempList.size(); i++ )
{
tempVO tempvo = (tempVO)tempList.get(i);
txtView.append(tempvo.gettempDATA());
txtView.append(tempvo.gettempDATA_DATE());
}
}
}