Android Studio, there's an error retrieving schedule information - java

Currently, I have to click on the screen to get the schedule information.
I think the calender and db are loaded at the same time, but the speed at which db is loaded is slow, so it doesn't appear on the calendar right away.
But when I enter the schedule screen, I want to have the schedule information from DB appear at the bottom.
Calendar Activity: Connect to the calendar adapter and load data from the DB. When I checked on the console, the DB information is immediately imported when you enter the schedule screen.
Calendar Adapter : Bind data to the created ViewHolder, color on date (BLUE)
`
public class CalendarActivity extends AppCompatActivity implements CalendarAdapter.OnItemListener
{
#Override
protected void onCreate(Bundle savedInstanceState) {
initWidgets();
CalendarUtils.selectedDate = LocalDate.now();
setMonthView();
// get data from DB
GetData task = new GetData();
task.execute(userID);
}
private void setMonthView() {
//년 월 텍스트뷰
monthYearText.setText(monthYearFromDate(CalendarUtils.selectedDate));
//해당 월 날짜 가져오기
ArrayList<LocalDate> daysInMonth = daysInMonthArray(CalendarUtils.selectedDate);
CalendarAdapter calendarAdapter = new CalendarAdapter(daysInMonth, this);
//레이아웃 설정, 열 7개
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 7);
calendarRecyclerView.setLayoutManager(layoutManager);
calendarRecyclerView.setAdapter(calendarAdapter);
setEventAdapter();
}
// 이벤트 Adapter 제공
private void setEventAdapter() {
//ID 로 목록 찾고 리스트 호출
ArrayList<Event> dailyEvents = eventsForDate(CalendarUtils.selectedDate);
EventAdapter eventAdapter = new EventAdapter(this, this, dailyEvents);
eventListView.setAdapter(eventAdapter);
}
// 새로운 이벤트 생성
public void newEventAction(View view) {
startActivity(new Intent(CalendarActivity.this, EventEditActivity.class));
}
// 재개될 때마다 다시 로드되도록 EventAdapter 호출
//Activity가 사용자와 상호작용하기 바로 전에 호출됨
#Override
protected void onResume() {
super.onResume();
setEventAdapter();
eventsList.clear();
}
// 주어진 날짜에 대한 모든 이벤트 반환
public static ArrayList<Event> eventsForDate(LocalDate date) {
events = new ArrayList<>();
for (int k = 0; k < eventsList.size(); k++) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String selectDate1 = date.toString(); //현재누른날짜
String startDate1 = eventsList.get(k).getStartdate(); //시작날짜
String endDate1 = eventsList.get(k).getEnddate(); //종료날짜
Date selectDate = null;
try {
selectDate = dateFormat.parse(selectDate1);
Date startDate = dateFormat.parse(startDate1);
Date endDate = dateFormat.parse(endDate1);
int result1 = selectDate.compareTo(startDate); // curr > d1
int result2 = selectDate.compareTo(endDate);
// 조건이 맞을때
if ((result1 >= 0) && (result2 <= 0)) //선택한 날짜가 시작날짜랑 같거나 크고 & 앤드날짜보다 작거나 같으면
events.add(eventsList.get(k)); //items.get(k)가 events 어레이에 더해짐
} catch (ParseException e) {
e.printStackTrace();
}
}
return events;
}
// 주어진 날짜에 대한 ID 반환 - 수정인지 판단
public static int eventsForID(String passedID) {
for (int i = 0; i < eventsList.size(); i++) {
String ID = eventsList.get(i).getID();
if(ID != null && passedID != null) {
//각각 일치하면 0 리턴하므로 합계 0일경우 모두 일치한다.
if (passedID.compareTo(ID)== 0) {
Log.e("compare", "ok");
return 1;
}
}
}
return 0;
}
// DB에서 이벤트 가져오기
class GetData extends AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
String errorString = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(CalendarActivity.this,
"Please Wait", null, true, true);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
Log.d(TAG, "response - " + result);
if (result != null) {
mJsonString = result;
showResult();
}
}
#Override
protected String doInBackground(String... params) {
String searchKeyword1 = params[0];
String serverURL = "http://"+IP_ADDRESS+"/event_query.php";
String postParameters = "userID=" + searchKeyword1;
Log.d(TAG, "userID_event : " + searchKeyword1);
try {
URL url = new URL(serverURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(5000);
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.connect();
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(postParameters.getBytes("UTF-8"));
outputStream.flush();
outputStream.close();
int responseStatusCode = httpURLConnection.getResponseCode();
Log.d(TAG, "response code - " + responseStatusCode);
InputStream inputStream;
if (responseStatusCode == HttpURLConnection.HTTP_OK) {
inputStream = httpURLConnection.getInputStream();
} else {
inputStream = httpURLConnection.getErrorStream();
}
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
return sb.toString().trim();
} catch (Exception e) {
Log.d(TAG, "getData: Error ", e);
errorString = e.toString();
return null;
}
}
// DB에서 array로 데이터 가져옴
public void showResult() {
try {
JSONObject jsonObject = new JSONObject(mJsonString);
JSONArray jsonArray = jsonObject.getJSONArray(TAG_JSON);
// eventsList에 저장하기 전 저장되어있던 List를 clear한 후 가져온다
eventsList.clear();
for (int i = 0; i < jsonArray.length(); i++) {
if (jsonArray.length() != 0) {
JSONObject item = jsonArray.getJSONObject(i);
Log.d(TAG, "JSONObject : " + item);
// 해당 키워드로 DB에서 데이터를 가져온다(ID, title...)
ID = item.getString("ID");
title = item.getString("title");
startdate = item.getString("startdate");
enddate = item.getString("enddate");
alarmactive = item.getString("alarmactive");
// 가져온 데이터 eventsList에 저장
eventsList.add(new Event(ID, title, startdate, enddate, alarmactive));
Log.d(TAG, "eventsList : " + eventsList.toString());
}
}
} catch (JSONException e) {
Log.d(TAG, "showResult_member : ", e);
}
}
}
}
`
`
class CalendarAdapter extends RecyclerView.Adapter<CalendarViewHolder>
{
private final ArrayList<LocalDate> days;
private final OnItemListener onItemListener;
#NonNull
#Override
public CalendarViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.calendar_cell, parent, false);
ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
layoutParams.height = (int) (parent.getHeight() * 0.199999999); //월별 달력
return new CalendarViewHolder(view, onItemListener, days);
}
// 생성된 ViewHolder 에 데이터 바인딩
#Override
public void onBindViewHolder(#NonNull CalendarViewHolder holder, int position)
{
//날짜 변수에 담기
final LocalDate date = days.get(position);
if (date == null)
//날짜가 null인 경우 홀더 날짜를 설정
holder.dayOfMonth.setText("");
else {
//그렇지 않으면 날짜 넣기
holder.dayOfMonth.setText(String.valueOf(date.getDayOfMonth()));
//선택한 날짜 회색으로 표시
if (date.equals(CalendarUtils.selectedDate)) {
holder.parentView.setBackgroundColor(Color.LTGRAY);
}
//주말 색상 지정(토요일: BLUE, 일요일: RED)
if ((position + 1) % 7 == 0) {
holder.dayOfMonth.setTextColor(Color.BLUE);
} else if (position == 0 || position % 7 == 0) {
holder.dayOfMonth.setTextColor(Color.RED);
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
for (int i = 0; CalendarActivity.eventsList.size()>i ; i++) {
Event CalendarDate1 = CalendarActivity.eventsList.get(i);
Date curr = dateFormat.parse(date.toString());
// yyyy-MM-dd
Date d1 = dateFormat.parse(CalendarDate1.startdate);
Date d2 = dateFormat.parse(CalendarDate1.enddate);
int result1 = curr.compareTo(d1); // curr > d1
int result2 = curr.compareTo(d2);
// BLUE
if ((result1 >= 0) && (result2 <= 0))
holder.parentView.setBackgroundColor(Color.parseColor("#83BBF3"));
}
}
catch (ParseException e) {
e.printStackTrace();
}
}
}
// 전체 데이터 개수 return
#Override
public int getItemCount()
{
return days.size();
}
public interface OnItemListener
{
//해당 변수 이름은 현재날짜로 변경됨
void onItemClick(int position, LocalDate date);
}
}
`
I've moved the GetData function to another activity.
Because the code to update the data is in the calendar activity, the data is imported when the calendar is first turned on, but it cannot be modified and deleted.

