Here I am trying to display the name and price of the test.
and I'm taking a recycler view to do the same using the JET Parsing GET method.
But I'm not getting anything in my business and showing myself black there.
here is my code
please help me find the solution.
Model class
public class TestListsModel {
public String test_price;
public String testlist_id;
public String test_name;
}
This is my Adapter:
public class AdapterTestList extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private LayoutInflater inflater;
List<TestListsModel> data= Collections.emptyList();
TestListsModel current;
int currentPos=0;
// create constructor to innitilize context and data sent from MainActivity
public AdapterTestList(Context context, List<TestListsModel> data){
this.context=context;
inflater= LayoutInflater.from(context);
this.data=data;
}
// Inflate the layout when viewholder created
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.test_list_row, parent,false);
MyHolder holder=new MyHolder(view);
return holder;
}
// Bind data
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
// Get current position of item in recyclerview to bind data and assign values from list
MyHolder myHolder= (MyHolder) holder;
TestListsModel current=data.get(position);
myHolder.testName.setText(current.test_name);
myHolder.testPrice.setText( current.test_price);
// load image into imageview using glide
/* Glide.with(context).load("http://192.168.1.7/test/images/" + current.fishImage)
.placeholder(R.drawable.ic_img_error)
.error(R.drawable.ic_img_error)
.into(myHolder.ivFish);*/
}
// return total item from List
#Override
public int getItemCount() {
return data.size();
}
class MyHolder extends RecyclerView.ViewHolder{
TextView testName;
TextView testPrice;
// create constructor to get widget reference
public MyHolder(View itemView) {
super(itemView);
testName = (TextView) itemView.findViewById(R.id.test_name);
testPrice = (TextView) itemView.findViewById(R.id.price_name);
}
}
}
This is my Activity Class:
public class HealthServicesActivity extends AppCompatActivity implements View.OnClickListener {
SharePreferenceManager<LoginModel> sharePreferenceManager;
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView testListRecylerView;
private AdapterTestList mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_health_services);
ButterKnife.bind(this);
sharePreferenceManager = new SharePreferenceManager<>(getApplicationContext());
dayTimeDisplay();
new AsyncLogin().execute();
}
private class AsyncLogin extends AsyncTask<String, String, String> {
//ProgressDialog pdLoading = new ProgressDialog(getApplicationContext());
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
/* pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();*/
}
#Override
protected String doInBackground(String... params) {
try {
String url_test="http://192.168.1.80/aoplnew/api/users/gettestlist/"+sharePreferenceManager.getUserLoginData(LoginModel.class).getResult().getCenterId();
// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
//url = new URL("http://192.168.1.7/test/example.json");
url = new URL(url_test);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("[]");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
//pdLoading.dismiss();
List<TestListsModel> data=new ArrayList<>();
//pdLoading.dismiss();
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
TestListsModel testData = new TestListsModel();
testData.testlist_id= json_data.getString("testlist_id");
testData.test_name= json_data.getString("test_name");
testData.test_price= json_data.getString("test_price");
data.add(testData);
}
// Setup and Handover data to recyclerview
testListRecylerView = (RecyclerView)findViewById(R.id.test_list_recycler_view);
mAdapter = new AdapterTestList(HealthServicesActivity.this, data);
testListRecylerView.setAdapter(mAdapter);
testListRecylerView.setLayoutManager(new LinearLayoutManager(HealthServicesActivity.this));
} catch (JSONException e) {
Toast.makeText(HealthServicesActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
Thanks in advance for any answer!
You need to set the setLayoutManager before the setting the adapter like below. In your code, you have setAdapter() before the setLayoutManager therefore your adapter not set properly.
Refer this for the further explanation https://developer.android.com/guide/topics/ui/layout/recyclerview
testListRecylerView = (RecyclerView)findViewById(R.id.test_list_recycler_view);
mAdapter = new AdapterTestList(HealthServicesActivity.this, data);
/**
* SET THE LAYOUT MANAGER BEFORE SETTING THE ADAPTER
*/
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(HealthServicesActivity.this);
testListRecylerView.setLayoutManager(mLayoutManager);
testListRecylerView.setItemAnimator(new DefaultItemAnimator());
/**
* AND THAN SET THE ADAPTER
*/
testListRecylerView.setAdapter(mAdapter);
Related
Im new to android development have very basic knowledge of this whatever i have achieved till now is achieved using this website or youtube videos i'm stuck in AsyncTask (Earlier i was using .get() on Create View and it was working fine but UI Was blocked until task is finished. To Avoid UI Blocking i was advice to remove .get() function from OnCreateView() function now after removing this im not being able to get any data from AsyncTask). I did that but now i'm not being able to create view i did lots of research but unable to get this strength
Here is my Codes Please Help how to create view from this
OnCreateView() :-
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View GView = inflater.inflate(R.layout.fragment_dashboard, container, false);
progressBarHolder = (FrameLayout) GView.findViewById(R.id.progressBarHolder);
GridView gridView = (GridView) GView.findViewById(R.id.gridView);
//Toast.makeText(getActivity(),Json_String,Toast.LENGTH_LONG).show();
String finalResult = null;
try{
finalResult = String.valueOf(new JSONTask().execute("https://www.example.in/android_api/dashboard_data",JsonData()));
Toast.makeText(getActivity(),Json_String,Toast.LENGTH_LONG).show();
JSONObject parentObject = null;
parentObject = new JSONObject(finalResult);
if(((String) parentObject.names().get(0)).matches("error")){
JSONObject jObj = parentObject.getJSONObject("error");
errorThrow(jObj.getString("Description"));
} else if(((String) parentObject.names().get(0)).matches("success")){
JSONObject jObj = parentObject.getJSONObject("success");
JSONArray arrajson = jObj.getJSONArray("data");
String arrayCount = Integer.toString(arrajson.length());
String[] type = new String[arrajson.length()];
Integer[] count = new Integer[arrajson.length()];
for (int i=0; i<arrajson.length();i++){
JSONObject jsonObject = arrajson.getJSONObject(i);
type[i] = jsonObject.getString("type");
count[i] = jsonObject.getInt("count");
}
CustomAdpter customAdpter = new CustomAdpter(DashboardFragment.this,type,count);
gridView.setAdapter(customAdpter);
return GView;
}
} catch (JSONException e) {
e.printStackTrace();
}
return GView;
}
Base Adapter Code :-
class CustomAdpter extends BaseAdapter {
String[] type;
Integer[] count;
public CustomAdpter(DashboardFragment dashboardFragment, String[] type, Integer[] count){
this.count = count;
this.type = type;
}
#Override
public int getCount() {
return type.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = getLayoutInflater().inflate(R.layout.grid_single_itme,null);
TextView textView = (TextView) view.findViewById(R.id.TextView1);
TextView textView1 = (TextView) view.findViewById(R.id.textView2);
textView.setText(String.valueOf(count[i]));
textView1.setText(type[i]);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(),"Booking Item Clicked",Toast.LENGTH_LONG).show();
}
});
return view;
}
}
AsyncTask Code :-
public class JSONTask extends AsyncTask<String,String,String> {
private ProgressDialog mProgressDialog;
int progress;
public JSONTask(){
mProgressDialog = new ProgressDialog(getContext());
mProgressDialog.setMax(100);
mProgressDialog.setProgress(0);
}
#Override
protected void onPreExecute(){
mProgressDialog = ProgressDialog.show(getContext(),"Loading","Loading Data...",true,false);
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
final String finalJson = params[1];
String json = finalJson;
try{
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setRequestProperty("A-APK-API", "******");
connection.setRequestProperty("Authorization", "Basic **:**");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.connect();
OutputStream stream = connection.getOutputStream();
OutputStreamWriter streams = new OutputStreamWriter(stream, "UTF-8");
stream.write(json.getBytes("UTF-8"));
stream.close();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
StringBuffer buffer = new StringBuffer();
String line = "";
while((line = reader.readLine()) != null){
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(connection != null){
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e){
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String result){
super.onPostExecute(result);
Json_String = result;
Toast.makeText(getContext(),result,Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
}
}
Please help me here
You cannot get a result from asynctask when you dont use .get().
So change that statement. Start only the asynctask.
Then put all the code after that line in onPostExecute() of the AsyncTask.
Thats all.
you should change way you are creating the Adapter and attaching
you should do this
1.At first get the data in List,ArrayList etc. via AsyncTask, doInBackGround method
then on the onPostExecute method retrieve the data and create Adapter and attach it to your View
While you are getting data you can show some ProgressDialog.
If your AsyncTask is in other separate class then use interface to get the data from your AsyncTask class
look at this https://stackoverflow.com/a/47373959/8197737
I am trying to show data in custom listView using API
there is no error but data is not shown in custom list .i made separate
class for asyncTask ,Adapters and model.
code of asyncTask is
public class CourseOutlinesTask extends AsyncTask<String, String, String> {
ProgressDialog dialog;
Context context;
private ArrayList<CourseModel> postList = new ArrayList<CourseModel>();
private ListView listView;
private View root;
TrainerCourseAdapter adapter;
String json_string;
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//close process dialog
if (this.dialog != null) {
this.dialog.dismiss();
}
//parse json
try {
JSONObject jsonParse = new JSONObject(result);
JSONArray query = jsonParse.getJSONArray("courses");
for (int i = 0; i < query.length(); i++) {
try {
JSONObject jsonParser = query.getJSONObject(i);
CourseModel post = new CourseModel();
post.setId(jsonParser.getInt("id"));
post.setTitle(jsonParser.getString("title"));
post.setStatus(jsonParser.getString("status"));
post.setDescription(jsonParser.getString("description"));
System.out.println(post.getStatus()+"asdadasdad");
System.out.println(post);
postList.add(post);
TrainerCourseAdapter adapter = new TrainerCourseAdapter(context,postList);
}catch (Exception e) {
System.out.println(e);
}
// Parsing json
post.setDescription(obj.getString("description"));
// ****Handle CreationDate-Object
// Genre is json array
}
} else {
MyAppUtil.getToast(getApplicationContext(), message);
}*/
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
code of my adapter class is
public class TrainerCourseAdapter extends BaseAdapter {
private List list;
private Context context;
private static LayoutInflater inflater = null;
String [] cName;
String [] cDetail;
String [] created;
String [] cStatus;
TextView c_name,c_detail,c_date,c_status;
ArrayList<CourseModel> itemList;
Context mcontext;
public TrainerCourseAdapter(Context context,List list) {
mcontext = context;
itemList = (ArrayList<CourseModel>) list;
}
#Override
public int getCount() {
return itemList.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
public void setItemList(ArrayList<CourseModel> itemList) {
this.itemList = itemList;
}
public class Holder
{
TextView c_name;
TextView c_detail;
TextView c_date ;
Button c_status;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
Holder holder = new Holder();
View rowView;
rowView = inflater.inflate(R.layout.row_courses_list, viewGroup,false);
this.c_name = (TextView) rowView.findViewById(R.id.txt_courseName);
this.c_detail = (TextView) rowView.findViewById(R.id.txt_courseDetail);
this.c_date = (TextView) rowView.findViewById(R.id.txt_courseDate);
this.c_status = (Button) rowView.findViewById(R.id.btn_courseStatus);
System.out.println("Mudassir Don");
final CourseModel data = itemList.get(i);
this.c_name.setText(data.getTitle());
this.c_detail.setText(data.getDescription());
this.c_status.setText(data.getStatus());
this.c_date.setText(data.getId());
System.out.println(c_date);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "You Clicked "+ cName[i], Toast.LENGTH_LONG).show();
}
});
return rowView;
}
}
code of activity is
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_outlines);
CourseOutlinesTask task = new CourseOutlinesTask();
task.execute("http://mantis.vu.edu.pk/bridging_the_gap/public/viewCourseOutlines");
mylist = task.viewResult();
listView = (ListView) findViewById(R.id.course_listView);
listView.setAdapter(new TrainerCourseAdapter(CourseOutlinesActivity.this,mylist ) {
});
You need to assign your custom Adapter to listView.
yourListView.setAdapter(yourAdapter);
In your case, inside onPostExecute method of CourseOutlinesTask you should write it.
TrainerCourseAdapter adapter = new TrainerCourseAdapter(context,postList);
listView = (ListView) findViewById(R.id.course_listView);
listview.setAdapter(adapter);
Hope this helps.
You need to write a interface and get response in your activity and set adapter to list view
like.
TrainerCourseAdapter adapter = new TrainerCourseAdapter(context,postList);
listView = (ListView) findViewById(R.id.course_listView);
listview.setAdapter(adapter);
You can use callBack interface to get itemArraylist data to your activity class.
After getting itemlist data in activity class you can set adapter to listview.
TrainerCourseAdapter adapter = new TrainerCourseAdapter(context, postList);
listView = (ListView) findViewById(R.id.course_listView);
listview.setAdapter(adapter);
// You can create interface in your CourseOutlinesClass with two method onSuccess() and onFailure() and in onPostExecute() send arraylist data using this interface to activity , then set adapter to fill data in listview.
Use the below code:-
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_outlines);
listView = (ListView) findViewById(R.id.course_listView);
new CourseOutlinesTask().execute("http://mantis.vu.edu.pk/bridging_the_gap/public/viewCourseOutlines");
}
and in postExecute of your AsyncTask setAdapter to listView
TrainerCourseAdapter adapter = new TrainerCourseAdapter(context,postList);
listView.setAdapter(adapter);
My recyclerView is not displaying the item views and dont no why, and I am able to get the data from the server but the recyclerView is just not populating my data with the ui.
Here is my Adapter class that binds the itemviews with the data :
public class AdapterBooking extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private LayoutInflater inflater;
List<Booking> data= Collections.emptyList();
Booking current ;
public AdapterBooking(Context context,List<Booking> data) {
this.context = context;
this.inflater= LayoutInflater.from(context);
this.data = data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.containerbookings, parent,false);
MyHolder holder=new MyHolder(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
MyHolder myHolder = (MyHolder) holder;
current = data.get(position);
myHolder.txtAccommoName.setText(current.AccommoName);
myHolder.txtBookingDate.setText("Booking Date: " + current.BookingDate);
myHolder.txtBookingExpiry.setText("Booking Expiry: " + current.BookingDuration);
myHolder.txtBookngStatus.setText("Status " + current.AccredStatus);
myHolder.txtBookngStatus.setTextColor( ContextCompat.getColor(context, R.color.colorAccent));
Glide.with(context).load(R.drawable.the_yard_room)
.placeholder(R.drawable.ic_img_error)
.error(R.drawable.ic_img_error)
.into(myHolder.img);
}
#Override
public int getItemCount() {
return data.size();
}
class MyHolder extends RecyclerView.ViewHolder {
TextView txtAccommoName;
ImageView img;
TextView txtBookingDate;
TextView txtBookingExpiry;
TextView txtBookngStatus;
BootstrapButton btnCancel;
public MyHolder(View itemView) {
super( itemView );
txtAccommoName = (TextView)itemView.findViewById(R.id.textBookedAccommoName);
img= (ImageView) itemView.findViewById(R.id.imageBookedAccomo);
txtBookingDate = (TextView)itemView.findViewById(R.id.txtBookingDate);
txtBookingExpiry = (TextView)itemView.findViewById( R.id. txtBookingExpiry);
txtBookngStatus = (TextView)itemView.findViewById( R.id.txtBookingStatus );
btnCancel = (BootstrapButton)itemView.findViewById( R.id. btnCancelBookings);
}
Here is my Activity class that gets the data from the server:
public class BookingList extends AppCompatActivity {
List<Booking> data;
Booking booking;
RecyclerView recyclerViewBooking;
AdapterBooking mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_booking_list );
new Connect().execute();
}
private class Connect extends AsyncTask<String,String,String>
{
ProgressDialog load;
HttpURLConnection connection = null;
URL url = null;
String http = null;
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(BookingList.this);
int studID = settings.getInt("STUDENT_ID_BOOKING",0 );
public Connect() {
load = new ProgressDialog(BookingList.this);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
load.setMessage("Loading...");
load.setCancelable(false);
load.show();
}
#Override
protected String doInBackground(String... params) {
http = "http://192.168.42.197:5432/WCF/BookingServices.svc/getAllBookingsByStud/"+studID;
try {
url = new URL(http);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(15000);
connection.setConnectTimeout(10000);
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "Application/json");
connection.setDoInput(true);
} catch (IOException e) {
e.printStackTrace();
}
try {
int code = connection.getResponseCode();
System.out.println("Response: " + code);
if(code ==HttpURLConnection.HTTP_OK)
{
InputStream input = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line = null;
while((line=reader.readLine()) != null)
{
result.append(line);
}
System.out.println(result.toString());
return (result.toString());
}else {
return("Unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
}finally {
connection.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
load.dismiss();
load.dismiss();
data= new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length();i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject object = jsonObject.getJSONObject("Accommodation");
JSONObject objectStudent = jsonObject.getJSONObject("Student");
booking = new Booking();
booking.Name = objectStudent.getString("Name");
booking.Surname = objectStudent.getString("Surname");
booking.StudentNumber = objectStudent.getInt("StudentNumber");
booking.AccommoName = object.getString("AccommoName");
booking.AccredStatus = object.getString("AccredStatus");
booking.BookingDate = jsonObject.getString("BookingDate");
booking.BookingDuration = jsonObject.getString("BookingDuration");
booking.BookingStatus = jsonObject.getString( "BookingStatus" );
data.add(booking);
}
recyclerViewBooking = (RecyclerView)findViewById(R.id.listOfbooks);
mAdapter = new AdapterBooking(BookingList.this,data);
recyclerViewBooking.setAdapter(mAdapter);
recyclerViewBooking.setLayoutManager(new LinearLayoutManager(BookingList.this));
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(BookingList.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
Check your Layout, make sure your RecyclerView isn't child of ScrollView. If you need that, you can use NestedScrollView.
If you make a breakpoint, your onBindViewHolder works?
Another thing yo can try:
There is a RecyclerView method: setHasStableIds(boolean).
#Override
public void setHasStableIds(boolean hasStableIds) {
return false;
}
Also, I think the context is wrong:
In activity:
private Activity getActivity {
return this;
}
In AsyncTask:
mAdapter = new AdapterBooking(getActivity().getApplicationContext(),data);
I hope this information help you.
Good luck.
Remove this:
MyHolder myHolder = (MyHolder) holder;
Instead do this: because I think there is no need to get another holder reference when you already have it on onBindViewHolder(..) method
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
current = data.get(position);
holder.txtAccommoName.setText(current.AccommoName);
holder.txtBookingDate.setText("Booking Date: " + current.BookingDate);
holder.txtBookingExpiry.setText("Booking Expiry: " + current.BookingDuration);
holder.txtBookngStatus.setText("Status " + current.AccredStatus);
holder.txtBookngStatus.setTextColor( ContextCompat.getColor(context, R.color.colorAccent));
Glide.with(context).load(R.drawable.the_yard_room)
.placeholder(R.drawable.ic_img_error)
.error(R.drawable.ic_img_error)
.into(holder.img);
}
Try this please and do let me know if it changes anything for you.
EDIT: As pointed out by #adnbsr as well in his comments you need to check this as well because it feels wrong instead you should have done this
extends RecyclerView.Adapter<AdapterBooking.MyHolder>
Fixed the problem. Im using shared preference to store data so I used the wrong key to get a value from the shared preference which before was causing the sharedpreference value to be initialized to zero.
i have some problem with my JSON code.
I want to display a list that contain text and image. The text and image stored on my online database, i using JSON for taking them down to my android app.
The JSON doesn't display any error, the text are displayed but the image are not appear.
I check the logcat and there's no error for this process. I using viewAdapter for displaying the image on the list.
Please master help me, can you gimme some simple explanation how to solve this??
Thanks...
NB. This is my code for HomeFragment.java (where i doing the JSON).
public class HomeFragment extends Fragment implements InternetConnectionListener, ApiHandler.ApiHandlerListener {
private static final String ARG_SECTION_NUMBER = "section_number";
private final int CATEGORY_ACTION = 1;
private CategorySelectionCallbacks mCallbacks;
private ArrayList<Category> categoryList;
private ListView categoryListView;
private String Error = null;
private InternetConnectionListener internetConnectionListener;
public HomeFragment() {
}
public static HomeFragment newInstance(int sectionNumber) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((HomeActivity) activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER));
try {
mCallbacks = (CategorySelectionCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement CategorySelectionCallbacks.");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
categoryListView = (ListView) rootView.findViewById(R.id.categoryListView);
return rootView;
}
#Override
public void onResume() {
super.onResume();
if (UtilMethods.isConnectedToInternet(getActivity())) {
initCategoryList();
} else {
internetConnectionListener = (InternetConnectionListener) HomeFragment.this;
showNoInternetDialog(getActivity(), internetConnectionListener,
getResources().getString(R.string.no_internet),
getResources().getString(R.string.no_internet_text),
getResources().getString(R.string.retry_string),
getResources().getString(R.string.exit_string), CATEGORY_ACTION);
}
}
public class getCategList extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
/**
* json is populating from text file. To make api call use ApiHandler class
*
* <CODE>ApiHandler apiHandler = new ApiHandler(this, URL_GET_CATEGORY);</CODE> <BR>
* <CODE>apiHandler.doApiRequest(ApiHandler.REQUEST_GET);</CODE> <BR>
*
* You will get the response in onSuccessResponse(String tag, String jsonString) method
* if successful api call has done. Do the parsing as the following.
*/
URL hp = null;
try {
hp = new URL(
getString(R.string.liveurl) + "foodcategory.php");
Log.d("URL", "" + hp);
URLConnection hpCon = hp.openConnection();
hpCon.connect();
InputStream input = hpCon.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(input));
String x = "";
x = r.readLine();
String total = "";
while (x != null) {
total += x;
x = r.readLine();
}
Log.d("UR1L", "" + total);
JSONArray j = new JSONArray(total);
Log.d("URL1", "" + j.length());
categoryList = new ArrayList<Category>();
for (int i = 0; i < j.length(); i++) {
Category category = new Category();// buat variabel category
JSONObject Obj;
Obj = j.getJSONObject(i); //sama sperti yang lama, cman ini lebih mempersingkat karena getJSONObject cm d tulis sekali aja disini
category.setId(Obj.getString(JF_ID));
category.setTitle(Obj.getString(JF_TITLE));
category.setIconUrl(Obj.getString(JF_ICON));
if (!TextUtils.isEmpty(Obj.getString(JF_BACKGROUND_IMAGE))) {
category.setImageUrl(Obj.getString(JF_BACKGROUND_IMAGE));
}
Log.d("URL1",""+Obj.getString(JF_TITLE));
categoryList.add(category);
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
categoryListView.setAdapter(new CategoryAdapter(getActivity(), mCallbacks, categoryList));
}
});
}catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Error = e.getMessage();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Error = e.getMessage();
} catch (JSONException e) {
// TODO Auto-generated catch block
Error = e.getMessage();
e.printStackTrace();
} catch (NullPointerException e) {
// TODO: handle exception
Error = e.getMessage();
}
return null;
}
}
//! function for populate category list
private void initCategoryList() {
new getCategList().execute();
}
#Override
public void onConnectionEstablished(int code) {
if (code == CATEGORY_ACTION) {
initCategoryList();
}
}
#Override
public void onUserCanceled(int code) {
if (code == CATEGORY_ACTION) {
getActivity().finish();
}
}
//! catch json response from here
#Override
public void onSuccessResponse(String tag, String jsonString) {
//! do same parsing as done in initCategoryList()
}
//! detect response error here
#Override
public void onFailureResponse(String tag) {
}
//! callback interface listen by HomeActivity to detect user click on category
public static interface CategorySelectionCallbacks {
void onCategorySelected(String catID, String title);
}
}
This code for categoryAdapter.java (where i put the result of JSON to the list)
public class CategoryAdapter extends ArrayAdapter<Category> implements View.OnClickListener {
private final LayoutInflater inflater;
private final ArrayList<Category> categoryList;
private Activity activity;
private HomeFragment.CategorySelectionCallbacks mCallbacks;
private String dummyUrl = "http://www.howiwork.org";
AbsListView.LayoutParams params;
public CategoryAdapter(Activity activity, HomeFragment.CategorySelectionCallbacks mCallbacks, ArrayList<Category> categoryList) {
super(activity, R.layout.layout_category_list);
this.activity = activity;
this.inflater = LayoutInflater.from(activity.getApplicationContext());
this.categoryList = categoryList;
this.mCallbacks = mCallbacks;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder row;
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_category_list, null);
row = new ViewHolder();
row.bannerImage = (ImageView) convertView.findViewById(R.id.catBannerImageView);
row.categoryImage = (ImageView) convertView.findViewById(R.id.catImageView);
row.categoryName = (TextView) convertView.findViewById(R.id.catNameTV);
} else {
row = (ViewHolder) convertView.getTag();
}
Category category = categoryList.get(position);
Picasso.with(activity).load(UtilMethods
.getDrawableFromFileName(activity,category.getIconUrl()))
.tag(category.getIconUrl())
.into(row.categoryImage);
row.categoryName.setText(category.getTitle());
Picasso.with(activity)
.load(UtilMethods.getDrawableFromFileName(activity,category.getImageUrl()))
.placeholder(R.drawable.img_banner_placeholder)
.tag(category.getIconUrl())
.fit()
.into(row.bannerImage);
row.bannerImage.setOnClickListener(this);
row.categoryImage.setTag(position);
row.categoryName.setTag(position);
row.bannerImage.setTag(position);
return convertView;
}
#Override
public int getCount() {
return categoryList.size();
}
#Override
public void onClick(View v) {
int position = Integer.parseInt(v.getTag().toString());
mCallbacks.onCategorySelected(categoryList.get(position).getId(),
categoryList.get(position).getTitle());
}
private static class ViewHolder {
public ImageView bannerImage;
public TextView categoryName;
public ImageView categoryImage;
}
}
Try this.
Picasso.with(activity).load(category.getIconUrl())
.into(row.categoryImage);
If it worked !. You Check the UtilMethods.getDrawableFromFileName() !!!
I have an app which downloads YouTube JSON data. The code works perfectly in a desktop app, but not in android (the list is null when trying to iterate through it). Here's my code which matters:
public String DownloadJSONData(){
BufferedReader reader = null;
String webc = "";
try{
URL url = new URL("http://gdata.youtube.com/feeds/api/users/thecovery/uploads?v=2&alt=json");
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while((read = reader.read(chars)) != -1){
buffer.append(chars,0,read);
}
webc = buffer.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
return webc;
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println(webc);
return webc;
}
public void GetData() throws JSONException {
JSONObject obj = new JSONObject(DownloadJSONData());
JSONArray feed = obj.getJSONObject("feed").getJSONArray("entry");
for(int i = 0; i < feed.length(); i++){
EPISODE_NAME.add(feed.getJSONObject(i).getJSONObject("title").getString("$t"));
EPISODE_LINK.add(feed.getJSONObject(i).getJSONArray("link").getJSONObject(0).getString("href"));
}
ListView episodes = (ListView) findViewById(R.id.episodeChooser);
ArrayAdapter<String> episodesSource = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,EPISODE_NAME);
}
}
In the onCreate method, I call the GetData() method, and I try to set the adapter to the ListView from the EPISODE_NAME ArrayList, but it's null. I also tried to set the adapter after the method, in onCreate, but no luck. Anyone can help?
It works fine
Add Below permission in Manifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
ManiActivity.java
public class MainActivity extends Activity {
private ListView listView;
private List<FeedsDTO> feedsList = new ArrayList<FeedsDTO>();
private FeedsDTO dto = null;
private BackgroundThread backgroundThread;
private CustomAdapter customAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listview);
backgroundThread = new BackgroundThread();
backgroundThread.execute();
}
private void setListViewAdapter(){
customAdapter = new CustomAdapter(this, R.layout.listitem, feedsList);
listView.setAdapter(customAdapter);
}
private class BackgroundThread extends AsyncTask<Void, Void, String> {
private ProgressDialog progressBar = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar = new ProgressDialog(MainActivity.this);
progressBar.setCancelable(false);
progressBar.show();
}
#Override
protected String doInBackground(Void... params) {
BufferedReader reader = null;
String webc = "";
try{
URL url = new URL("http://gdata.youtube.com/feeds/api/users/thecovery/uploads?v=2&alt=json");
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while((read = reader.read(chars)) != -1){
buffer.append(chars,0,read);
}
webc = buffer.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
return webc;
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println(webc);
return webc;
}
#Override
protected void onPostExecute(String result) {
JSONObject obj;
try {
obj = new JSONObject(result);
JSONArray feed = obj.getJSONObject("feed").getJSONArray("entry");
Log.i("=======", "========="+feed.length());
for(int i = 0; i < feed.length(); i++){
dto = new FeedsDTO();
dto.setName(feed.getJSONObject(i).getJSONObject("title").getString("$t"));
dto.setLink(feed.getJSONObject(i).getJSONArray("link").getJSONObject(0).getString("href"));
feedsList.add(dto);
dto = null;
}
Log.i("=======LIst Size", "========="+feedsList.size());
progressBar.dismiss();
setListViewAdapter();
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(result);
}
}
}
CustomAdapter.java
public class CustomAdapter extends ArrayAdapter<FeedsDTO>{
private LayoutInflater inflater;
private int layoutID;
public CustomAdapter(Context cntx, int resource, List<FeedsDTO> objects) {
super(cntx, resource, objects);
this.inflater =(LayoutInflater) cntx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.layoutID = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
try {
ViewHolder holder = null;
if (convertView == null) {
convertView = inflater.inflate(layoutID, null);
holder = new ViewHolder();
holder.NameTV = (TextView) convertView.findViewById(R.id.textview);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
FeedsDTO feedsDTO = getItem(position);
holder.NameTV.setText(feedsDTO.getName());
feedsDTO = null;
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
private class ViewHolder{
TextView NameTV;
}
}
FeedsDTO.java
public class FeedsDTO {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
private String link;
}
listitem.xlm:-
<?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="vertical" >
<TextView
android:id="#+id/textview"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</TextView>
I hope this code will work perfectly
Most apps include several different activities that allow the user to
perform different actions. Whether an activity is the main activity
that's created when the user clicks your app icon or a different
activity that your app starts in response to a user action, the system
creates every new instance of Activity by calling its onCreate()
method.
You must implement the onCreate() method to perform basic application
startup logic that should happen only once for the entire life of the
activity. For example, your implementation of onCreate() should define
the user interface and possibly instantiate some class-scope
variables.
For example, the following example of the onCreate() method shows some
code that performs some fundamental setup for the activity, such as
declaring the user interface (defined in an XML layout file), defining
member variables, and configuring some of the UI.
You are basically mixing stuff left and right. First create your Interface in the onCreate() and do the logic in onStart().
You should read the android lifecycle. See here