Написал небольшую сетевую библиотеку под проект. Суть проблемы в том что Data всегда приходит null-ем.
Привожу полный листинг кода:
Вызов в MainActivity:
Data data = getSingleDataFromServer(); // всегда приходит null
NetWorker - непосредственно работа с сетью:
package com.rexhaif.netlib;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.*;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* Created by
*/
public class NetWorker {
private final String domain = "http://0.0.0.0/";
private final String scriptPath = "server.php";
private final String tokenParam = "&token=";
private String token = "lalala";
private final String datanumPram = "?datanum="; //номер возвращаемого значения
private String URL;
private void createURL(int datanum) throws Exception {
this.URL = "" + domain
+ "" + scriptPath
+ "" + datanumPram
+ "" + datanum
+ "" + tokenParam
+ "" + token
+ "";
}
/**
* Выполнение запроса к серверу
* @return Тело ответа сервера
* @throws Exception
*/
public String executeRequest(int datanum) throws Exception {
createURL(datanum);
HttpClient http = new DefaultHttpClient();
HttpGet request = new HttpGet(URL);
HttpResponse response;
HttpEntity entity;
response = http.execute(request);
entity = response.getEntity();
String result = "";
if (entity != null){
InputStream instream = entity.getContent();
result = inStreamToString(instream);
instream.close();
}
return result;
}
private String inStreamToString(InputStream in) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public Data toData(String str) throws Exception {
JSONObject json = new JSONObject(str);
String jsonTagLongitude = "long";
String jsonTagLatitude = "lati";
String jsonTagTime = "time";
String jsonTagTemp = "temp";
String jsonTagHumidity = "humid";
String jsonTagPressure = "press";
String jsonTagPanelTiling = "tilt";
String jsonTagPanelAzimuth = "azi";
String jsonTagPanelVoltage = "volts";
String jsonTagPanelElectricity = "currs";
String jsonTagWindmillVoltage = "voltv";
String jsonTagWindmillElectricity = "currv";
String jsonTagBatteryVoltage = "volta";
String jsonTagBatteryElectricity = "curra";
String jsonTagLoadVoltage = "voltn";
String jsonTagLoadElectricity = "currn";
String jsonValueLongitude = json.getString(jsonTagLongitude);
String jsonValueLatitude = json.getString(jsonTagLatitude);
String jsonValueTime = json.getString(jsonTagTime);
Double jsonValueTemp = Double.parseDouble(json.getString(jsonTagTemp));
Double jsonValueHumidity = Double.parseDouble(json.getString(jsonTagHumidity));
Double jsonValuePressure = Double.parseDouble(json.getString(jsonTagPressure));
Double jsonValuePanelTiling = Double.parseDouble(json.getString(jsonTagPanelTiling));
Double jsonValuePanelAzimuth = Double.parseDouble(json.getString(jsonTagPanelAzimuth));
Double jsonValuePanelVoltage = Double.parseDouble(json.getString(jsonTagPanelVoltage));
Double jsonValuePanelElectricity = Double.parseDouble(json.getString(jsonTagPanelElectricity));
Double jsonValueWindmillVoltage = Double.parseDouble(json.getString(jsonTagWindmillVoltage));
Double jsonValueWindmillElectricity = Double.parseDouble(json.getString(jsonTagWindmillElectricity));
Double jsonValueBatteryVoltage = Double.parseDouble(json.getString(jsonTagBatteryVoltage));
Double jsonValueBatteryElectricity = Double.parseDouble(json.getString(jsonTagBatteryElectricity));
Double jsonValueLoadVoltage = Double.parseDouble(json.getString(jsonTagLoadVoltage));
Double jsonValueLoadElectricity = Double.parseDouble(json.getString(jsonTagLoadElectricity));
//конвертация даты из вида "2015.02.01 10.28.17"
String[] splitedTime = new String[6];
String[] preSplit = jsonValueTime.split("\\.");
String[] dayHourSplit = preSplit[2].split("\\s+");
splitedTime[0] = preSplit[0];
splitedTime[1] = preSplit[1];
splitedTime[2] = dayHourSplit[0];
splitedTime[3] = dayHourSplit[1];
splitedTime[4] = preSplit[3];
splitedTime[5] = preSplit[4];
long convertedGPSYear = Long.parseLong(splitedTime[0]);
long convertedGPSMonth = Long.parseLong(splitedTime[1]);
long convertedGPSDay = Long.parseLong(splitedTime[2]);
long convertedGPSHour = Long.parseLong(splitedTime[3]);
long convertedGPSMin = Long.parseLong(splitedTime[4]);
long convertedGPSSec = Long.parseLong(splitedTime[5]);
return new Data(
jsonValueLongitude,
jsonValueLatitude,
convertedGPSYear,
convertedGPSMonth,
convertedGPSDay,
convertedGPSHour,
convertedGPSMin,
convertedGPSSec,
jsonValueTemp,
jsonValueHumidity,
jsonValuePressure,
jsonValuePanelTiling,
jsonValuePanelAzimuth,
jsonValuePanelVoltage,
jsonValuePanelElectricity,
jsonValueWindmillVoltage,
jsonValueWindmillElectricity,
jsonValueBatteryVoltage,
jsonValueBatteryElectricity,
jsonValueLoadVoltage,
jsonValueLoadElectricity
);
}
}
DataHelper - обертка над NetWorker-ом
package com.rexhaif.netlib;
import android.os.AsyncTask;
/**
* Created by
*/
public class DataHelper {
private class SingleDataGetTask extends AsyncTask<Void, Void, Data>{
@Override
protected Data doInBackground(Void... params) {
NetWorker networker = new NetWorker();
try {
return networker.toData(networker.executeRequest(1));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
private class MultipleDataGetTask extends AsyncTask<Integer, Void, Data[]>{
@Override
protected Data[] doInBackground(Integer... params) {
NetWorker networker = new NetWorker();
try {
Data[] result = new Data[params[0]];
for (int i = 1; i <= params[0]; ++i){
result[i - 1] = networker.toData(networker.executeRequest(i));
}
return result;
} catch (Exception e) {
e.printStackTrace();
}
return new Data[0];
}
}
/**
* Асинхронное получение одной записи с сервера
* @return Самая новая запись, имеющаяся на сервере.
* @throws java.lang.Exception
*/
public Data getSingleDataFromServer() throws Exception {
SingleDataGetTask getTask = new SingleDataGetTask();
getTask.execute();
return getTask.get();
}
/**
* Асинхронное получение с сервера от 1 до 5 самых новых записей
* @param datanum количество получаемых записей
* @return Массив data[] из самых новых записей, упорядоченных по времени
* где data[0] - самая новая запись, а data[ от 1 - 4 ] последующие в порядке устаревания
* @throws java.lang.Exception
*/
public Data[] getMultipleDataFromServer(Integer datanum) throws Exception {
MultipleDataGetTask getTask = new MultipleDataGetTask();
getTask.execute();
return getTask.get();
}
}