Related

Lisview inside a Listview not working

I am making an android app that shows weather using OWM 5day 3hour forecast API, The ui consists of EditText to input a city name, a button to initiate the call process, a listview that will display 5 entries (five days) and each day entry includes another listview that displays decription and temperature for every 3 hours in a day,
I am able to see the listview for days but cannot see the nested listview for the hourly data. My classes include : MainActivity, WeatherAdapter to show 3hourly weather, DayAdapter to show day entries, and JsonToWeather data class that extracts data out of the Json response and make an Arraylist of data for only one particular day. I tried to log the error and highlighted the error position by a comment.
MainActivity :
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private String responseJSON = null;
ListView listView;
ArrayList<WeatherData> weatherDataArrayList;
WeatherAdapter weatherAdapter = null;
EditText cityName;
String city = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.dayList);
cityName = (EditText) findViewById(R.id.cityName);
Button load = (Button) findViewById(R.id.loadButton);
load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
city = cityName.getText().toString();
Log.d(TAG, "onClick: city is : " + city);
if(city == null){
Toast toast = null;
toast.makeText(MainActivity.this,"Please Enter a city before continuing",Toast.LENGTH_LONG);
toast.show();
} else {
String url = "http://api.openweathermap.org/data/2.5/forecast?q=" + (city.toLowerCase()) + "&units=metric&appid=8b10912e19fde267f36f6cb785ee7efd";
Log.d(TAG, "onCreate: staring download task");
DownloadJSON downloadJSON = new DownloadJSON();
downloadJSON.execute(url);
Log.d(TAG, "onCreate: after downloadtask");
}
}
});
if(weatherDataArrayList == null){
Log.d(TAG, "onCreate: ArrayList is Still null");
}
}
private class DownloadJSON extends AsyncTask<String, Void, String>{
private static final String TAG = "DownloadJSON";
private String downloadJSON(String url){
StringBuilder jsonResult = new StringBuilder();
try{
URL apiURL = new URL(url);
HttpURLConnection connection = (HttpURLConnection) apiURL.openConnection();
int responseCode = connection.getResponseCode();
Log.d(TAG, "downloadJSON: Response code "+ responseCode);
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
int charReader;
char[] inputBuffer = new char[500];
while(true){
charReader = reader.read(inputBuffer);
if(charReader < 0){
break;
}
if(charReader > 0){
jsonResult.append(String.copyValueOf(inputBuffer, 0, charReader));
}
}
reader.close();
return jsonResult.toString();
}catch (MalformedURLException e){
Log.e(TAG, "downloadJSON: URL is Invalid");
}catch (IOException e){
Log.e(TAG, "downloadJSON: IO Error");
}
return null;
}
#Override
protected String doInBackground(String... strings) {
Log.d(TAG, "doInBackground: url is : " + strings[0]);
String jsonResponse = downloadJSON(strings[0]);
if(jsonResponse == null){
Log.e(TAG, "doInBackground: Error downloading");
}
return jsonResponse;
}
#Override
protected void onPostExecute(String jsonResponse) {
super.onPostExecute(jsonResponse);
Log.d(TAG, "onPostExecute: json received is : " + jsonResponse);
if(jsonResponse != null){
JsonToWeatherData jtwd = new JsonToWeatherData();
weatherDataArrayList = jtwd.extractor(jsonResponse);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
String date1 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date2 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date3 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date4 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date5 = simpleDateFormat.format(calendar.getTime());
ArrayList<String> days = new ArrayList<>();
days.add(date1);
days.add(date2);
days.add(date3);
days.add(date4);
days.add(date5);
DayAdapter day = new DayAdapter(MainActivity.this,R.layout.layout_day_card,days,weatherDataArrayList);
listView.setAdapter(day);
} else {
Log.d(TAG, "onPostExecute: no json recieved, city is Wrong");
Toast toast = Toast.makeText(MainActivity.this,"Please provide a valid city!",Toast.LENGTH_LONG);
toast.show();
}
}
}
}
WeatherAdapter :
public class WeatherAdapter extends ArrayAdapter<WeatherData> {
private static final String TAG = "WeatherAdapter";
private final int layoutResourceID;
private LayoutInflater layoutInflater;
private ArrayList<WeatherData> block;
public WeatherAdapter(#NonNull Context context, int resource, ArrayList<WeatherData> block) {
super(context, resource, block);
this.layoutResourceID = resource;
this.block = block;
this.layoutInflater = LayoutInflater.from(context);
Log.d(TAG, "WeatherAdapter: called constructor");
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
if(convertView == null){
convertView = layoutInflater.inflate(layoutResourceID,parent,false);
}
Log.d(TAG, "getView: entered");
WeatherData weatherData = block.get(position);
TextView temp = (TextView) convertView.findViewById(R.id.temperature);
temp.setText(weatherData.getTemp());
TextView shortDesc = (TextView) convertView.findViewById(R.id.descrip);
shortDesc.setText(weatherData.getShortDesc());
return convertView;
}
}
DayAdapter :
public class DayAdapter extends ArrayAdapter<String> {
private static final String TAG = "DayAdapter";
private ArrayList<String> dayBlock;
private LayoutInflater layoutInflater;
private int layoutresourceID;
private ArrayList<WeatherData> dayWeather, fullBlock;
private Context context;
JsonToWeatherData json = new JsonToWeatherData();
public DayAdapter(#NonNull Context context, int resource, #NonNull ArrayList<String> dayBlock, ArrayList<WeatherData> weatherBlock) {
super(context, resource, dayBlock);
this.context = context;
this.dayBlock = dayBlock;
this.fullBlock = weatherBlock;
layoutInflater = LayoutInflater.from(context);
this.layoutresourceID = resource;
if(fullBlock == null){
Log.e(TAG, "DayAdapter: full block is null");
}
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
if (convertView == null){
convertView = layoutInflater.inflate(layoutresourceID,parent,false);
}
TextView date = (TextView) convertView.findViewById(R.id.date);
TextView minTempFoDay = (TextView) convertView.findViewById(R.id.minTempOfDay);
TextView maxTempFoDay = (TextView) convertView.findViewById(R.id.maxTempOfDay);
ListView weatherHolderListView = (ListView) convertView.findViewById(R.id.wHoldLV);
String dateString = dayBlock.get(position);
dayWeather = json.extractByDate(fullBlock,dateString);
if(fullBlock == null){
Log.d(TAG, "getView: fullblock is null");
}
if(dayWeather == null){
Log.d(TAG, "getView: dayweather array is null");
} else {
Log.d(TAG, "getView: dayweather is not null");
}
String test = dayWeather.get(position).getTemp(); // error occured here
Log.d(TAG, "getView: test string : " + test);
date.setText(dateString);
DecimalFormat df = new DecimalFormat(".##");
float mint = 500, maxt = 0;
String mint1 = "", maxt1 = "";
for(WeatherData data : dayWeather){
if(mint > Float.parseFloat(data.getMinTemp())){
mint = Float.parseFloat(data.getMinTemp());
mint1 = df.format(mint);
Log.d(TAG, "getView: mint : " + mint);
}
if (maxt > Float.parseFloat(data.getMaxTemp())){
maxt = Float.parseFloat(data.getMaxTemp());
maxt1 = df.format(maxt);
}
}
minTempFoDay.setText(mint1);
maxTempFoDay.setText(maxt1);
WeatherAdapter weatherAdapter = new WeatherAdapter(context,R.layout.weather_holder,dayWeather);
weatherHolderListView.setAdapter(weatherAdapter);
return convertView;
}
}
JsonToWeatherData:
public class JsonToWeatherData {
private static final String TAG = "JsonToWeatherData";
public ArrayList<WeatherData> extractor(String jsonData){
Log.d(TAG, "extractor: in the method");
if(jsonData == null){
return null; // if there is no json data is received
} else {
ArrayList<WeatherData> weatherDataArrayList = new ArrayList<WeatherData>();
Log.d(TAG, "extractor: in the else field");
try{
Log.d(TAG, "extractor: in try block");
JSONObject root = new JSONObject(jsonData);
int count = root.getInt("cnt");
JSONArray wList = root.getJSONArray("list");
for (int i = 0; i < count; ++i){
WeatherData weather = new WeatherData();
JSONObject wBlock = wList.getJSONObject(i);
weather.setDate(wBlock.getString("dt_txt"));
JSONObject mainObj = wBlock.getJSONObject("main");
weather.setTemp(String.valueOf(mainObj.getDouble("temp")));
weather.setMinTemp(String.valueOf(mainObj.getDouble("temp_min")));
weather.setMaxTemp(String.valueOf(mainObj.getDouble("temp_max")));
weather.setHumidity(String.valueOf(mainObj.getInt("humidity")));
JSONArray warray = wBlock.getJSONArray("weather");
JSONObject weatherObj = warray.getJSONObject(0);
weather.setDescription(weatherObj.getString("description"));
weather.setShortDesc(weatherObj.getString("main"));
weather.setIconID(weatherObj.getString("icon"));
weatherDataArrayList.add(weather);
Log.d(TAG, "extractor: temp field is :" + weather.getTemp());
}
}catch (JSONException e){
e.printStackTrace();
}
return weatherDataArrayList;
}
}
public ArrayList<WeatherData> extractByDate(ArrayList<WeatherData> fullList,String date){
ArrayList<WeatherData> dayweatherList = new ArrayList<WeatherData>();
for( WeatherData weather : fullList ){
if( ( weather.getDate().substring(0,9) ).equals(date) ){
dayweatherList.add(weather);
}
}
return dayweatherList;
}
}
What should I do?
Error message : (
08-19 23:11:39.914 12148-12148/com.jugalmistry.apps.fivedaysofweather D/DayAdapter: getView: dayweather is not null
08-19 23:11:39.916 12148-12148/com.jugalmistry.apps.fivedaysofweather D/AndroidRuntime: Shutting down VM
08-19 23:11:39.918 12148-12148/com.jugalmistry.apps.fivedaysofweather E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.jugalmistry.apps.fivedaysofweather, PID: 12148
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:411)
at com.jugalmistry.apps.fivedaysofweather.DayAdapter.getView(DayAdapter.java:58)
I have attempted to help you with the full code below.
I would also recommend you implement the ViewHolder pattern ViewHolder pattern example for increased performance.
public class MainActivity extends AppCompatActivity
{
private static final String TAG = "MainActivity";
EditText cityName;
String city = null;
ListView dayListView;
ArrayList<WeatherData> weatherDataArrayList;
DayAdapter dayAdapter;
//private String responseJSON = null;
//WeatherAdapter weatherAdapter = null; // Creating this adapter within the DayAdapter
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityName = (EditText) findViewById(R.id.cityName);
Button load = (Button) findViewById(R.id.loadButton);
dayListView = (ListView) findViewById(R.id.dayList);
load.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
city = cityName.getText().toString();
Log.d(TAG, "onClick: city is : " + city);
if (city == null)
{
Toast toast = null;
toast.makeText(MainActivity.this,"Please Enter a city before continuing",Toast.LENGTH_LONG);
toast.show();
}
else
{
String url = "http://api.openweathermap.org/data/2.5/forecast?q=" + (city.toLowerCase()) + "&units=metric&appid=8b10912e19fde267f36f6cb785ee7efd";
Log.d(TAG, "onCreate: staring download task");
DownloadJSON downloadJSON = new DownloadJSON();
downloadJSON.execute(url);
Log.d(TAG, "onCreate: after downloadtask");
}
}
});
}
public void SetDayListData(ArrayList<String> dayBlock, ArrayList<WeatherData> weatherBlock)
{
if (dayAdapter == null)
{
dayAdapter = new DayAdapter(MainActivity.this,R.layout.layout_day_card, days, weatherDataArrayList);
dayListView.setAdapter(dayAdapter);
}
else
{
//created a new method "UpdateData" just to update the data in the adapter
dayAdapter.UpdateData(days, weatherDataArrayList);
dayAdapter.notifyDataSetChanged();
}
}
private class DownloadJSON extends AsyncTask<String, Void, String>
{
private static final String TAG = "DownloadJSON";
private String downloadJSON(String url)
{
StringBuilder jsonResult = new StringBuilder();
try
{
URL apiURL = new URL(url);
HttpURLConnection connection = (HttpURLConnection) apiURL.openConnection();
int responseCode = connection.getResponseCode();
Log.d(TAG, "downloadJSON: Response code "+ responseCode);
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
int charReader;
char[] inputBuffer = new char[500];
while (true)
{
charReader = reader.read(inputBuffer);
if (charReader < 0)
{
break;
}
if (charReader > 0)
{
jsonResult.append(String.copyValueOf(inputBuffer, 0, charReader));
}
}
reader.close();
return jsonResult.toString();
}
catch (MalformedURLException e)
{
Log.e(TAG, "downloadJSON: URL is Invalid");
}
catch (IOException e)
{
Log.e(TAG, "downloadJSON: IO Error");
}
return null;
}
#Override
protected String doInBackground(String... strings)
{
Log.d(TAG, "doInBackground: url is : " + strings[0]);
String jsonResponse = downloadJSON(strings[0]);
if (jsonResponse == null)
{
Log.e(TAG, "doInBackground: Error downloading");
}
return jsonResponse;
}
#Override
protected void onPostExecute(String jsonResponse)
{
super.onPostExecute(jsonResponse);
Log.d(TAG, "onPostExecute: json received is : " + jsonResponse);
if (jsonResponse != null)
{
JsonToWeatherData jtwd = new JsonToWeatherData();
weatherDataArrayList = jtwd.extractor(jsonResponse);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
String date1 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date2 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date3 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date4 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date5 = simpleDateFormat.format(calendar.getTime());
ArrayList<String> days = new ArrayList<>();
days.add(date1);
days.add(date2);
days.add(date3);
days.add(date4);
days.add(date5);
SetDayListData(days, weatherDataArrayList);
}
else
{
Log.d(TAG, "onPostExecute: no json recieved, city is Wrong");
Toast toast = Toast.makeText(MainActivity.this,"Please provide a valid city!",Toast.LENGTH_LONG);
toast.show();
}
}
}
}
public class DayAdapter extends ArrayAdapter<String>
{
private static final String TAG = "DayAdapter";
private Context context;
private LayoutInflater layoutInflater;
private int layoutresourceID;
private ArrayList<String> dayBlock;
private ArrayList<WeatherData> dayWeather, weatherBlock;
JsonToWeatherData json = new JsonToWeatherData();
public DayAdapter(#NonNull Context context, int resource, #NonNull ArrayList<String> dayBlock, ArrayList<WeatherData> weatherBlock)
{
super(context, resource, dayBlock);
this.context = context;
this.dayBlock = dayBlock;
this.weatherBlock = weatherBlock;
layoutInflater = LayoutInflater.from(context);
this.layoutresourceID = resource;
if (weatherBlock == null)
{
Log.e(TAG, "DayAdapter: full block is null");
}
}
#Override
public int getCount()
{
return dayBlock.getSize();
}
public void UpdateData(#NonNull ArrayList<String> dayBlock, ArrayList<WeatherData> weatherBlock)
{
this.dayBlock = dayBlock;
this.weatherBlock = weatherBlock;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent)
{
if (convertView == null)
{
convertView = layoutInflater.inflate(layoutresourceID,parent,false);
}
if (weatherBlock == null)
{
Log.d(TAG, "getView: weatherBlock is null");
return convertView;
}
TextView date = (TextView) convertView.findViewById(R.id.date);
TextView minTempFoDay = (TextView) convertView.findViewById(R.id.minTempOfDay);
TextView maxTempFoDay = (TextView) convertView.findViewById(R.id.maxTempOfDay);
ListView weatherHolderListView = (ListView) convertView.findViewById(R.id.wHoldLV);
String dateString = dayBlock.get(position);
dayWeather = json.extractByDate(weatherBlock, dateString);
if (dayWeather == null)
{
Log.d(TAG, "getView: dayweather array is null");
return convertView;
}
if (position > dayWeather.getSize() - 1)
{
Log.d(TAG, "getView: the position is too great for the dayWeather array");
return convertView;
}
String test = dayWeather.get(position).getTemp(); // error occured here
Log.d(TAG, "getView: test string : " + test);
date.setText(dateString);
DecimalFormat df = new DecimalFormat(".##");
float mint = 500, maxt = 0;
String mint1 = "", maxt1 = "";
for (WeatherData data : dayWeather)
{
if (mint > Float.parseFloat(data.getMinTemp()))
{
mint = Float.parseFloat(data.getMinTemp());
mint1 = df.format(mint);
Log.d(TAG, "getView: mint : " + mint);
}
if (maxt > Float.parseFloat(data.getMaxTemp()))
{
maxt = Float.parseFloat(data.getMaxTemp());
maxt1 = df.format(maxt);
}
}
minTempFoDay.setText(mint1);
maxTempFoDay.setText(maxt1);
WeatherAdapter weatherAdapter = new WeatherAdapter(context, R.layout.weather_holder, dayWeather);
weatherHolderListView.setAdapter(weatherAdapter);
return convertView;
}
}

String time passed from AsyncTask class variable not converting into date object in android but it works fine when i hard code the sting

String time passed from AsyncTask class variable not converting into date object in android but it works fine when i hard code the string.
public class Main2Activity extends AppCompatActivity {
String getdate, getday, gethijri, gettimezone, getfajr, getsunrise, getduhr, getasr, getsunset, getmaghrib, getisha, getimsak;
public static final String inputFormat = "hh:mm";
SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat);
String compareFajrOne = "";
String compareFajrTwo = "";
private Date date;
private Date dateComparefajrOne;
private Date dateComparefajrTwo;
private Date dateCompareishaTwo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dailynamazrecord);
Button fajrofer = (Button) findViewById(R.id.fajrada);
final boolean[] ispressed = {false};
Calendar now = Calendar.getInstance();
final int hour = now.get(Calendar.HOUR);
final int minute = now.get(Calendar.MINUTE);
date = parseDateeb(Integer.toString(hour)+":"+ Integer.toString(minute));
dateComparefajrOne = parseDateeb(compareFajrOne);
dateComparefajrTwo = parseDateeb(compareFajrTwo);
fajrofer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext, compareFajrOne+"\n"+compareFajrTwo+"\n"+dateComparefajrOne+"\n"+date+"\n"+dateComparefajrTwo, Toast.LENGTH_LONG).show();
if ( dateComparefajrOne.before(date)&& dateComparefajrTwo.after(date)) {
if (ispressed[0]) {
fajrofer.setBackgroundResource(R.drawable.namazoffered);
} else {
fajrofer.setBackgroundResource(R.drawable.ofeer);
}
ispressed[0] = !ispressed[0];
} else {
if (p != null)
showPopup(Main2Activity.this, p);
}
}
});
public class FectchDetails2 extends AsyncTask<String, String, String> {
String data = "";
#Override
protected String doInBackground(String... params) {
URL url = null;
try {
url = new URL("http://api.aladhan.com/v1/timingsByCity?city=Karachi&country=Pakistan&method=8");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line != null) {
line = bufferedReader.readLine();
data = data + line;
}
JSONObject json = new JSONObject(data);
JSONObject gtimings=json2.getJSONObject("timings");
getfajr = gtimings.getString("Fajr");
getsunrise = gtimings.getString("Sunrise");
getduhr = gtimings.getString("Dhuhr");
getasr = gtimings.getString("Asr");
getsunset = gtimings.getString("Sunset");
getmaghrib = gtimings.getString("Maghrib");
getisha = gtimings.getString("Isha");
getimsak = gtimings.getString("Imsak");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
compareStringOne=getfajr.toString();
compareStringTwo=getsunrise.toString();
}
}
private Date parseDateeb(String date) {
try {
return inputParser.parse(date);
} catch (java.text.ParseException e) {
return new Date(0);
}
}
}
String time passed from AsyncTask class variable not converting into date object in android but it works fine when i hard code the sting.
like:
String compareFajrOne = "05:18";
String compareFajrTwo = "06:40";
Kindly guide me i just want to check that current time is in the range of given times

