Android : Fill ListView wtih different data from async requests

on Sunday, October 12, 2014


I need to make some async http requests and get data from json then parse it and fill the ListView with adapter (I've custom one). So my problem is that I do all requests I need in the onCreate method first time and everything works well! I mean that I do 3 requests and my ListView is fiiling with data from JSON of first request and of the third and then ListView has 2 rows with different data. But if I destroy my activity and open it again I've only 1 row in my ListView though Log.w shows me that all data has downloaded. Consider that I work with adapter incorrect but I have no ideas where it's wrong. Here is my code :



public class smActive extends Activity {
private static final String MY_SETTINGS = "my_settings";
final String token = "token";
public CustomListAdapter adapter;
String hasBeenShown;
boolean EmptyArray = false;
String url;
private ArrayList<BDItem> feedList = null;
private ListView feedListView = null;

protected void onCreate(Bundle sup) {
super.onCreate(sup);
setContentView(R.layout.request_activity);
SharedPreferences prefs = getSharedPreferences(MY_SETTINGS,
Context.MODE_PRIVATE);
hasBeenShown = prefs.getString(token, "null");
url = "http://api.check-host.ru/myauto/request/list/?token=" + hasBeenShown + "&type=2&status=1";
Log.w("urlOnCreate", url);

try {
new ActiveAccepted().getPublicTimeline("5");
} catch (JSONException e) {
e.printStackTrace();
}
try {
new ActiveAccepted().getPublicTimeline("4");
} catch (JSONException e) {
e.printStackTrace();
}
new DownloadFilesTask().execute(url);
// callAsynchronousTask(0);
Log.w("onCreate","created");

}

@Override
public void onResume(){
super.onResume();
Log.w("onResume","resumed");
// callAsynchronousTask(1);

}

@Override
public void onRestart(){
super.onRestart();
Log.w("onRestart","restarted");
// callAsynchronousTask(1);
}

@Override
public void onDestroy(){
super.onDestroy();
Log.w("onDestroy","destroyed");
// callAsynchronousTask(1);
}

@Override
protected void onStop(){
super.onStop();
Log.w("onStop","stop");
// callAsynchronousTask(1);
}

public void callAsynchronousTask(int stop) {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {

try {
new ActiveAccepted().getPublicTimeline("5");
} catch (JSONException e) {
e.printStackTrace();
Log.w("Empty request","no data with 5 status");
}
try {
new ActiveAccepted().getPublicTimeline("4");
} catch (JSONException e) {
e.printStackTrace();
Log.w("Empty request","no data with 4 status");
}

new DownloadFilesTask().execute(url);
}
});
}
};
if(stop==0) {
timer.schedule(doAsynchronousTask, 0, 8000); //execute in every 8000 ms
}
else if(stop == 1){
timer.cancel();
doAsynchronousTask.cancel();
Log.w("timer","cancelled");
}
}
public void updateList() {
feedListView = (ListView) findViewById(R.id.reqList);
if(feedListView.getAdapter() == null) {
try {
Log.w("adapter is null","Set new");
adapter = new CustomListAdapter(this, feedList);
feedListView.setAdapter(adapter);
} catch (Exception e) {
e.printStackTrace();
}
} else {

runOnUiThread(new Runnable() {
@Override
public void run() {
Log.w("notifyDataSetChanged","updateList happened");

adapter.notifyDataSetChanged();
feedListView.setAdapter(adapter); // added last
}
});

}
feedListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Object o = feedListView.getItemAtPosition(position);
BDItem newsData = (BDItem) o;
String reqNum = newsData.getNumber();
String mark = newsData.getMark();
String model = newsData.getModel();
String year = newsData.getYear();
String reason = newsData.getReason();
String upTime = newsData.getTime();
final String fpDate = upTime.split(" ")[0];
final String id = newsData.getNumber();
final TimePicker time = new TimePicker(smActive.this);
final String PredvMoney = "0.00";
time.setIs24HourView(true);

if(newsData.getStatus().equalsIgnoreCase("1")) {
new AlertDialog.Builder(smActive.this)
.setView(time)
.setMessage("Заказ номер: " + reqNum + "\nна текущее время\n" + mark + " " + model + "\n" + year + " год" + "\n" + reason + "\nВремя: ")
.setPositiveButton("Принять", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {

View main = getWindow().getDecorView().getRootView();
Log.w("время в пикере: ", time.getCurrentHour().toString() + ":" + time.getCurrentMinute().toString());
String sendTime = fpDate + "%20" + time.getCurrentHour().toString() + ":" + time.getCurrentMinute().toString();
Log.w("sendTime", sendTime);

try {
new MyAutoClientUsage().getPublicTimeline(id, sendTime, PredvMoney,"take");
} catch (JSONException e) {
e.printStackTrace();
}


}
})
.setNegativeButton("Отмена", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {


}
})
.show();
} else if (newsData.getStatus().equalsIgnoreCase("4")){

new AlertDialog.Builder(smActive.this)

.setMessage("Подтвердить прибытие машины?")
.setPositiveButton("Да", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {

View main = getWindow().getDecorView().getRootView();

try {
new CarArrived().getPublicTimeline(id);
} catch (JSONException e) {
e.printStackTrace();
}
try {
new ActiveAccepted().getPublicTimeline("5");
} catch (JSONException e) {
e.printStackTrace();
}

}
})
.setNegativeButton("Нет", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {


}
})
.show();
} else if (newsData.getStatus().equalsIgnoreCase("5")){
final EditText sum = new EditText(smActive.this);
sum.setHint("Введите сумму");
sum.setInputType(InputType.TYPE_CLASS_NUMBER);
new AlertDialog.Builder(smActive.this)
.setView(sum)
.setMessage("Укажите стоимость ремонта")
.setPositiveButton("Да", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {

View main = getWindow().getDecorView().getRootView();
String sumToSend = sum.getText().toString() + ".00";
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
String sendTime = fpDate + "%20" + currentDateandTime;
try {
new MyAutoClientUsage().getPublicTimeline(id, sendTime, sumToSend,"finish");
} catch (JSONException e) {
e.printStackTrace();
}
Log.w("sdf",currentDateandTime);

try {
new ActiveAccepted().getPublicTimeline("6");
} catch (JSONException e) {
e.printStackTrace();
}

}
})
.setNegativeButton("Нет", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {


}
})
.show();
}


}
});

}

