Lisview inside a Listview not working - java

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;
}
}

Related

Android Studio, there's an error retrieving schedule information

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.

android api json array within array parsing java

I'm making a simple news app for my class and i'm using an api from The Guardian to populate my feed. I had it all working with the article Title, Date, and URL, but upon adding the Section and Author name I cant seem to get it to populate the feed. The device is saying No News Found and the log is saying "Error response code: 429"
Any help/criticism is greatly appreciated!
Activity
public class NewsActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<News>> {
private static final String LOG_TAG = NewsActivity.class.getName();
private static final String GUARDIAN_REQUEST_URL =
"http://content.guardianapis.com/search?section=games&order-by=newest&api-key=test&show-tags=contributor";
private static final int NEWS_LOADER_ID = 1;
private NewsAdapter mAdapter;
private TextView mEmptyStateTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_activity);
ListView newsListView = (ListView) findViewById(R.id.list);
mEmptyStateTextView = (TextView) findViewById(R.id.empty_view);
newsListView.setEmptyView(mEmptyStateTextView);
mAdapter = new NewsAdapter(this, new ArrayList<News>());
newsListView.setAdapter(mAdapter);
newsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
News currentNews = mAdapter.getItem(position);
Uri newsUri = Uri.parse(currentNews.getUrl());
Intent websiteIntent = new Intent(Intent.ACTION_VIEW, newsUri);
startActivity(websiteIntent);
}
});
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(NEWS_LOADER_ID, null, this);
} else {
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
mEmptyStateTextView.setText(R.string.no_internet_connection);
}
}
#Override
public Loader<List<News>> onCreateLoader(int i, Bundle bundle) {
return new NewsLoader(this, GUARDIAN_REQUEST_URL);
}
#Override
public void onLoadFinished(Loader<List<News>> loader, List<News> news) {
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
mEmptyStateTextView.setText(R.string.no_news);
if (news != null && !news.isEmpty()) {
mAdapter.addAll(news);
updateUi(news);
}
}
private void updateUi(List<News> news) {
}
#Override
public void onLoaderReset(Loader<List<News>> loader) {
mAdapter.clear();
}
}
Adapter
public class NewsAdapter extends ArrayAdapter<News> {
public NewsAdapter(Context context, List<News> news) {
super(context, 0, news);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.news_list_item, parent, false);
}
News currentNews = getItem(position);
TextView titleView = (TextView) listItemView.findViewById(R.id.title);
String title = currentNews.getTitle();
titleView.setText(title);
TextView dateView = (TextView) listItemView.findViewById(R.id.date);
String dateToString = String.valueOf(currentNews.getDate());
String date = dateToString.substring(0, 10);
dateView.setText(date);
TextView authorView = (TextView) listItemView.findViewById(R.id.firstname);
String authorFirstName = currentNews.getAuthorFirstName();
authorView.setText(authorFirstName);
TextView lastNameView = (TextView) listItemView.findViewById(R.id.lastname);
String authorLastName = currentNews.getAuthorLastName();
lastNameView.setText(authorLastName);
TextView sectionView = (TextView) listItemView.findViewById(R.id.section);
String section = currentNews.getSection();
sectionView.setText(section);
return listItemView;
}
}
QueryUtils
public class QueryUtils {
private static final String LOG_TAG = QueryUtils.class.getSimpleName();
private QueryUtils() {
}
public static List<News> fetchNewsData(String requestUrl) {
// Create URL object
URL url = createUrl(requestUrl);
// Perform HTTP request to the URL and receive a JSON response back
String jsonResponse = null;
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG, "Problem making the HTTP request.", e);
}
List<News> newss = extractResultFromJson(jsonResponse);
return newss;
}
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Problem building the URL ", e);
}
return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
// If the URL is null, then return early.
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// If the request was successful (response code 200),
// then read the input stream and parse the response.
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the news JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
private static List<News> extractResultFromJson(String newsJSON) {
if (TextUtils.isEmpty(newsJSON)) {
return null;
}
List<News> newss = new ArrayList<>();
try {
JSONObject baseJsonResponse = new JSONObject(newsJSON);
JSONObject mainResponse = baseJsonResponse.getJSONObject("response");
JSONArray newsArray = mainResponse.getJSONArray("results");
for (int i = 0; i < newsArray.length(); i++) {
JSONObject currentNews = newsArray.getJSONObject(i);
String title = currentNews.getString("webTitle");
String date = currentNews.getString("webPublicationDate");
String url = currentNews.getString("webUrl");
String section = currentNews.getString("sectionName");
JSONArray tagsArray = currentNews.getJSONArray("tags");
for (int j = 0; j < tagsArray.length(); j++) {
JSONObject currentTag = tagsArray.getJSONObject(j);
String authorFirstName = currentTag.getString("firstName");
String authorLastName = currentTag.getString("lastName");
News news = new News(title, date, url, authorFirstName, authorLastName, section);
newss.add(news);
}
}
} catch (JSONException e) {
Log.e("QueryUtils", "Problem parsing the news JSON results", e);
}
return newss;
}
}