Cannot set value to textview in runonuithread

public class PerformanceDashboard extends MotherActivity {
String dashboardData;
int SELECTED_PAGE, SEARCH_TYPE, TRAY_TYPE;
List<String[]> cachedCounterUpdates = new ArrayList<String[]>();
List<DasDetails> docList = new ArrayList<DasDetails>();
ListView listViewDashboard;
DataAdapter dataAdap = new DataAdapter();
TextView noOfItems, userCount, totalLoginTime;
int itemsTotal = 0, userTotal = 0, totalTime = 0;
String KEYWORD = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (App.isTestVersion) {
Log.e("actName", "StoreOut");
}
if (bgVariableIsNull()) {
this.finish();
return;
}
setContentView(R.layout.dashboard);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setProgressBarIndeterminateVisibility(false);
lytBlocker = (LinearLayout) findViewById(R.id.lyt_blocker);
listViewDashboard = (ListView) findViewById(R.id.dashboard_listview);
noOfItems = ((TextView) findViewById(R.id.noOfItems));
userCount = ((TextView) findViewById(R.id.userCount));
totalLoginTime = ((TextView) findViewById(R.id.totalLoginTime));
new DataLoader().start();
listViewDashboard.setAdapter(dataAdap);
System.out.println("PerformanceDashboard. onCreate processOutData() -- item total " + itemsTotal); //0 i am not getting that adapter value i.e. 6
System.out.println("PerformanceDashboard. onCreate processOutData() -- user total " + userTotal); //0 i am not getting that adapter value i.e. 4
System.out.println("PerformanceDashboard. onCreate processOutData() -- total total " + totalTime); //0 i am not getting that adapter value i.e. 310
}
private class DataAdapter extends BaseAdapter {
#Override
public int getCount() {
return docList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
LayoutInflater li = getLayoutInflater();
if (convertView == null)
convertView = li.inflate(R.layout.dashboard_item, null);
final DasDetails item = docList.get(position);
((TextView) convertView.findViewById(R.id.cMode))
.setText(item.cMode);
((TextView) convertView.findViewById(R.id.noOfItems))
.setText(item.totPickItemCount);
((TextView) convertView.findViewById(R.id.userCount))
.setText(item.userCount);
((TextView) convertView.findViewById(R.id.totalLoginTime))
.setText(item.totLoginTime);
TextView textView = ((TextView) convertView
.findViewById(R.id.avgSpeed));
Double s = Double.parseDouble(item.avgPickingSpeed);
textView.setText(String.format("%.2f", s));
if (position == 0 || position == 2 || position == 4) {
convertView.setBackgroundColor(getResources().getColor(
R.color.hot_pink));
} else if (position == 1 || position == 3 || position == 5) {
convertView.setBackgroundColor(getResources().getColor(
R.color.lightblue));
}
return convertView;
}
}
class ErrorItem {
String cMode, dDate, userCount, totLoginTime, totPickItemCount,
avgPickingSpeed;
public ErrorItem(HashMap<String, String> row) {
cMode = row.get(XT.MODE);
dDate = row.get(XT.DATE);
userCount = row.get(XT.USER_COUNT);
totLoginTime = row.get(XT.TOT_LOGIN_TIME);
totPickItemCount = row.get(XT.TOT_PICK_ITEM_COUNT);
avgPickingSpeed = row.get(XT.AVG_PICKING_SPEED);
}
}
private class DataLoader extends Thread {
#Override
public void run() {
super.run();
System.out.println("DataLoader dashboard");
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair(C.PRM_IDX, C.GET_SUMMARY));
param.add(new BasicNameValuePair(C.PRM_HDR_DATA, "2016-07-04")); // yyyy-mm-dd
toggleProgressNoUINoBlock(true);
final String result = callService(C.WS_ST_PERFORMANCE_DASHBOARD,
param);
if (!App.validateXmlResult(actContext, null, result, true))
return;
runOnUiThread(new Runnable() {
#Override
public void run() {
Runnable r = new Runnable() {
#Override
public void run() {
dataAdap.notifyDataSetChanged();
toggleProgressNoUINoBlock(false);
}
};
dashboardData = result;
processOutData(r);
}
});
}
}
private String callService(String serviceName, List<NameValuePair> params) {
String result = ws.callService(serviceName, params);
return result;
}
private void processOutData(final Runnable rAfterProcessing) {
if (dashboardData == null || dashboardData.length() == 0)
return;
new Thread() {
#Override
public void run() {
super.run();
final List<HashMap<String, String>> dataList = XMLfunctions
.getDataList(dashboardData, new String[] { XT.MODE,
XT.DATE, XT.USER_COUNT, XT.TOT_LOGIN_TIME,
XT.TOT_PICK_ITEM_COUNT, XT.AVG_PICKING_SPEED });
final List<DasDetails> tempList = new ArrayList<DasDetails>();
for (int i = 0; i < dataList.size(); i++) {
int pos = docExists(tempList, dataList.get(i).get(XT.MODE));
if (pos == -1) {
if (SEARCH_TYPE == 0
|| KEYWORD.equals("")
|| (SEARCH_TYPE == 1 && dataList.get(i)
.get(XT.CUST_NAME).contains(KEYWORD))
|| (SEARCH_TYPE == 2 && dataList.get(i)
.get(XT.DOC_NO).contains(KEYWORD))) {
DasDetails doc = new DasDetails(dataList.get(i));
int cachePos = getPosInCachedCounterUpdates(doc.cMode);
if (cachePos != -1) {
if (cachedCounterUpdates.get(cachePos)[1]
.equals(doc.dDate))
cachedCounterUpdates.remove(cachePos);
else
doc.dDate = cachedCounterUpdates
.get(cachePos)[1];
}
tempList.add(doc);
pos = tempList.size() - 1;
}
}
if (pos == -1)
continue;
}
runOnUiThread(new Runnable() {
#Override
public void run() {
docList = tempList;
rAfterProcessing.run();
logit("processOutData", "Processing OVER");
}
});
for (int i = 0; i < docList.size(); i++) {
itemsTotal = itemsTotal+ Integer.parseInt(docList.get(i).totPickItemCount);
userTotal = userTotal + Integer.parseInt(docList.get(i).userCount);
totalTime = totalTime + Integer.parseInt(docList.get(i).totLoginTime);
}
System.out.println("PerformanceDashboard.processOutData() -- fINAL item TOTAL " + itemsTotal); // 6 i have data here but i need this data in my oncreate but not getting why?????
System.out.println("PerformanceDashboard.processOutData() -- userTotal TOTAL " + userTotal); //4
System.out.println("PerformanceDashboard.processOutData() -- totalTime TOTAL " + totalTime); //310
noOfItems.setText(itemsTotal); // crashing with null pointer exception
// userCount.setText(userTotal);
// totalLoginTime.setText(totalTime);
};
}.start();
}
private class DasDetails {
public String cMode, dDate, userCount, totLoginTime, totPickItemCount,
avgPickingSpeed;
public DasDetails(HashMap<String, String> data) {
cMode = data.get(XT.MODE);
dDate = data.get(XT.DATE);
userCount = data.get(XT.USER_COUNT);
totLoginTime = data.get(XT.TOT_LOGIN_TIME);
totPickItemCount = data.get(XT.TOT_PICK_ITEM_COUNT);
avgPickingSpeed = data.get(XT.AVG_PICKING_SPEED);
}
}
public Integer docExists(List<DasDetails> list, String docNo) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).cMode.equals(docNo))
return i;
}
return -1;
}
private int getPosInCachedCounterUpdates(String docNo) {
for (int i = 0; i < cachedCounterUpdates.size(); i++) {
if (cachedCounterUpdates.get(i)[0].equals(docNo))
return i;
}
return -1;
}
}
This is the above code please go through it and let me know if any clarifications are required. I cannot able to set "itemsTotal" value to "noOfIttems" textview. I have added the comments. Please help me in solving this issue.
Thanks in advance.
Please check your noOfItems textView's id. TextView is null.

