RecyclerView is not showing any item - java

I have a RecyclerView which items I populate from json response.
public class UserProfile extends AppCompatActivity {
private UserData userData;
private ProfileNewsFeedAdapter adapter;
private ArrayList<ProgramModel> list;
private RecyclerView profileNewsFeed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_profile_activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
userData = new UserData(this);
list = new ArrayList<>();
adapter = new ProfileNewsFeedAdapter(getActivity(), list);
initializeViews();
}
private void initializeViews() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setTitle(userData.getName());
TextView userEmail = (TextView) findViewById(R.id.emailPrfId);
TextView birthday = (TextView) findViewById(R.id.birthdayId);
TextView userClass = (TextView) findViewById(R.id.userClassId);
userEmail.setText(userData.getEmail());
birthday.setText("Ditëlindja: " + userData.getBirthday());
userClass.setText("Klasa: " + userData.getUserClass());
setFont(userEmail);
setFont(birthday);
setFont(userClass);
profileNewsFeed = (RecyclerView) findViewById(R.id.profileNewsFeed);
profileNewsFeed.setLayoutManager(new LinearLayoutManager(this));
profileNewsFeed.setItemAnimator(new DefaultItemAnimator());
profileNewsFeed.setHasFixedSize(true);
profileNewsFeed.setAdapter(adapter);
GetBorrowedBooks getBorrowedBooks = new GetBorrowedBooks();
getBorrowedBooks.execute();
}
private void setFont(TextView textView) {
textView.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/Roboto-Light.ttf"));
}
private AppCompatActivity getActivity() {
return this;
}
private class GetBorrowedBooks extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
String userId = userData.getUserId();
StringRequest stringRequest = new StringRequest(Request.Method.GET, "http://ec2-52-39-232-168.us-west-2.compute.amazonaws.com/user/" + userId + "/requests", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
if (jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String imageName = "http://ec2-52-39-232-168.us-west-2.compute.amazonaws.com/files/books/" + jsonObject.getString("cover");
list.add(new ProgramModel(jsonObject.getString("title"), jsonObject.getString("author"), imageName));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
MyDynamicToast.errorMessage(AppController.getInstance(), "Volley did not respond!");
}
});
AppController.getInstance().addToRequestQueue(stringRequest);
return null;
}
}
}
This is the adapter code:
public class ProfileNewsFeedAdapter extends RecyclerView.Adapter<ProfileNewsFeedAdapter.MyViewHolder> {
private AppCompatActivity activity;
private ArrayList<ProgramModel> program;
private LayoutInflater inflater;
public ProfileNewsFeedAdapter(AppCompatActivity activity, ArrayList<ProgramModel> program) {
this.activity = activity;
inflater = activity.getLayoutInflater();
this.program = program;
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title, author;
ImageView bookImage;
MyViewHolder(View v) {
super(v);
title = (TextView) v.findViewById(R.id.bookTitleBorrowId);
author = (TextView) v.findViewById(R.id.bookAuthorBorrowId);
bookImage = (ImageView) v.findViewById(R.id.bookImageBorrowCardId);
}
void setMenuDetail(ProgramModel model, final int position) {
title.setText(model.getTitle());
author.setText(model.getMessage());
// Set text fonts
title.setTypeface(Typeface.createFromAsset(activity.getAssets(), "fonts/Roboto-Bold.ttf"));
author.setTypeface(Typeface.createFromAsset(activity.getAssets(), "fonts/Roboto-Light.ttf"));
Picasso.with(activity).load(model.getImageUrl()).into(bookImage);
bookImage.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.bookImageCardId:
new GetBookInfo(activity, title.getText().toString()).execute();
break;
}
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = inflater.inflate(R.layout.profile_cardview_item, parent, false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
ProgramModel menuModel = program.get(position);
holder.setMenuDetail(menuModel, position);
}
#Override
public int getItemCount() {
return program.size();
}
private class GetBookInfo extends AsyncTask<Void, Void, Void> {
private String bookTitle, bookAuthor, bookDescription, requestedBook, bookUrl, bookId;
private int copies;
private Context c;
GetBookInfo(Context c, String requestedBook) {
this.c = c;
this.requestedBook = requestedBook;
}
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... voids) {
fetchBookInfo();
return null;
}
private void fetchBookInfo() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, AppConfig.URL_FETCH_BOOKS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if (jsonObject.getString("title").equals(requestedBook)) {
bookId = "" + jsonObject.getInt("id");
bookTitle = jsonObject.getString("title");
bookAuthor = jsonObject.getString("author");
bookDescription = jsonObject.getString("description");
copies = jsonObject.getInt("quantity");
setBookUrl("http://ec2-52-39-232-168.us-west-2.compute.amazonaws.com/files/books/" + jsonObject.getString("cover"));
Intent intent = new Intent(c, BookActivity.class);
intent.putExtra("title", getBookTitle());
intent.putExtra("author", getBookAuthor());
intent.putExtra("bookId", getBookId());
intent.putExtra("description", getBookDescription());
intent.putExtra("copies", getCopies());
intent.putExtra("description", getBookDescription());
intent.putExtra("bookUrl", getBookUrl());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
c.startActivity(intent);
}
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("JSON Error: ", "" + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
MyDynamicToast.errorMessage(AppController.getInstance(), "Volley Error!");
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(stringRequest);
}
String getBookTitle() {
return bookTitle;
}
String getBookAuthor() {
return bookAuthor;
}
String getBookDescription() {
return bookDescription;
}
String getBookId() {
return bookId;
}
int getCopies() {
return copies;
}
private void setBookUrl(String url) {
bookUrl = url;
}
String getBookUrl() {
return bookUrl;
}
}
}
This is the ProgramModel class from which I get item's datas:
public class ProgramModel {
private String title;
private String message;
private int image;
private String imageUrl;
public ProgramModel(String title, String message, int image) {
this.title = title;
this.message = message;
this.image = image;
}
public ProgramModel(String title, String message) {
this.title = title;
this.message = message;
}
public ProgramModel(String title, String message, String imageUrl) {
this.title = title;
this.message = message;
this.imageUrl = imageUrl;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMessage() {
return message;
}
int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getImageUrl() {
return this.imageUrl;
}
}
This is the main layout code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:fitsSystemWindows="true"
tools:context="com.libraryhf.libraryharryfultz.activity.UserProfile">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="4">
<android.support.v7.widget.AppCompatImageView
android:id="#+id/userImageId"
android:layout_width="0dp"
android:layout_height="80dp"
android:layout_marginTop="3dp"
android:layout_weight="1"
android:src="#drawable/prf_image" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:layout_weight="3"
android:orientation="vertical"
android:padding="7dp">
<android.support.v7.widget.AppCompatTextView
android:id="#+id/emailPrfId"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<android.support.v7.widget.AppCompatTextView
android:id="#+id/birthdayId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
android:clickable="true"
android:paddingTop="7dp" />
<android.support.v7.widget.AppCompatTextView
android:id="#+id/userClassId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
android:clickable="true"
android:paddingTop="7dp" />
</LinearLayout>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
<android.support.v7.widget.RecyclerView
android:id="#+id/profileNewsFeed"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="150dp"
android:scrollbars="none" />
</android.support.design.widget.CoordinatorLayout>
This is the single item layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent">
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/item_cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
card_view:cardBackgroundColor="#color/colorAccent"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="5dp"
card_view:contentPadding="7dp">
<android.support.v7.widget.LinearLayoutCompat
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/bookTitleBorrowId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_margin="5dp"
android:text="#string/dummyText"
android:textColor="#color/white"
android:textSize="20sp" />
<android.support.v7.widget.LinearLayoutCompat
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_marginStart="9dp"
android:layout_weight="7"
android:orientation="horizontal">
<android.support.v7.widget.AppCompatImageView
android:layout_width="16dp"
android:layout_height="16dp"
android:layout_marginTop="1dp"
android:layout_weight="1"
app:srcCompat="#drawable/writer_icon" />
<TextView
android:id="#+id/bookAuthorBorrowId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_weight="6"
android:text="#string/dummyText"
android:textColor="#color/white"
android:textSize="13sp" />
</android.support.v7.widget.LinearLayoutCompat>
<ImageView
android:id="#+id/bookImageBorrowCardId"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp"
tools:ignore="ContentDescription" />
</android.support.v7.widget.LinearLayoutCompat>
</android.support.v7.widget.CardView>
</LinearLayout>
Unfortunately my items are not showing on the screen. I know that recyclerview is shown because I can notice the animations on top and on bottom but the items are not there. Where have I gone wrong here? Thank you.

Try adding adapter.notifyDataSetChanged(); after you add new element to the list. If you don't notify the adapter that the list changed, it won't update the recyclerview so that the data is always the empty list that is declared at the start.

you are accessing views from doInBackground, doInBackground is called on a different thread. you should access those views from onPostExecute(), an AsyncTask method that is called on the ui thread.

Related

RecyclerView doesn't Update and shows on screen until Soft Keyboard is Open/Close

I have one problem with my RecyclerView - it doesn't update on the main screen after pressing on the button. It can only appear after close/open soft keeboard. I looked a lot of solutions overe here but nothing helped me. I have just a simple app which sends a request "String" to server and gets one JSON Object and next inserts it on RecyclerView. But the data in RecyclerView don't apear immediately. I'm in deadlock. Help me.
Code in the activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/sky"
tools:context=".MainActivity">
<EditText
android:id="#+id/editTextRequestCity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/write_name_of_city_or_index"
android:inputType="textPersonName"
android:maxLength="30"
android:minHeight="48dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toTopOf="#+id/recyclerViewListForecast"
app:layout_constraintEnd_toStartOf="#+id/buttonShowWeather"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/buttonShowWeather"
android:layout_width="54dp"
android:layout_height="48dp"
android:background="#drawable/search_city"
android:onClick="onClickShowWeather"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toTopOf="#+id/recyclerViewListForecast"
app:layout_constraintStart_toEndOf="#+id/editTextRequestCity"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerViewListForecast"
app:layoutManager="LinearLayoutManager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editTextRequestCity"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Code in the weather_item.xml:
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/cardViewItem"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="1dp"
app:cardCornerRadius="1dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/textViewDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center"
android:background="#00FFFFFF"
android:textColor="#color/black"
android:textSize="15sp" />
<TextView
android:id="#+id/textViewTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center"
android:textColor="#color/black"
android:textSize="15sp" />
<TextView
android:id="#+id/textViewFallout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center"
android:textSize="15sp" />
<TextView
android:id="#+id/textViewDegree"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center"
android:textColor="#color/black"
android:textSize="15sp" />
<TextView
android:id="#+id/textViewPressure"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center"
android:textColor="#color/black"
android:textSize="15sp" />
<TextView
android:id="#+id/textViewHumidity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center"
android:textColor="#color/black"
android:textSize="15sp" />
<TextView
android:id="#+id/textViewSpeedWind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center"
android:textColor="#color/black"
android:textSize="15sp" />
<TextView
android:id="#+id/textViewGustWind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center"
android:textColor="#color/black"
android:textSize="15sp" />
<TextView
android:id="#+id/textViewDirectionWind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center"
android:textSize="15sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
Code in WeatherItem:
package com.example.forecast;
public class WeatherItem {
private String date;
private String time;
private String fallout;
private String degree;
private String pressure;
private String humidity;
private String speedWind;
private String gustWind;
private String directionWind;
public WeatherItem(String date, String time, String fallout, String degree, String pressure, String humidity, String speedWind, String gustWind, String directionWind) {
this.date = date;
this.time = time;
this.fallout = fallout;
this.degree = degree;
this.pressure = pressure;
this.humidity = humidity;
this.speedWind = speedWind;
this.gustWind = gustWind;
this.directionWind = directionWind;
}
public String getDate() {
return date;
}
public String getTime() {
return time;
}
public String getFallout() {
return fallout;
}
public String getDegree() {
return degree;
}
public String getPressure() {
return pressure;
}
public String getHumidity() {
return humidity;
}
public String getSpeedWind() {
return speedWind;
}
public String getGustWind() {
return gustWind;
}
public String getDirectionWind() {
return directionWind;
}
}
Code in WeatherAdapter:
package com.example.forecast;
public class WeatherAdapter extends RecyclerView.Adapter<WeatherAdapter.WeatherViewHolder> {
public ArrayList<WeatherItem> weatherItems;
Context context;
public WeatherAdapter(Context context, ArrayList <WeatherItem> weatherItems) {
this.context = context;
this.weatherItems = weatherItems;
}
#NonNull
#Override
public WeatherViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.weather_item, parent, false);
return new WeatherViewHolder(view);
}
#Override
public void onBindViewHolder(final WeatherViewHolder holder, int position) {
WeatherItem weatherItem = weatherItems.get(position);
holder.textViewDate.setText(weatherItem.getDate());
holder.textViewTime.setText(weatherItem.getTime());
holder.textView.setText(weatherItem.getFallout());
holder.textViewDegree.setText(weatherItem.getDegree());
holder.textViewPressure.setText(weatherItem.getPressure());
holder.textViewHumidity.setText(weatherItem.getHumidity());
holder.textViewSpeedWind.setText(weatherItem.getSpeedWind());
holder.textViewGustWind.setText(weatherItem.getGustWind());
holder.textViewDirectionWind.setText(weatherItem.getDirectionWind());
}
#Override
public int getItemCount() {
return weatherItems.size();
}
static class WeatherViewHolder extends RecyclerView.ViewHolder {
private TextView textViewDate;
private TextView textViewTime;
private TextView textView;
private TextView textViewDegree;
private TextView textViewPressure;
private TextView textViewHumidity;
private TextView textViewSpeedWind;
private TextView textViewGustWind;
private TextView textViewDirectionWind;
public WeatherViewHolder(#NonNull View itemView) {
super(itemView);
textViewDate = itemView.findViewById(R.id.textViewDate);
textViewTime = itemView.findViewById(R.id.textViewTime);
textView = itemView.findViewById(R.id.textViewFallout);
textViewDegree = itemView.findViewById(R.id.textViewDegree);
textViewPressure = itemView.findViewById(R.id.textViewPressure);
textViewHumidity = itemView.findViewById(R.id.textViewHumidity);
textViewSpeedWind = itemView.findViewById(R.id.textViewSpeedWind);
textViewGustWind = itemView.findViewById(R.id.textViewGustWind);
textViewDirectionWind = itemView.findViewById(R.id.textViewDirectionWind);
}
}
}
And finaly my code in MainActivity:
public class MainActivity extends AppCompatActivity {
EditText editTextRequestCity;
private RecyclerView recyclerViewListForecast;
WeatherAdapter adapter;
private ArrayList<WeatherItem> weatherItems = new ArrayList<>();
private final String WEATHER_URL = "https://api.openweathermap.org/data/2.5/forecast?q=%s&lang=ru&units=metric&appid=ce288368c68807e060c17369bfbef3b3";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextRequestCity = findViewById(R.id.editTextRequestCity);
recyclerViewListForecast = findViewById(R.id.recyclerViewListForecast);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
recyclerViewListForecast.setLayoutManager(linearLayoutManager);
adapter = new WeatherAdapter(getApplicationContext(), weatherItems = new ArrayList<>());
recyclerViewListForecast.setAdapter(adapter);
}
public void onClickShowWeather(View view) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
weatherItems.clear();
adapter.notifyDataSetChanged();
String city = editTextRequestCity.getText().toString().trim();
String request = String.format(WEATHER_URL,city);
DownLoadWeatherTask task = new DownLoadWeatherTask();
task.execute(request);
}
private class DownLoadWeatherTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
URL url = null;
HttpURLConnection urlConnection = null;
StringBuilder result = new StringBuilder();
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
result.append(line);
line = reader.readLine();
}
return result.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null) {
try {
JSONObject jsonObjectMain = new JSONObject(s);
JSONArray jsonArray = jsonObjectMain.getJSONArray("list");
for (int i = 0; i < jsonArray.length(); i++) {
ArrayList<WeatherItem> weatherItemDay = new ArrayList<>();
JSONObject jsonObjectDay = jsonArray.getJSONObject(i);
String dateTime = jsonObjectDay.getString("dt_txt");
String date = dateTime.substring(0, 10).trim();
String time = dateTime.substring(11, 16).trim();
String fallout = jsonObjectDay.getJSONArray("weather").getJSONObject(0).getString("description").trim();
String degree = String.format("" + jsonObjectDay.getJSONObject("main").getInt("temp")).trim();
String pressure = String.format("" + jsonObjectDay.getJSONObject("main").getInt("pressure")).trim();
String humidity = String.format("" + jsonObjectDay.getJSONObject("main").getInt("humidity")).trim();
String speedWind = String.format("" + jsonObjectDay.getJSONObject("wind").getInt("speed")).trim();
String gustWind = String.format("" + jsonObjectDay.getJSONObject("wind").getInt("gust")).trim();
String directionWind = String.format("" + jsonObjectDay.getJSONObject("wind").getInt("deg")).trim();
weatherItems.add(new WeatherItem(date, time, fallout, degree, pressure, humidity, speedWind, gustWind, directionWind));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
Call notifyDataSetChanged() when you add a new item to your list. Based on your code, this needs to happen in onPostExecute for you.
You are already calling notifyDataSetChanged() in the onClick but this is before the task has finished, therefore the item doesn't show because it hasn't been added to the list yet.

Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference in my Adapter class [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I'm having these error on my coding
Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference onBindViewHolder(BrandAdapter.java:67) and
BrandAdapter.onBindViewHolder(BrandAdapter.java:34).
I'm not really sure what went wrong as I follow the tutorial very closely. And my database is not empty.
It contains child.
this is my adapter class
public class BrandAdapter extends RecyclerView.Adapter<BrandAdapter.MyViewHolder> {
private Context context;
List<String> key;
ArrayList<Brand> brandList;
public BrandAdapter(ArrayList<Brand> brandList) {
this.brandList = brandList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.brand_list, viewGroup, false);
context = viewGroup.getContext();
return new BrandAdapter.MyViewHolder(view);
}
public BrandAdapter(Context c) {
this.context = c;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, final int i) {
myViewHolder.brand_name.setText(brandList.get(i).getBrand_name());
Picasso.with(context).load(brandList.get(i).getBrand_image()).into(myViewHolder.image);
// Picasso.with(mcontext).load(brand.getBrand_image()).into(myViewHolder.image);
myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String bName = brandList.get(i).getBrand_name();
String pic = brandList.get(i).getBrand_image();
Log.i("loz", bName);
Intent intent = new Intent(context, updateBrand.class);
intent.putExtra("brand_name", bName);
intent.putExtra("imgurl", pic);
context.startActivity(intent);
}
});
#Override
public int getItemCount() {
return brandList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView brand_name;
CardView brand_cv;
ImageView image, btnDelete;
LinearLayout frame_layout;
public MyViewHolder(View itemView) {
super(itemView);
brand_name = itemView.findViewById(R.id.name);
image = itemView.findViewById(R.id.image);
brand_cv = itemView.findViewById(R.id.brand_cv);
btnDelete = itemView.findViewById(R.id.delete);
frame_layout = itemView.findViewById(R.id.frame_layout);
}
}
}
my Brand Activity class
public class BrandActivity extends AppCompatActivity {
DatabaseReference databaseReference;
ArrayList<Brand> brandList;
RecyclerView recyclerView;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_brand);
databaseReference = FirebaseDatabase.getInstance().getReference("Brand").child("");
recyclerView = findViewById(R.id.rv);
searchView = findViewById(R.id.searchView);
}
#Override
protected void onStart() {
super.onStart();
if (databaseReference != null) {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
brandList = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
brandList.add(ds.getValue(Brand.class));
}
}
BrandAdapter brandAdapter = new BrandAdapter(brandList);
recyclerView.setAdapter(brandAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(BrandActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
app:cardElevation="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#color/lightgray">
<TextView
android:id="#+id/brand_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="sample"
android:textStyle="bold"
android:textColor="#color/white"
android:textAlignment="center"
android:background="#color/black"
android:textSize="20sp"
android:textAppearance="#style/TextAppearance.AppCompat.Headline" />
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#FCFAFA"
android:scaleType="centerCrop"
android:adjustViewBounds="true"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/delete"
android:layout_width="60dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:padding="8dp"
android:visibility="visible"
app:srcCompat="#drawable/trash" />
</LinearLayout>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#000" />
</androidx.cardview.widget.CardView>
Brand model
public class Brand {
public String brand_id;
public String brand_name;
public String brand_image;
public Brand(){}
public Brand(String brand_id, String brand_name, String brand_image) {
this.brand_id = brand_id;
this.brand_name = brand_name;
this.brand_image = brand_image;
}
public String getBrand_id() {
return brand_id;
}
public void setBrand_id(String brand_id) {
this.brand_id = brand_id;
}
public String getBrand_name() {
return brand_name;
}
public void setBrand_name(String brand_name) {
this.brand_name = brand_name;
}
public String getBrand_image() {
return brand_image;
}
public void setBrand_image(String brand_image) {
this.brand_image = brand_image;
}
}
In your MyViewHolder you are trying to find view that doesn't exist in your layout. So, try to change brand_name = itemView.findViewById(R.id.name) to brand_name = itemView.findViewById(R.id.brand_name). The same problem is also related to the other views in layout except image and delete: you don't have views with brand_cv and frame_layout ids.

Use SearchView with a ListView that have an image and text

I have a problem, I learnt how to use a SearchView with text, but I have an Activity where the listView have an image and text, but I couldnt find the way to display the filter.
So, I debug the code in order to understand why this happens and I get this in the LogCat:
java.lang.RuntimeException: Unable to start activity ComponentInfo{mundo.hola.app.frank.com.universidad2/mundo.hola.app.frank.com.universidad2.RankingActividad}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SearchView.setOnQueryTextListener(android.widget.SearchView$OnQueryTextListener)' on a null object reference
the code compiles great, but when I try to have access to this activity trough an Intent the App crashes.
If someone could help me i would be greatful.
activity
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbarLayout_po"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<android.support.v7.widget.Toolbar
android:id="#+id/appbar_rank"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:minHeight="?attr/actionBarSize"
>
<ImageView
android:id="#+id/home_rank"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:scaleType="center"
tools:ignore="ContentDescription"
android:src="#drawable/ic_first_page_24dp" />
<SearchView
android:id="#+id/search_tecnico"
android:layout_width="match_parent"
android:layout_height="match_parent">
<requestFocus />
</SearchView>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<ListView
android:id="#+id/rankinglista"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
</android.support.design.widget.CoordinatorLayout>
item_list
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorBlanco"
android:foreground="?attr/selectableItemBackground"
android:orientation="vertical"
android:paddingBottom="8dp"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="8dp">
<ImageView
android:id="#+id/imagenR"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_centerVertical="true" />
<TextView
android:id="#+id/tv_nombreUR"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="false"
android:layout_marginLeft="56dp"
android:layout_marginStart="65dp"
android:textColor="#android:color/black"
tools:text="NombreU" />
<TextView
android:id="#+id/tv_PuntajeR"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tv_nombreUR"
android:layout_alignStart="#+id/tv_nombreUR"
android:layout_below="#+id/tv_nombreUR"
tools:text="Puntaje" />
<TextView
android:id="#+id/tv_NpuntajeR"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tv_PuntajeR"
android:layout_alignParentBottom="false"
android:layout_alignStart="#+id/tv_PuntajeR"
android:layout_alignWithParentIfMissing="false"
android:layout_below="#+id/tv_PuntajeR"
android:textColor="#android:color/holo_red_dark"
tools:text="11223344" />
</RelativeLayout>
Class Ranking
public class Ranking {
private int Id;
private String Titulo;
private String Puntaje;
private String NPuntaje;
private int Imagen;
public Ranking(int id, String titulo, String puntaje, String NPuntaje, int imagen) {
Id = id;
Titulo = titulo;
Puntaje = puntaje;
this.NPuntaje = NPuntaje;
Imagen = imagen;
}
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getTitulo() {
return Titulo;
}
public void setTitulo(String titulo) {
Titulo = titulo;
}
public String getPuntaje() {
return Puntaje;
}
public void setPuntaje(String puntaje) {
Puntaje = puntaje;
}
public String getNPuntaje() {
return NPuntaje;
}
public void setNPuntaje(String NPuntaje) {
this.NPuntaje = NPuntaje;
}
public int getImagen() {
return Imagen;
}
public void setImagen(int imagen) {
Imagen = imagen;
}
}
Activity Class
public class RankingActividad extends AppCompatActivity {
ImageView inicio1;
SearchView sv;
Toolbar toolbar1;
ListView listadatos;
ArrayList<Ranking> Lista;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ranking_actividad);
inicio1 = (ImageView) findViewById(R.id.home_rank);
sv = (SearchView) findViewById(R.id.search);
toolbar1 = (Toolbar) findViewById(R.id.appbar_rank);
listadatos = (ListView) findViewById(R.id.rankinglista);
Lista = new ArrayList<Ranking>();
Lista.add(new Ranking(1,"Universidad 1","Puntaje","4512",R.drawable.ufps));
Lista.add(new Ranking(2,"universidad 2","Puntaje","4512",R.drawable.unip));
Lista.add(new Ranking(3,"universidad 3","Puntaje","4512",R.drawable.ufps));
Lista.add(new Ranking(4,"universidad 4","Puntaje","4512",R.drawable.ufps));
final RankingAdaptador rankingAdaptador = new RankingAdaptador(getApplicationContext(),Lista);
listadatos.setAdapter(rankingAdaptador);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if(TextUtils.isEmpty(s)){
rankingAdaptador.filter("");
listadatos.clearTextFilter();
}else{
String texto = s;
rankingAdaptador.filter(s);
}
return true;
}
});
Adapter Class
public class RankingAdaptador extends BaseAdapter {
Context context;
LayoutInflater inflater;
List<Ranking> ListaObjetos;
private ArrayList<Ranking> arraylist;
public RankingAdaptador(Context context, List<Ranking> listaObjetos) {
this.context = context;
ListaObjetos = listaObjetos;
inflater = LayoutInflater.from(context);
this.arraylist = new ArrayList<Ranking>();
this.arraylist.addAll(ListaObjetos);
}
public class ViewHolder{
TextView mtitulo,mpuntaje,npuntaje;
ImageView mimagen;
}
#Override
public int getCount() {
return ListaObjetos.size(); //retorna la cantidad de elementos de la lista
}
#Override
public Object getItem(int i) {
return ListaObjetos.get(i);
}
#Override
public long getItemId(int i) {
return ListaObjetos.get(i).getId();
}
#Override
public View getView(int position, View view, ViewGroup parent) {
ViewHolder holder;
if (view==null){
holder = new ViewHolder();
view = inflater.inflate(R.layout.ranking_item_lista,null);
// localizar los items de la lista
holder.mimagen = view.findViewById(R.id.imagenR);
holder.mtitulo = view.findViewById(R.id.tv_nombreUR);
holder.mpuntaje = view.findViewById(R.id.tv_PuntajeR);
holder.npuntaje = view.findViewById(R.id.tv_NpuntajeR);
view.setTag(holder);
}else {
holder = (ViewHolder)view.getTag();
}
// setear los textos de la lista
holder.mtitulo.setText(ListaObjetos.get(position).getTitulo());
holder.mpuntaje.setText(ListaObjetos.get(position).getPuntaje());
holder.npuntaje.setText(ListaObjetos.get(position).getNPuntaje());
// setear las imagenes de la lista
holder.mimagen.setImageResource(ListaObjetos.get(position).getImagen());
return null;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
ListaObjetos.clear();
if (charText.length() == 0) {
ListaObjetos.addAll(arraylist);
} else {
for (Ranking wp : arraylist) {
if (wp.getTitulo().toLowerCase(Locale.getDefault()).contains(charText)) {
ListaObjetos.add(wp);
}
}
}
notifyDataSetChanged();
}}
sv.setOnQueryTextListener(new Sear...
You never initialized sv, so it's null. Add this:
sv = (SearchView) findViewById(R.id.search_tecnico);

RecyclerView - I can't add more than 1 line

I'm with a problem to add more than 1 line(item) in my RecyclerView, the item overwrites the previous one when I tap the button, but if I create a List<> with data in hardcoded on onCreate, It works adding more than 1 line in the RecyclerView. Follow the code:
ListChecklistAdapter
public class ListChecklistAdapter extends RecyclerView.Adapter<ListChecklistAdapter.ListChecklistViewHolder> {
private List<Checklist> mChecklist;
private Context mCtx;
public ListChecklistAdapter(Context ctx, List<Checklist> checklists) {
mCtx = ctx;
mChecklist = checklists;
}
#Override
public ListChecklistViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mCtx).inflate(R.layout.item_checklist, parent, false);
return new ListChecklistViewHolder(view);
}
#Override
public void onBindViewHolder(ListChecklistViewHolder holder, int position) {
holder.cbItem.setText(mChecklist.get(position).getDescricao());
holder.cbItem.setChecked(mChecklist.get(position).isCheckado());
}
#Override
public int getItemCount() {
return mChecklist.size();
}
public class ListChecklistViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.item_checkbox)
CheckBox cbItem;
public ListChecklistViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
public void refreshData(List<Checklist> item) {
this.mChecklist.clear();
this.mChecklist.addAll(item);
notifyDataSetChanged();
}
}
item_checklist
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="#+id/item_checkbox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:paddingLeft="6dp"
android:text=" "
tools:text="Exemplo de item de lista" />
</RelativeLayout>
MainActivity
public class MainActivity extends AppCompatActivity {
#BindView(R.id.rcv_lista)
RecyclerView rvLista;
int valor;
private List<Checklist> lista;
private ListChecklistAdapter listChecklistAdapter;
#BindView(R.id.btn_add_item)
Button btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
private int cont() {
return valor++;
}
public void novoItem(View view) {
lista = new ArrayList<>();
lista.add(new Checklist("Item " + (cont() + 1), true));
loadRecycler(lista);
}
private void loadRecycler(List<Checklist> lista) {
if (listChecklistAdapter == null) {
Log.i("LOG", "IF");
listChecklistAdapter = new ListChecklistAdapter(this, lista);
rvLista.setAdapter(listChecklistAdapter);
rvLista.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
rvLista.addItemDecoration(new DividerItemDecoration(this, 1));
return;
} else {
Log.i("LOG", "ELSE");
listChecklistAdapter.refreshData(lista);
listChecklistAdapter.onAttachedToRecyclerView(rvLista);
}
}
}
activity_main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context="teste.com.br.recyclercomcheckbox.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/rcv_lista"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/btn_add_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginTop="5dp"
android:background="#android:color/transparent"
android:onClick="novoItem"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:text="+ novo item"
android:textColor="#009688" />
</LinearLayout>
Just remove this line this.mChecklist.clear(); from your refreshData() method.
public void refreshData(List<Checklist> item) {
this.mChecklist.addAll(item);
notifyDataSetChanged();
}
#Nilesh Rathod solved the problem! I just deleted this.mChecklist.clear(); from the ListCheckAdapter.java > refreshData()
Thanks for everyone to help too!