public JSONObject getJSONFromUrl(String url) {
InputStream is = null;
JSONObject jObj = null;
String json = null;

// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
// HttpPost httpPost = new HttpPost(url);

HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;

}

public JSONArray getJSONArrayFromUrl(String url) {
InputStream is = null;
JSONArray jArr = null;
String json = null;

// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
// HttpPost httpPost = new HttpPost(url);

HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

try {
jArr = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jArr;

}

public void parseJson(JSONObject json) {
try {

// parsing json object
// if (json.getString("status").equalsIgnoreCase("ok")) {
JSONArray posts = json.getJSONArray("requests");

feedList = new ArrayList<BDItem>();
Log.w("LENGTH", "" + posts.length());
for (int i = 0; i < posts.length(); i++) {
JSONObject post = (JSONObject) posts.getJSONObject(i);
JSONObject jn = (JSONObject) post.getJSONObject(post.names().toString().replaceAll("\\[\"", "").replaceAll("\"\\]", ""));
Log.w("object", "" + jn);
BDItem item = new BDItem();
item.setNumber(jn.getString("request_id")); // номер заявки
item.setTime(jn.getString("request_cdate")); // время изменения заявки
item.setPhone(jn.getString("request_customer_phone")); // телефон
item.setFIO(jn.getString("request_customer_name")); // фио
// item.setSource(jn.getString("request_source_id")); // источник

item.setCarClass(jn.getString("request_car_class")); // класс машины
item.setMark(jn.getString("request_car_name")); // марка
if (jn.has("request_car_model") && jn.getString("request_car_model") != null) { // модель
item.setModel(jn.getString("request_car_model"));
}
item.setYear(jn.getString("request_car_manufactured")); // год
item.setReason(jn.getString("request_reason")); // причина обращения
if (jn.has("request_note") && jn.getString("request_note") != null) { //комментарий
item.setComment(jn.getString("request_note"));
}
item.setStatus(jn.getString("request_status")); // статус

if (jn.has("request_date_assigned") && jn.getString("request_date_assigned") != null) { // дата ремонта
item.setWorkDate(jn.getString("request_date_assigned"));
}
if (jn.has("request_cost_actual") && jn.getString("request_cost_actual") != null) { // стоимость
item.setCost(jn.getString("request_cost_actual"));
}
item.setWorkType(jn.getString("service_name")); // вид работ

feedList.add(item);

}
// }
} catch (JSONException e) {
e.printStackTrace();
}

}

private class DownloadFilesTask extends AsyncTask<String, Integer, Void> {

@Override
protected void onProgressUpdate(Integer... values) {
}

@Override
protected void onPostExecute(Void result) {

updateList();

}

@Override
protected Void doInBackground(String... params) {
String url = params[0];


try {
JSONObject json = getJSONFromUrl(url);

parseJson(json);
} catch (Exception e) {
JSONArray jsonArray = getJSONArrayFromUrl(url);
Log.w("Array","IS EMPTY!");
EmptyArray = true;


}
return null;
}
}

class MyAutoClientUsage {
public void getPublicTimeline(String id, String date, String cost,String type) throws JSONException {
MyAutoClient.get("myauto/request/"+type+"/?id=" + id + "&date=" + date + "&cost=" + cost+"&token="+hasBeenShown, null, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// If the response is JSONObject instead of expected JSONArray
JSONObject obj = response;
String result = null;
try {
result = obj.getString("result");
} catch (JSONException e) {
e.printStackTrace();
}


if (null != feedList) {
feedList.clear();
}
updateList();
Log.w("updateList","accepted");


try {
new ActiveAccepted().getPublicTimeline("4");
} catch (JSONException e) {
e.printStackTrace();
}

Log.w("result", result);
Log.w("принятие","проканало!");



}

@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
Log.w("OK","JSONArray");
}
});


}
}