how to cancel method of count down timer to stop working

I have list of music that user set time to play. I want to have a button to cancel m count down timer .
I test some way but it doesn't work at all.
here is my code to play and set time to play.
public class Main extends Activity {
public static int hour_device, minute_device;
public static int hour_user, minute_user;
Splash splash;
ListView listView;
Adaptor adaptor;
private MediaPlayer mediaPlayer;
static View lastview = null;
static MyIndexStore indexStore;
List<String> lines1 = new ArrayList<String>();
List<String> lines2 = new ArrayList<String>();
static List<String> array_audio = new ArrayList<String>();
InputStream in;
BufferedReader reader;
String line = "1";
String[] tracks;
String[] names;
String[] infos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
indexStore = new MyIndexStore(getApplicationContext());
setContentView(R.layout.main_activity);
splash = new Splash(this);
splash.set_identity("1");
initiate();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.a1);
//lastview = null;
listView = (ListView) findViewById(R.id.list);
ReadText1();
names = lines1.toArray(new String[0]);// = {"track one","the seconnd track","a nice track","name name name","the seconnd track","a nice track","name name name"};
ReadText2();
infos = lines2.toArray(new String[0]);
tracks = array_audio.toArray(new String[0]);
adaptor = new Adaptor(getApplicationContext(), tracks, names, infos);
listView.setAdapter(adaptor);
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
if (lastview != null) {
ImageView play = (ImageView) lastview.findViewById(R.id.play_stop);
play.setImageResource(R.drawable.n_btn_play_unselected);
}
}
});
}
private static void initiate() {
Field[] fields = R.raw.class.getFields();
array_audio.clear();
for (int count = 0; count < fields.length; count++) {
array_audio.add("a" + (count + 1));
}
}
private void play(int index) {
mediaPlayer.release();
index++;
String s = "a" + index;
Resources resources = getResources();
final int resourceId = resources.getIdentifier(s, "raw", getPackageName());
try {
mediaPlayer = MediaPlayer.create(this, resourceId);
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
mediaPlayer.release();
listView.invalidateViews();
super.onPause();
}
private void ReadText1() {
lines1.clear();
line = "1";
try {
in = this.getAssets().open("names.txt");
reader = new BufferedReader(new InputStreamReader(in));
while (line != null) {
line = reader.readLine();
if (line != null)
lines1.add(line);
else
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void ReadText2() {
lines2.clear();
line = "1";
try {
in = this.getAssets().open("infos.txt");
reader = new BufferedReader(new InputStreamReader(in));
while (line != null) {
line = reader.readLine();
if (line != null)
lines2.add(line);
else
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
public class Adaptor extends ArrayAdapter<String> {
private final Context context;
private final String[] tracks;
private final String[] names;
private final String[] infos;
private HashMap<Integer,String> textMap;
Typeface type_face;
public Adaptor(Context context, String[] tracks, String[] names, String[] infos) {
super(context, R.layout.track, tracks);
this.context = context;
this.tracks = tracks;
this.names = names;
this.infos = infos;
type_face = Typeface.createFromAsset(context.getAssets(), "BTitrBd.ttf");
this.textMap = new HashMap<>();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.track, parent, false);
TextView name = (TextView) rowView.findViewById(R.id.track_name);
final TextView time = (TextView) rowView.findViewById(R.id.time);
//populate the textview from map
if(textMap!=null && textMap.get(new Integer(position))!=null){
time.setText(textMap.get(new Integer(position)));
}
name.setText(names[position]);
name.setTypeface(type_face);
name.setTypeface(type_face);
final ImageView ringtone = (ImageView) rowView.findViewById(R.id.ringtone);
if (position == indexStore.getindex())
ringtone.setImageResource(R.drawable.n_btn_ringtone_seted);
final ImageView play = (ImageView) rowView.findViewById(R.id.play_stop);
ringtone.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater factory = LayoutInflater.from(Main.this);
final View deleteDialogView = factory.inflate(
R.layout.mylayout, null);
final AlertDialog deleteDialog = new AlertDialog.Builder(Main.this).create();
deleteDialog.setView(deleteDialogView);
TextView device_time = (TextView) deleteDialogView.findViewById(R.id.current_time);
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
hour_device = hour;
minute_device = minute;
device_time.setText(hour_device + ":" + minute_device);
deleteDialogView.findViewById(R.id.set).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TimePicker timePicker = (TimePicker) deleteDialogView.findViewById(R.id.timepicker);
timePicker.setIs24HourView(true);
hour_user = timePicker.getCurrentHour();
minute_user = timePicker.getCurrentMinute();
String time1 = hour_device + ":" + minute_device;
String time2 = hour_user + ":" + minute_user;
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date date1 = null;
try {
date1 = format.parse(time1);
} catch (ParseException e) {
e.printStackTrace();
}
Date date2 = null;
try {
date2 = format.parse(time2);
} catch (ParseException e) {
e.printStackTrace();
}
long result = date2.getTime() - date1.getTime();
new CountDownTimer(result, 1000) {
public void onTick(long millisUntilFinished) {
time.setText(("seconds remaining: " + millisUntilFinished / 1000));
//create HashMap<Integer,String> textMap at the constructer of the adapter
//now fill this info int'o it
textMap.put(new Integer(position), "seconds remaining: " + millisUntilFinished / 1000);
//notify about the data change
notifyDataSetChanged();
}
public void onFinish() {
time.setVisibility(View.INVISIBLE);
//create HashMap<Integer,String> textMap at the constructer of the adapter
//now fill this info into it
textMap.put(new Integer(position),null);
//notify about the data change
notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "finish", Toast.LENGTH_LONG).show();
if (rowView != lastview || mediaPlayer == null) {
play(position);
if (lastview != null)
lastview = rowView;
} else {
play.setImageResource(R.drawable.n_btn_play_unselected);
mediaPlayer.release();
lastview = null;
}
}
}.start();
deleteDialog.dismiss();
}
});
deleteDialog.show();
}
});
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (rowView != lastview || mediaPlayer == null) {
play(position);
if (lastview != null)
lastview = rowView;
} else {
play.setImageResource(R.drawable.n_btn_play_unselected);
mediaPlayer.release();
lastview = null;
}
}
});
return rowView;
}
}
}
make the count down timer an instance variable;
private CountDownTimer timer;
then delegate your count to this variable:
#Override
public void onClick(View v) {
...
timer = new CountDownTimer(result, 1000) {
...
}
}
now you can stop the timer whenever you want to:
timer.cancel();
Check this code, working Successfull
call class from here
timer = new CounterClass(timeInmilles, 1000);
timer.start();
CounterClass is here
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
}
public void onTick(long millisUntilFinished) {
}
}
use to cancel see below line
timer.cancel()