populating alert dialog with list view,JSON

I am trying to fill an alert dialog with a JSON response how ever i am getting the following error :
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
i have inflated the list view in the onCreate as other posts suggest
i have included all relevant xml and java code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<CheckedTextView
android:id="#+id/text1"
android:layout_width="match_parent"
android:layout_height="?listPreferredItemHeightSmall"
android:checkMark="?android:attr/listChoiceIndicatorSingle"
android:gravity="center_vertical"
android:paddingLeft="?listPreferredItemPaddingLeft"
android:paddingRight="?listPreferredItemPaddingRight"
android:textAppearance="?textAppearanceListItemSmall" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/colorPrimary"
tools:context=".Queue.QueueStatusFragment">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listviewResp"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingTop="15dp"
android:layout_centerVertical="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
public class QueueStatusFragment extends Fragment{
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
private TextView txtQueue;
private TextView txtCust;
private TextView txtTime;
private TextView txtBranch;
private String urlString;
private Button btnLeave;
private int reasonId;
ListView list;
public QueueStatusFragment()
{}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_queuestatus, container, false);
txtQueue = (TextView) v.findViewById(R.id.txtQueue);
txtTime = (TextView) v.findViewById(R.id.txtTime);
txtCust = (TextView) v.findViewById(R.id.txtCust);
txtBranch = (TextView) v.findViewById(R.id.txtBranch);
list=(ListView)v.findViewById(R.id.listviewResp);
btnLeave = (Button) v.findViewById(R.id.btnLeave);
SessionV globalVariable = (SessionV) getActivity().getApplicationContext();
urlString = "http://172.20.10.5:1012/easyQ.svc/rest/queueDetails/" + globalVariable.getCustId();
new ProcessJson().execute(urlString);
System.out.println("works");
btnLeave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog alertDialog = new AlertDialog.Builder(
getActivity()).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("You are about to leave the queue, are you sure?");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
urlString = "http://172.20.10.5:1012/easyQ.svc/rest/reasons";
new getReasons().execute(urlString);
for(int i = 0; i < oslist.size();i++)
{
String id = oslist.get(i).get("id");
System.out.println(id);
}
}
});
alertDialog.show();
// SessionV globalVariable = (SessionV) getActivity().getApplicationContext();
//String urlString1 = "http://172.20.10.5:1012/easyQ.svc/rest/leaveQueue";
// new JsonHandler().execute(urlString1);
//System.out.println("works");
}
});
// Inflate the layout for this fragment
return v;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
private class ProcessJson extends AsyncTask<String, Void, String> {
protected String doInBackground(String... strings) {
String stream;
String urlString = strings[0];
HTTPDataHandler hh = new HTTPDataHandler();
stream = hh.GetHTTPData(urlString);
// Return the data from specified url
System.out.println(stream);
return stream;
}
protected void onPostExecute(String stream) {
if (stream != null) {
String[] array = stream.split(",");
String part1 = array[1];
String part2 = array[2];
String part3 = array[3];
String part4 = array[4];
String queueId = array[5];
SessionV globalVariable = (SessionV) getActivity().getApplicationContext();
globalVariable.setQueueId(queueId);
if (part1 != null && part2 != null && part3 != null) {
int minutes = (int) Integer.parseInt(part1) / 60;
txtBranch.append("Branch Name: " + part4);
txtQueue.append("Service Name: " + part3);
txtCust.append("Queue Position: " + part2);
txtTime.append("Waiting Time: " + minutes + " minutes");
}
}
}
}
private class getReasons extends AsyncTask<String, Void, String>{
protected String doInBackground(String... strings) {
String stream;
String urlString = strings[0];
HTTPDataHandler hh = new HTTPDataHandler();
stream = hh.GetHTTPData(urlString);
// Return the data from specified url
System.out.println(stream);
return stream;
}
protected void onPostExecute(String stream) {
if (stream != null)
{
try
{
JSONObject object = new JSONObject(stream);
JSONArray array = object.getJSONArray("reasonsResult");
for(int i = 0 ; i < array.length(); i++) {
JSONObject reasonObj = array.getJSONObject(i);
String ID = reasonObj.getString("reason_leaving_id");
String reason = reasonObj.getString("description");
HashMap<String, String> map = new HashMap<String, String>();
map.put("description", reason);
map.put("id", ID);
oslist.add(map);
}
AlertDialog alertDialog = new AlertDialog.Builder(
getActivity()).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("You are about to leave the queue, are you sure?");
for(int i = 0; i < oslist.size(); i++)
{
ListAdapter adapter = new SimpleAdapter(getActivity(), oslist,
R.layout.dialog_list,
new String[] { "description"}, new int[] {
R.id.text1});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String branchId = oslist.get(+position).get("id");
final SessionV globalVariable = (SessionV) getActivity().getApplicationContext();
globalVariable.setBranchId(branchId);
Fragment fragment = null;
fragment = new JoinFragment();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container_body, fragment).commit();
}
});
}
alertDialog.show();
}
catch(JSONException e)
{
e.printStackTrace();
}
}
}
}
private class JsonHandler extends AsyncTask<String, Void, String> {
protected String doInBackground(String... strings) {
String stream;
String urlString = strings[0];
HTTPDataHandler hh = new HTTPDataHandler();
final SessionV globalVariable = (SessionV) getActivity().getApplicationContext();
System.out.println("sssss" + globalVariable.getQueueId() + globalVariable.getCustId());
JSONObject sender = new JSONObject();
try {
sender.put("queueid", globalVariable.getQueueId());
sender.put("customerid", globalVariable.getCustId());
//sender.put("reasonid",);
} catch (JSONException e) {
e.printStackTrace();
}
stream = hh.POST(urlString, sender);
// Return the data from specified url
System.out.println(stream);
return stream;
}
protected void onPostExecute(String stream) {
if (stream != null) {
if (stream.equals("\"Successful\"")) {
Toast.makeText(getActivity().getApplicationContext(),
"Successfully left Queue", Toast.LENGTH_LONG).show();
Fragment fragment=null;
fragment=new HomeFragment();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container_body, fragment).commit();
} else if (stream.equals("\"Not Exist\"")) {
Toast.makeText(getActivity().getApplicationContext(),
"Unable to leave Queue", Toast.LENGTH_LONG).show();
} else if (stream.equals("\"Not exist\"")) {
Toast.makeText(getActivity().getApplicationContext(),
"Not in queue", Toast.LENGTH_LONG).show();
}
}
}
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/colorPrimary"
tools:context=".Queue.QueueStatusFragment" >
<TextView
android:id="#+id/txtBranch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="8"
android:layout_centerHorizontal="true"
android:layout_centerInParent="false"
android:text="hello"
android:layout_marginTop="100dp"
android:gravity="center|left"
android:textColor="#ffffff"
android:textColorHint="#ffffff" />
<TextView
android:id="#+id/txtQueue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="8"
android:text="hello1"
android:layout_marginTop="160dp"
android:gravity="center|left"
android:textColor="#ffffff"
android:layout_centerHorizontal="true"
android:layout_centerInParent="false"
android:textColorHint="#ffffff" />
<TextView
android:id="#+id/txtTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="8"
android:text="hello2"
android:gravity="center|left"
android:layout_marginTop="44dp"
android:layout_centerInParent="false"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:layout_below="#+id/txtQueue"
android:layout_alignStart="#+id/txtQueue" />
<TextView
android:id="#+id/txtCust"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="8"
android:text="hello3"
android:gravity="center|left"
android:textColor="#ffffff"
android:layout_marginTop="47dp"
android:layout_centerInParent="false"
android:textColorHint="#ffffff"
android:layout_below="#+id/txtTime"
android:layout_alignStart="#+id/txtTime" />
<Button
android:id="#+id/btnLeave"
android:layout_width="312dp"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
android:gravity="center"
android:text="Leave Queue"
android:textColor="#ffffff"
android:textStyle="bold"
android:layout_marginBottom="65dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
I think your problem is in your fragment_queuestatus there is no Listview. Which you add the previous layout. That why it's not get the listview and when you try to set the adapter it's thing you set something in a NULL object. So, Add the ListView in the fragment_queuestatus layout. That will solve the problem.

Categories