Android-Error messages with intent within Adapter

I am trying to get the maps intent working within my Json Adapter. But somehow I am always getting the Error message :
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.content.Context.startActivity(android.content.Intent)' on a null object reference
This is my second Android Project and I can't find my mistake.
I hope some of you guys can help me.
class JSONAdapter extends BaseAdapter implements ListAdapter{
private final Activity activity;
private Context context;
private final JSONArray jsonArray;
JSONAdapter(Activity activity, JSONArray jsonArray) {
assert activity != null;
assert jsonArray != null;
this.jsonArray = jsonArray;
this.activity = activity;
}
#Override public int getCount() {
if(null==jsonArray)
return 0;
else
return jsonArray.length();
}
#Override public JSONObject getItem(int position) {
if(null==jsonArray) return null;
else
return jsonArray.optJSONObject(position);
}
#Override public long getItemId(int position) {
JSONObject jsonObject = getItem(position);
return jsonObject.optLong("id");
}
#Override public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = activity.getLayoutInflater().inflate(R.layout.row, null);
TextView tBrand =(TextView)convertView.findViewById(R.id.tvbrand);
TextView tStreet =(TextView)convertView.findViewById(R.id.tvstreet);
final TextView tPrice = (TextView)convertView.findViewById(R.id.tvprice);
final TextView tPlace = (TextView)convertView.findViewById(R.id.tvplace);
TextView tOpen = (TextView)convertView.findViewById(R.id.tvopen);
JSONObject json_data = getItem(position);
if(null!=json_data ) {
String brand = null;
String street = null;
String price = null;
String houseNumber = null;
String place = null;
String postCode = null;
boolean open = false;
Double statLng = null;
Double statLat = null;
try {
brand = json_data.getString("brand");
street = json_data.getString("street");
price = Double.toString(json_data.getDouble("price"));
houseNumber = json_data.getString("houseNumber");
place = json_data.getString("place");
postCode = json_data.getString("postCode");
open = json_data.getBoolean("isOpen");
statLng = json_data.getDouble("lng");
statLat = json_data.getDouble("lat");
} catch (JSONException e) {
e.printStackTrace();
}
if (houseNumber.equals("null")) {
houseNumber = "";
}
tBrand.setText(brand);
tPrice.setText(price + "€");
tStreet.setText(street + " " + houseNumber);
tPlace.setText(postCode + " " + place);
if (open == true) {
tOpen.setText("geöffnet");
tOpen.setTextColor(Color.GREEN);
} else {
tOpen.setText("geschlossen");
tOpen.setTextColor(Color.RED);
}
final Double finalStatLng = statLng;
final Double finalStatLat = statLat;
tPrice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri gmmIntentUri = Uri.parse("google.navigation:q=" + finalStatLat + "," + finalStatLng);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
context.startActivity(mapIntent);
}
});
}
return convertView;
}
You have missed to assign value to context
context = activity; or use activity.startActivity(mapIntent);