class ActiveAccepted {
public void getPublicTimeline(String statNum) throws JSONException {
MyAutoClient.get("myauto/request/list/?token=" + hasBeenShown + "&type=2&status="+statNum, null, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// If the response is JSONObject instead of expected JSONArray
JSONObject obj = response;
String result = null;

parseJson(obj);
updateList();
Log.w("принятые заявки", obj.toString());
Log.w("теперь ","отображаются!");

}

@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
Log.w("Empty Array","JSONArray (seems like empty request or error)");
}
});


}
}

class CarArrived {
public void getPublicTimeline(String id) throws JSONException {
MyAutoClient.get("myauto/request/arrive/?id="+id+"&token="+hasBeenShown, null, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// If the response is JSONObject instead of expected JSONArray
JSONObject obj = response;
String result = null;
if(feedList !=null) {
feedList.clear();
}
parseJson(obj);
if (null != feedList) {
runOnUiThread(new Runnable() {
@Override
public void run() {
updateList();
}
});


}
Log.w("Машина приехала", obj.toString());
Log.w("Третий статус ","работает!)");




}

@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
Log.w("OK","JSONArray");
}
});


}
}
}


LogCat when I open Activity frist time: (tried to show that I take 2 rows but got only one (16) )



10-12 18:41:54.178 1850-1850/com.companyname.project13 W/urlOnCreate﹕ http://api.check-host.ru/myauto/request/list/?token=04cb3b78-4c95-11e4-9ba3-b5b879359f7c&type=2&status=1
10-12 18:41:54.190 1850-1850/com.companyname.project13 W/url﹕ myauto/request/list/?token=04cb3b78-4c95-11e4-9ba3-b5b879359f7c&type=2&status=5
10-12 18:41:54.194 1850-1850/com.companyname.project13 W/url﹕ myauto/request/list/?token=04cb3b78-4c95-11e4-9ba3-b5b879359f7c&type=2&status=4
10-12 18:41:54.198 1850-1850/com.companyname.project13 W/onCreate﹕ created
10-12 18:41:54.198 1850-1850/com.companyname.project13 W/onResume﹕ resumed
10-12 18:41:54.226 1850-1850/com.companyname.project13 W/EGL_emulation﹕ eglSurfaceAttrib not implemented
10-12 18:41:54.498 1850-1926/com.companyname.project13 W/LENGTH﹕ 1
10-12 18:41:54.502 1850-1926/com.companyname.project13 W/object﹕ {"service_id":"2","request_cost_actual":"250.00","request_status":"1","request_car_model":"23","request_date_assigned":"2014-09-24 15:20:00","request_car_name":"Нексиа","service_name":"Техн. обслуживание","request_note":"тестовый коммент","request_car_class":"B","request_reason":"Поменять подвеску и ещё что нибудь","request_car_manufactured":"1996","request_assigned_by":null,"request_updated":"2014-09-24 22:26:35","request_status_first":"1","request_date_actual":"2014-10-05 15:11:38","request_id":"16","request_cost_assigned":"0.00","request_customer_phone":"","request_customer_name":"Татьяна Те","request_source_id":"1","request_terminal_id":null,"request_customer_id":"4","request_cdate":"2014-10-06 16:14:53"}
10-12 18:41:54.502 1850-1850/com.companyname.project13 W/adapter is null﹕ Set new
10-12 18:41:54.562 1850-1850/com.companyname.project13 W/Empty Array﹕ JSONArray (seems like empty request or error)
10-12 18:41:54.562 1850-1850/com.companyname.project13 W/LENGTH﹕ 1
10-12 18:41:54.566 1850-1850/com.companyname.project13 W/object﹕ {"service_id":"2","request_cost_actual":"0.00","request_status":"5","request_car_model":"1","request_date_assigned":"2014-09-24 13:55:00","request_car_name":"1","service_name":"Техн. обслуживание","request_note":"1","request_car_class":"1","request_reason":"1","request_car_manufactured":"2001","request_assigned_by":null,"request_updated":"2014-09-24 22:19:08","request_status_first":"1","request_date_actual":null,"request_id":"29","request_cost_assigned":"0.00","request_customer_phone":"1","request_customer_name":"1","request_source_id":"1","request_terminal_id":"3","request_customer_id":"19","request_cdate":"2014-10-07 00:48:14"}
10-12 18:41:54.566 1850-1850/com.companyname.project13 W/notifyDataSetChanged﹕ updateList happened
10-12 18:41:54.566 1850-1850/com.companyname.project13 W/принятые заявки﹕ {"requests":[{"29":{"service_id":"2","request_cost_actual":"0.00","request_status":"5","request_car_model":"1","request_date_assigned":"2014-09-24 13:55:00","request_car_name":"1","service_name":"Техн. обслуживание","request_note":"1","request_car_class":"1","request_reason":"1","request_car_manufactured":"2001","request_assigned_by":null,"request_updated":"2014-09-24 22:19:08","request_status_first":"1","request_date_actual":null,"request_id":"29","request_cost_assigned":"0.00","request_customer_phone":"1","request_customer_name":"1","request_source_id":"1","request_terminal_id":"3","request_customer_id":"19","request_cdate":"2014-10-07 00:48:14"}}]}
10-12 18:41:54.566 1850-1850/com.companyname.project13 W/теперь﹕ отображаются!