Android: Downloaded Images not showing in ListView

I used an AsyncTask to download Images from a URL and I wanted to display those images in a listview using a custom adapter. Everything else is downloading correctly, but the images just won't show in my listview. I tried different links, different methods (setImageDrawable & setImageBitmap) and nothing will work. Hopefully you guys can help me, I will post the relevant code parts.
`private int getEventsLength(String eventsUnformated) {
int count = 0;
int startPos = 0;
String find = "event {";
while (eventsUnformated.indexOf(find, startPos) != -1) {
startPos = eventsUnformated.indexOf(find, startPos) + find.length();
count++;
}
return count;
}
private Event[] getEvents(String eventsUnformated) {
ArrayList<Event> eventList = new ArrayList<Event>();
int startPos = 0;
int eventLength = getEventsLength(eventsUnformated);
for (int i = 0; i < eventLength; i++) {
ArrayList<String> weirdList = new ArrayList<String>();
while (weirdList.size() < 6) {
startPos = eventsUnformated.indexOf(':', startPos) + 1;
weirdList.add(eventsUnformated.substring(startPos, eventsUnformated.indexOf('\n', startPos)).trim());
}
Date eventDate = null;
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
try {
eventDate = dateFormat.parse(weirdList.get(2));
}
catch (ParseException ex) { }
try {
new DownloadImageTask().execute(new URL(weirdList.get(4)));
}
catch (MalformedURLException ex) { }
eventList.add(new Event(weirdList.get(0), weirdList.get(1), eventDate, eventImage, weirdList.get(3)));
}
return eventList.toArray(new Event[eventList.size()]);
}
private void populateEventListView() {
ArrayAdapter<Event> adapter = new EventListAdapter();
eventListView = (ListView) findViewById(R.id.listView2);
eventListView.setAdapter(adapter);
}
private class DownloadTask extends AsyncTask<Void, Void, Void> {
String downloadedEvents = "", downloadedChapters = "";
#Override
protected Void doInBackground(Void... params) {
try {
URL eventsUrl = new URL("myUrl/events.txt");
URL chaptersUrl = new URL("myUrl/chapters.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(eventsUrl.openStream()));
String temp = "";
String news = "";
while((temp = reader.readLine()) != null) {
news += temp + "\n";
}
reader.close();
downloadedEvents = news;
news = "";
temp = "";
reader = new BufferedReader(new InputStreamReader(chaptersUrl.openStream()));
while((temp = reader.readLine()) != null) {
news += temp + "\n";
}
reader.close();
downloadedChapters = news;
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
ViewFlipper newsFlipper = (ViewFlipper) findViewById(R.id.flipperNews);
Event[] Events = getEvents(downloadedEvents);
Chapter[] Chapters = getChapters(downloadedChapters);
TextView[] Labels = new TextView[Events.length];
for (int i = 0; i < Events.length; i++) {
eventList.add(Events[i]);
Labels[i] = makeNews(Events[i].getEventName());
newsFlipper.addView(Labels[i]);
}
for (int i = 0; i < Chapters.length; i++) {
chapterList.add(Chapters[i]);
}
super.onPostExecute(result);
}
}
private class EventListAdapter extends ArrayAdapter<Event> {
public EventListAdapter() {
super(MainActivity.this, R.layout.listview_event, eventList);
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
View myView = convertView;
if (myView == null)
myView = getLayoutInflater().inflate(R.layout.listview_event, parent, false);
Event currentEvent = eventList.get(pos);
TextView eventName = (TextView) myView.findViewById(R.id.lblEventName);
eventName.setText(currentEvent.getEventName());
TextView eventHost = (TextView) myView.findViewById(R.id.lblHostName);
eventHost.setText(currentEvent.getHostChapter());
TextView eventDate = (TextView) myView.findViewById(R.id.lblEventDate);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy kk:mm");
eventDate.setText(dateFormat.format(currentEvent.getEventDate()));
TextView eventLocation = (TextView) myView.findViewById(R.id.lblEventLocation);
eventLocation.setText(currentEvent.getEventLocation());
ImageView badge = (ImageView) myView.findViewById(R.id.imgEvent);
badge.setImageDrawable(currentEvent.getEventImage());
return myView;
}
}
private class DownloadImageTask extends AsyncTask<URL,Void, Void> {
#Override
protected Void doInBackground(URL... imageUrls) {
try {
eventImage = Drawable.createFromStream(imageUrls[0].openConnection().getInputStream(), imageUrls[0].toString());
chapterImage = BitmapFactory.decodeStream(imageUrls[0].openStream());
}
catch (MalformedURLException ex) { }
catch (IOException ioException) { }
return null;
}
}`
Change your DownloadImageTask to:
private class DownloadImageTask extends AsyncTask<ImageView,Void, Bitmap> {
private ImageView imageView;
#Override
protected Void doInBackground(ImageView imv) {
URL imageURL = (URL) imv.getTag();
imageView = imv;
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream((InputStream)(imageURL.getContent()));
} catch (MalformedURLException e) {
// Invalid URL
} catch (IOException e) {
//Problem with connecting internet, or resource is not available
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap b){
imageView.setImageBitmap(bitmap);
}
}
And in your Adapter:
badge.setImageDrawable(placeHolderImage);
badge.setTag(currentEvent.getImageURL);
new DownloadImageTask().execute(badge);
And of course you have to add getImageURL to your Event class.

Categories

Resources