How do I fetch null from arraylist in android

I have a JSON like this
{
"questions": [{
"Creator_User_ID": "140110",
"Advisor_User_ID": null,
"Question_Video_Title": "media",
"playing_time": null,
"Created": "2016-01-20T00:00:00",
"Modified": "2016-01-20T00:00:00",
"question_video_playingTime": "0:4",
"Answer_Video_Title": null,
"Answer_Video_Link": null,
"answer_video_playingtime": null,
"StatusName": "Approved",
"QuestionID": 182
},
{
"Creator_User_ID": "140110",
"Advisor_User_ID": null,
"Question_Video_Title": "media",
"playing_time": null,
"Created": "2016-01-20T00:00:00",
"Modified": "2016-01-20T00:00:00",
"question_video_playingTime": "0:4",
"Answer_Video_Title": null,
"Answer_Video_Link": null,
"answer_video_playingtime": null,
"StatusName": "Approved",
"QuestionID": 182
}
]
}
I have added values of lets suppose "Answer_Video_Link" into Arraylist for e.g arraylistAnswerLink so the output will be like[null,null,....so on]
As setting this arraylist in a BaseAdapter,the functionality is want to achieve is:
if(arraylistAnswerLink.get(position).contains(null)){
button.setVisibilty(View.Visible)}
else{
button.setVisibilty(View.Gone)
}
This my json parsing code
jsonInnerArray = jsonInnerObject.getJSONArray("questions");
for (int j = 0; j <= jsonInnerArray.length(); j++) {
jsonArrayObject = jsonInnerArray.getJSONObject(j);
Question_Video_Title = jsonArrayObject.getString("Question_Video_Title");
question_video_playingTime = jsonArrayObject.getString("question_video_playingTime");
String Designation1 = jsonArrayObject.getString("Designation");
full_name = jsonArrayObject.getString("User_name"); Question_Video_Link = jsonArrayObject.getString("Question_Video_Link");
Answer_Video_Link = jsonArrayObject.getString("Answer_Video_Link");
QuestionID = jsonArrayObject.getString("QuestionID");
video_thumbnail=jsonArrayObject.getString("video_thumbnail"); }
am having error of array index out of bound while fetching null at a particular position of the list.
Please check my code
public class UnRepliedFragment_ extends Fragment {
private static final String ARG_PARAM1 = "param1";
private String mParam1;
View rootview;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
// ArrayList<Integer> arrayListImage;
ArrayList<Integer> arrayListVideos;
File mediaFile, vPath;
String song_dur_str, st, vst, vst1, orginalName;
String timestamp, advisorID, token;
int VIDEO_CAPTURE = 1000;
ProgressDialog dlg;
SharedPreferences preferences;
ArrayList<String> arrayListName, videoName, singleVideoName, questionLink, arrquestion_video_playingTime, answerLinkEmpty;
String FirstName, durationofVideo, User_name, Question_Video_Title, Question_Video_Link, shorted, cmpsort, question_video_playingTime, path, QuestionID;
int advisor, pos;
private List<Modals> feedsList;
Uri mediaPath;
PutObjectRequest por;
String url = "https://s3-us-west-1.amazonaws.com/talentedge1";
private static AmazonS3Client sS3Client;
Uri fileUri;
static Object Answer_Video_Link;
ArrayList<Object> answerLink;
Object item;
JSONObject jsonObject,innerObject;
JSONArray innerArray;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.fragment_unreplied, container, false);
dlg = new ProgressDialog(getActivity());
preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
token = preferences.getString(AppConstant.TOKEN, "");
advisorID = preferences.getString(AppConstant.USERID, "");
arrayListVideos = new ArrayList<>();
feedsList = new ArrayList<>();
arrayListName = new ArrayList<>();
videoName = new ArrayList<>();
questionLink = new ArrayList<>();
arrquestion_video_playingTime = new ArrayList<>();
answerLink = new ArrayList<>();
singleVideoName = new ArrayList<>();
/*
API hit
*/
new Proadvice().execute();
mRecyclerView = (RecyclerView) rootview.findViewById(R.id.recycler_view_unreplied);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
return rootview;
}
/*
Adapter class
*/
class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
private Context mContext;
private LayoutInflater inflater;
ArrayList<String> videoName;
ArrayList<String> questionLink;
ArrayList<String> arrquestion_video_playingTime;
ArrayList<Object> answerLink;
public MyRecyclerViewAdapter(ArrayList<String> videoName, ArrayList<String> questionLink, ArrayList<Object> answerLink, ArrayList<String> arrquestion_video_playingTime) {
this.videoName = videoName;
this.questionLink = questionLink;
this.answerLink = answerLink;
this.arrquestion_video_playingTime = arrquestion_video_playingTime;
}
#Override
public MyRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.unreplied_list_row, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(MyRecyclerViewAdapter.ViewHolder holder, int position) {
holder.txt_it_author.setText(arrayListName.get(position));
holder.textView.setText(arrquestion_video_playingTime.get(position));
holder.txt_it_Title.setText(videoName.get(position));
for (Object value : answerLink) {
if (value != null) {
System.out.println("Not Null" + value);
} else {
System.out.println("Null" + value);
}
}
}
#Override
public int getItemCount() {
return videoName.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView imageView;
TextView textView, txt_it_author, txt_it_Title, share;
RippleView relativeLayout;
LinearLayout imageButtonAnswer;
FrameLayout frameLayout;
public ViewHolder(View itemView) {
super(itemView);
relativeLayout = (RippleView) itemView.findViewById(R.id.relative_video_it);
relativeLayout.setOnClickListener(this);
imageView = (ImageView) itemView.findViewById(R.id.img_it_Video);
textView = (TextView) itemView.findViewById(R.id.txt_it_duration);
txt_it_author = (TextView) itemView.findViewById(R.id.txt_it_author);
txt_it_Title = (TextView) itemView.findViewById(R.id.txt_it_Title);
imageButtonAnswer = (LinearLayout) itemView.findViewById(R.id.img_answers);
frameLayout = (FrameLayout) itemView.findViewById(R.id.relative_play_img);
imageButtonAnswer.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int position = getLayoutPosition();
int id = v.getId();
switch (id) {
case R.id.relative_play_img:
Intent i = new Intent(getActivity(), Video_ViewAct.class);
i.putExtra("position", "" + position);
i.putExtra("Question_Video_Link", questionLink.get(position));
// i.putExtra("Answer_Video_Link", answerLink.get(position));
startActivity(i);
break;
}
}
}
}
class Proadvice extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
return doInLoginProadvice();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dlg.setMessage("Loading.....");
dlg.setCancelable(false);
dlg.show();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
dlg.dismiss();
if (result.contains("true")) {
updateUIProadvice(result);
}
}
}
private void updateUIProadvice(String result) {
try {
jsonObject = new JSONObject(result);
String message = jsonObject.getString("message");
innerObject = jsonObject.getJSONObject("Object");
innerArray = innerObject.getJSONArray("details");
// Log.e("arr", " " + arr);
for (int i = 0; i <= innerArray.length(); i++) {
JSONObject obj = innerArray.getJSONObject(i);
String advisorID = obj.getString("AdvisorID");
FirstName = obj.getString("FirstName");
String LastName = obj.getString("LastName");
String Email = obj.getString("Email");
String Password = obj.getString("Password");
String Designation = obj.getString("Designation");
String Company = obj.getString("Company");
String Location = obj.getString("Location");
String Description = obj.getString("Description");
String Profile_Pic_Small = obj.getString("Profile_Pic_Small");
String Profile_Pic_Original = obj.getString("Profile_Pic_Original");
String No_Questions = obj.getString("No_Questions");
String No_Answers = obj.getString("No_Answers");
String No_Up_Votes = obj.getString("No_Up_Votes");
String No_Followers = obj.getString("No_Followers");
String IsActive = obj.getString("IsActive");
String Created = obj.getString("Created");
String Modified = obj.getString("Modified");
JSONArray arr1 = innerObject.getJSONArray("questions");
for (int j = 0; j <= arr1.length(); j++) {
JSONObject obj1 = arr1.getJSONObject(j);
Question_Video_Title = obj1.getString("Question_Video_Title");
question_video_playingTime = obj1.getString("question_video_playingTime");
String Designation1 = obj1.getString("Designation");
User_name = obj1.getString("User_name");
Question_Video_Link = obj1.getString("Question_Video_Link");
shorted = Question_Video_Title.replace("=", " ");
cmpsort = shorted.replace("-", " ");
Answer_Video_Link = obj1.get("Answer_Video_Link");
QuestionID = obj1.getString("QuestionID");
videoName.add((cmpsort));
questionLink.add(Question_Video_Link);
answerLink.add(Answer_Video_Link);
arrayListName.add(User_name);
arrquestion_video_playingTime.add(question_video_playingTime);
mAdapter = new MyRecyclerViewAdapter(videoName, questionLink, answerLink, arrquestion_video_playingTime);
mRecyclerView.setAdapter(mAdapter);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private String doInLoginProadvice() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(AppConstant.getAdvivisorDetail);
httppost.addHeader("APIKEY", "123ABC890567");
httppost.addHeader("Token", token);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("AdvisorID", advisorID));
try {
httppost.setEntity(new UrlEncodedFormEntity(pairs));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
}
Here is the Simple Way to Parse JSON array and easily get Null as well as a value pair . Important Thing Do not use variable name as a capital letter it must be start with lower case.
please find programme and you can modify it according to Your Requirement
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class UnRepliedFragment_ {
//Define this as a global varraible
static Object Advisor_User_ID;
static Object Creator_User_ID;
static Object Question_Video_Title;
static Object playing_time;
static Object Created;
static Object Modified;
static Object question_video_playingTime;
static Object Answer_Video_Title;
static Object Answer_Video_Link;
static Object answer_video_playingtime;
static Object StatusName;
static Object QuestionID;
static ArrayList al;
public void onBindViewHolder() {
for (Object value : al) {
if (value != null) {
System.out.println("Not Null" + value);
} else {
System.out.println("Null" + value);
}
}
}
private void updateUIProadvice(String result) {
//Since i have an limited JSON so Accroding to that i did parsing . Dont try with getString just try with Get();//method
try {
JSONParser jsonParser = new JSONParser();
org.json.simple.JSONObject jsonObject = (org.json.simple.JSONObject) jsonParser.parse(result);
org.json.simple.JSONArray lang = (org.json.simple.JSONArray) jsonObject.get("questions");
for (int i = 0; i < lang.size(); i++) {
}
Iterator i = lang.iterator();
while (i.hasNext()) {
org.json.simple.JSONObject innerObj = (org.json.simple.JSONObject) i.next();
Creator_User_ID = innerObj.get("Creator_User_ID").toString();
Advisor_User_ID = innerObj.get("Advisor_User_ID");
Question_Video_Title = innerObj.get("Question_Video_Title");
playing_time = innerObj.get("playing_time");
Created = innerObj.get("Created");
Modified = innerObj.get("Modified");
question_video_playingTime = innerObj.get("question_video_playingTime");
Answer_Video_Title = innerObj.get("Answer_Video_Title");
question_video_playingTime = innerObj.get("question_video_playingTime");
Answer_Video_Title = innerObj.get("Answer_Video_Title");
Answer_Video_Link = innerObj.get("Answer_Video_Link");
answer_video_playingtime = innerObj.get("answer_video_playingtime");
StatusName = innerObj.get("StatusName");
QuestionID = innerObj.get("QuestionID");
// Storing data into arrayList
al = new ArrayList();
al.add(Creator_User_ID);
al.add(Advisor_User_ID);
al.add(Question_Video_Title);
al.add(playing_time);
al.add(Created);
al.add(Modified);
al.add(question_video_playingTime);
al.add(Answer_Video_Link);
al.add(Answer_Video_Title);
al.add(answer_video_playingtime);
al.add(QuestionID);
al.add(StatusName);
// First Way to get element one by one
for (Object value : al) {
if (value != null) {
System.out.println("Not Null:" + value);
} else {
System.out.println("Null:" + value);
}
}
//or Second Way
Object valuenext=al.get(0); // Get First Index Value
System.out.println(valuenext);
}
} catch (ParseException ex) {
ex.printStackTrace();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}
}

ListView Doesn't display anymore than 8 ImageViews

I am decoding jpeg images from a server request I get using json. I display them with a custom ListView Adapter along with a little text.
The images display correctly for the first 8 ImageViews in the ListView, however, after that it will no longer display the image (it will display the text). For example, if I have a total of 10 images, the last two images will not show in the ListView, but if I delete the first 2 images, the last two will show, so there is no concern about retrieving the actual images.
On my main activity (NotesActivity) I have a button that goes to another activity which does an asyntask, and in that async task in the onPostExecute, it returns back to the main activity where it should show the updated list (and it does, unless there are more than 8 images).
I don't know where to begin, any suggestions?
My Activity that contains the ListView
public class NotesActivity extends Activity implements OnClickListener {
String key = "NOTES";
String key2 = "UPDATE_NOTES";
Gson gson = new Gson();
// Notes myNotes = new Notes();
NotesList myNotes = new NotesList();
String bId;
String res = null;
EditText notes;
Button save;
private Button createNote;
private int position;
private String type;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notes_layout);
createNote = (Button) findViewById(R.id.notes_layout_btn_createNote);
Bundle bundle = this.getIntent().getExtras();
position = bundle.getInt("position");
type = bundle.getString("type");
//
if (type.equals("LISTINGS")) {
Listings it = ListingsFragment.myListings.getListings().get(
position);
bId = it.getBID();
notes = (EditText) findViewById(R.id.notes);
}
//
if (type.equals("SHARED")) {
Listings it = SharedFragment.myShared.getListings().get(position);
bId = it.getBID();
notes = (EditText) findViewById(R.id.notes);
}
GetNotes getNotes = new GetNotes();
try {
NotesList copy = new NotesList();
getNotes.execute(key, bId).get();
for (int j = 0; j < myNotes.getNotes().size(); j++) {
Notes note = myNotes.getNotes().get(j);
System.out.println("Removed value: " + note.getIsRemoved());
if (note.getIsRemoved() == null) {
copy.getNotes().add(note);
}
}
NotesAdapter adapter = new NotesAdapter(this, R.layout.note_row,
copy.getNotes());
ListView lv = (ListView) findViewById(R.id.notes_layout_lv_notesList);
lv.setAdapter(adapter);
} catch (Exception e) {
}
createNote.setOnClickListener(this);
}
private class GetNotes extends AsyncTask<String, String, NotesList> {
#Override
protected NotesList doInBackground(String... things) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("key", things[0]));
postParameters.add(new BasicNameValuePair("bId", things[1]));
// String valid = "1";
String response = null;
try {
response = CustomHttpClient.executeHttpPost(
"http://propclip.dev/mobile.php", postParameters);
res = response.toString();
// System.out.println("This is the response " + res);
// res = res.trim();
// res= res.replaceAll("\\s+","");
// error.setText(res);
// System.out.println(res);
myNotes = gson.fromJson(res, NotesList.class);
// System.out.println(res);
} catch (Exception e) {
res = e.toString();
}
return myNotes;
}
#Override
protected void onPostExecute(NotesList res) {
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.notes_layout_btn_createNote:
ProfileDataSource datasource = new ProfileDataSource(this);
datasource.open();
PropClipGlobal pcg = datasource.getUserIdenity();
Intent intent = new Intent(this, NewNoteActivity.class);
intent.putExtra("bId", bId);
intent.putExtra("uId", pcg.getUID());
intent.putExtra("username", pcg.getEm());
intent.putExtra("position", position);
intent.putExtra("type", type);
startActivity(intent);
}
}
}
My custom adapter
public class NotesAdapter extends ArrayAdapter<Notes> {
List<Notes> notes;
Context context;
public NotesAdapter(Context context, int resource, List<Notes> notes) {
super(context, resource, notes);
this.notes = notes;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.note_row, null);
}
Notes note = notes.get(position);
ImageView icon = (ImageView) v.findViewById(R.id.note_row_icon);
TextView name = (TextView) v.findViewById(R.id.note_row_name);
TextView message = (TextView) v.findViewById(R.id.note_row_message);
TextView date = (TextView) v.findViewById(R.id.note_row_date);
String input = note.getNoteDate();
SimpleDateFormat inputDf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat outputDf = new SimpleDateFormat("dd, yyyy");
SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
Date myDate = null;
try {
myDate = inputDf.parse(input);
} catch (ParseException e) {
e.printStackTrace();
}
String month = monthFormat.format(myDate);
date.setText(getMonth(Integer.parseInt(month)) + " "
+ outputDf.format(myDate));
message.setText(note.getNote());
name.setText(note.getFirstName() + " " + note.getLastName());
// System.out.println(p.getFileData());
byte[] imageAsBytes = Base64.decode(note.getFileData().getBytes(),
position);
icon.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0,
imageAsBytes.length));
System.out.println(note.getFileData());
return v;
}
public String getMonth(int month) {
return new DateFormatSymbols().getMonths()[month - 1];
}
}
Activity which eventually goes to the main activity (NotesActivity)
public class NewNoteActivity extends Activity implements OnClickListener {
private String uId;
private String bId;
private String username;
private String response;
private String key = "UPDATE_NOTES";
private Button submit;
private EditText note;
private int position;
private String type;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_note);
submit = (Button) findViewById(R.id.activity_new_note_btn_submit);
note = (EditText) findViewById(R.id.activity_new_note_et_note);
Intent intent = getIntent();
bId = intent.getStringExtra("bId");
uId = intent.getStringExtra("uId");
username = intent.getStringExtra("username");
position = intent.getIntExtra("position", 0);
type = intent.getStringExtra("type");
submit.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.new_note, menu);
return true;
}
private class UpdateNotes extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... values) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("key", values[0]));
postParameters.add(new BasicNameValuePair("bId", values[1]));
postParameters.add(new BasicNameValuePair("uId", values[2]));
postParameters.add(new BasicNameValuePair("username", values[3]));
postParameters.add(new BasicNameValuePair("note", values[4]));
String response = null;
try {
response = CustomHttpClient.executeHttpPost(
"http://propclip.dev/mobile.php", postParameters);
response = response.toString();
} catch (Exception e) {
response = e.toString();
}
return null;
}
#Override
protected void onPostExecute(String response) {
Intent intent = new Intent(getApplicationContext(),
NotesActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("position", position);
intent.putExtra("type", type);
startActivity(intent);
Toast toast = Toast.makeText(getApplicationContext(),"Added note!", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
#Override
public void onClick(View v) {
String noteMessage = note.getText().toString();
UpdateNotes updateNotes = new UpdateNotes();
updateNotes.execute(key, bId, uId, username, noteMessage);
}
}

Categories

Resources