LogCat when I open Activity the second time: ( ListView has one row again, but one another row (29))



10-12 18:42:22.557 1850-1850/com.companyname.project13 W/urlOnCreate﹕ http://api.check-host.ru/myauto/request/list/?token=04cb3b78-4c95-11e4-9ba3-b5b879359f7c&type=2&status=1
10-12 18:42:22.561 1850-1850/com.companyname.project13 W/url﹕ myauto/request/list/?token=04cb3b78-4c95-11e4-9ba3-b5b879359f7c&type=2&status=5
10-12 18:42:22.561 1850-1850/com.companyname.project13 W/url﹕ myauto/request/list/?token=04cb3b78-4c95-11e4-9ba3-b5b879359f7c&type=2&status=4
10-12 18:42:22.561 1850-1850/com.companyname.project13 W/onCreate﹕ created
10-12 18:42:22.561 1850-1850/com.companyname.project13 W/onResume﹕ resumed
10-12 18:42:22.593 1850-1850/com.companyname.project13 W/EGL_emulation﹕ eglSurfaceAttrib not implemented
10-12 18:42:22.653 1850-1850/com.companyname.project13 W/LENGTH﹕ 1
10-12 18:42:22.653 1850-1850/com.companyname.project13 W/object﹕ {"service_id":"2","request_cost_actual":"0.00","request_status":"5","request_car_model":"1","request_date_assigned":"2014-09-24 13:55:00","request_car_name":"1","service_name":"Техн. обслуживание","request_note":"1","request_car_class":"1","request_reason":"1","request_car_manufactured":"2001","request_assigned_by":null,"request_updated":"2014-09-24 22:19:08","request_status_first":"1","request_date_actual":null,"request_id":"29","request_cost_assigned":"0.00","request_customer_phone":"1","request_customer_name":"1","request_source_id":"1","request_terminal_id":"3","request_customer_id":"19","request_cdate":"2014-10-07 00:48:14"}
10-12 18:42:22.653 1850-1850/com.companyname.project13 W/adapter is null﹕ Set new
10-12 18:42:22.653 1850-1850/com.companyname.project13 W/принятые заявки﹕ {"requests":[{"29":{"service_id":"2","request_cost_actual":"0.00","request_status":"5","request_car_model":"1","request_date_assigned":"2014-09-24 13:55:00","request_car_name":"1","service_name":"Техн. обслуживание","request_note":"1","request_car_class":"1","request_reason":"1","request_car_manufactured":"2001","request_assigned_by":null,"request_updated":"2014-09-24 22:19:08","request_status_first":"1","request_date_actual":null,"request_id":"29","request_cost_assigned":"0.00","request_customer_phone":"1","request_customer_name":"1","request_source_id":"1","request_terminal_id":"3","request_customer_id":"19","request_cdate":"2014-10-07 00:48:14"}}]}
10-12 18:42:22.653 1850-1850/com.companyname.project13 W/теперь﹕ отображаются!
10-12 18:42:22.725 1850-1850/com.companyname.project13 W/Empty Array﹕ JSONArray (seems like empty request or error)
10-12 18:42:22.737 1850-1940/com.companyname.project13 W/LENGTH﹕ 1
10-12 18:42:22.737 1850-1940/com.companyname.project13 W/object﹕ {"service_id":"2","request_cost_actual":"250.00","request_status":"1","request_car_model":"23","request_date_assigned":"2014-09-24 15:20:00","request_car_name":"Нексиа","service_name":"Техн. обслуживание","request_note":"тестовый коммент","request_car_class":"B","request_reason":"Поменять подвеску и ещё что нибудь","request_car_manufactured":"1996","request_assigned_by":null,"request_updated":"2014-09-24 22:26:35","request_status_first":"1","request_date_actual":"2014-10-05 15:11:38","request_id":"16","request_cost_assigned":"0.00","request_customer_phone":"","request_customer_name":"Татьяна Те","request_source_id":"1","request_terminal_id":null,"request_customer_id":"4","request_cdate":"2014-10-06 16:14:53"}
10-12 18:42:22.741 1850-1850/com.companyname.project13 W/notifyDataSetChanged﹕ updateList happened


What I exactly want: make some requests like "http://api.check-host.ru/myauto/request/list/?token=04cb3b78-4c95-11e4-9ba3-b5b879359f7c&type=2&status=1" and "http://api.check-host.ru/myauto/request/list/?token=04cb3b78-4c95-11e4-9ba3-b5b879359f7c&type=2&status=5", get data from each other and put it in the ListView. Than work with every row personally as I do in setOnItemClickListener method. - Update my ListView every 8 seconds (now it's not important).


0 comments:

Post a Comment