listview won't populate from other class - java

i'm new to java and android(programmed in C# before).
i'm trying to populate a listview with a custom layout but nothing happens.
the listview is in the main activity and is being updated from a separate class.
here is all the stuff that i am trying to find the problem in:
activity_main.xml
<?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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.nasir.pre_alpha.MainActivity"
android:orientation="vertical">
<Button
android:text="Get Messages"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/msg_list"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="18dp"
android:onClick="onClick" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="15dp"
android:layout_below="#+id/msg_list"
android:id="#+id/msg_listview" />
</RelativeLayout>
list_view_layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/linearlayout">
<TextView
android:text="Number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView" />
<TextView
android:text="NUMBER"
android:layout_width="171dp"
android:layout_height="wrap_content"
android:id="#+id/txt_number" />
<TextView
android:text="Message Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView3" />
<TextView
android:text="TEXT"
android:layout_height="wrap_content"
android:id="#+id/txt_msg"
android:layout_width="171dp" />
</LinearLayout>
MainActivity.java:
package com.nasir.pre_alpha;
import android.Manifest;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(this ,new String[]{Manifest.permission.READ_SMS},255);
}
public void onClick (View l){
ContentResolver rslv=getContentResolver();
final String[] p=new String[]{"*"};
Uri uri=Uri.parse("content://sms");
Cursor cursor=rslv.query(uri,p,null,null,null);
cursor.moveToFirst();
ArrayList<String> numbers=new ArrayList<>();
ArrayList<String> msg_body=new ArrayList<>();
while (cursor.moveToNext()){
numbers.add(cursor.getString(cursor.getColumnIndex("address")));
msg_body.add(cursor.getString(cursor.getColumnIndex("body")));
}
model m=new model();
view v=new view();
controller c=new controller(m,v,getApplicationContext());
c.set_data(numbers,msg_body);
c.view_data();
}
}
model.java:
package com.nasir.pre_alpha;
import java.util.ArrayList;
/**
* Created by Rhasta on 6/26/2017.
*/
public class model {
private ArrayList<String> numbers=new ArrayList<>();
private ArrayList<String> msg_body=new ArrayList<>();
public ArrayList<String> get_numbers(){
return numbers;
}
public ArrayList<String> getMsg_body(){
return msg_body;
}
public void set_numbers(ArrayList<String> numbers){
this.numbers=numbers;
}
public void set_Msgbody(ArrayList<String> msg_body){
this.msg_body=msg_body;
}
}
view.java:
package com.nasir.pre_alpha;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Rhasta on 6/26/2017.
*/
public class view {
private Context c;
private class viewadapter extends BaseAdapter{
private ArrayList<String> numbers=new ArrayList<>();
private ArrayList<String> msg_body=new ArrayList<>();
public viewadapter(ArrayList<String> numbers,ArrayList<String> msg_body){
this.numbers=numbers;
this.msg_body=msg_body;
}
public int getCount(){
return numbers.size();
}
public View getView(int pos, View view, ViewGroup viewGroup){
LayoutInflater inflater=(LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row=inflater.inflate(R.layout.list_view_layout,null);
TextView number=(TextView)row.findViewById(R.id.txt_number);
number.setText(numbers.get(pos));
TextView msg_body=(TextView)row.findViewById(R.id.txt_msg);
Toast.makeText(c,msg_body.getText(),Toast.LENGTH_SHORT).show();
msg_body.setText(this.msg_body.get(pos));
return row;
}
public long getItemId(int pos){
return pos;
}
public Object getItem(int arg){
return null;
}
}
void set_context(Context context){
c=context;
}
public void update_data(ArrayList<String> numbers,ArrayList<String> msg_body){
viewadapter adapter=new viewadapter(numbers,msg_body);
LayoutInflater inflater=(LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v=inflater.inflate(R.layout.activity_main,null);
ListView lst=(ListView)v.findViewById(R.id.msg_listview);
lst.setAdapter(adapter);
}
}
controller.java:
package com.nasir.pre_alpha;
import android.content.Context;
import java.util.ArrayList;
/**
* Created by Rhasta on 6/26/2017.
*/
public class controller {
private model m;
private view v;
private Context c;
public controller(model m,view v,Context c){
this.m=m;
this.v=v;
this.c=c;
}
public void set_data(ArrayList<String> numbers,ArrayList<String> msg_body){
this.m.set_numbers(numbers);
this.m.set_Msgbody(msg_body);
}
public void view_data(){
v.set_context(c);
v.update_data(m.get_numbers(),m.getMsg_body());
}
}
but i can't find the problem.
the listview is just empty(won't show up)

You didn't initialize the listview and you haven't assigned a list of items to it. Try:
ListView listview = (ListView) findViewById(R.id.msg_listview);
listview.setAdapter(.......);

I really can't understand your code. I'd suggest you do it like this:
add this:
<uses-permission android:name="android.permission.READ_CONTACTS" />
in your manifest instead of:
ActivityCompat.requestPermissions(this ,new String[]{Manifest.permission.READ_SMS},255);
MainActivity
public class MainActivity extends AppCompatActivity {
private ArrayList<model> list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewadapter adapter = new viewadapter(list, getApplicationContext());
ListView lst = (ListView) findViewById(R.id.msg_listview);
lst.setAdapter(adapter);
}
public void onClick (View l){
ContentResolver rslv = getContentResolver();
final String[] p = new String[]{"*"};
Uri uri = Uri.parse("content://sms");
Cursor cursor = rslv.query(uri, p, null, null, null);
cursor.moveToFirst();
while (cursor.moveToNext()){
String address = cursor.getString(cursor.getColumnIndex("address"));
String body = cursor.getString(cursor.getColumnIndex("body"));
model m = new model();
m.setNumbers(address);
m.setMsgbody(body);
list.add(m);
}
}
}
model
public class model {
String numbers;
String msg_body;
public String getNumbers(){
return numbers;
}
public String getMsg_body(){
return msg_body;
}
public void setNumbers(String numbers){
this.numbers = numbers;
}
public void setMsgbody(String msg_body){
this.msg_body = msg_body;
}
}
viewadapter
private class viewadapter extends BaseAdapter{
private ArrayList<model> list = new ArrayList<>();
private Context context;
public viewadapter(ArrayList<model> list, Context context){
this.list = list;
this.context = context;
}
public int getCount(){
return list.size();
}
public View getView(int pos, View view, ViewGroup viewGroup){
View row = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_view_layout, null);
model model = list.get(pos)
TextView number = (TextView) row.findViewById(R.id.txt_number);
number.setText(model.getNumbers);
TextView msg_body = (TextView) row.findViewById(R.id.txt_msg);
Toast.makeText(c, msg_body.getText(), Toast.LENGTH_SHORT).show();
msg_body.setText(model.getMsg_body());
return row;
}
public long getItemId(int pos){
return pos;
}
public Object getItem(int arg){
return list.get(arg);
}
}
}
I don't think there is any need for a controller class.

Related

I am trying to retrieved data from firestore in recyclerview in android studio but getting blank page and no error i have tried many way but not work

sorry in adavaced bcz i am first time askking question on stack flow so and if need any other please let me know
okk my firestore Collestion is like these collection("user").document(currentUserId).collection("AddBlog").document
and i need AddBlog document and last my field name of firestore is same to model.java variable
code of activity name Trial.java
package com.example.talkvirtual;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
public class TrialActivity extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList<Model> dataList;
FirebaseFirestore db;
FirebaseAuth mAuth;
MyAdapter myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trial);
recyclerView = findViewById(R.id.recyclerViewTrial);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
dataList = new ArrayList<>();
recyclerView.setAdapter(myAdapter);
myAdapter = new MyAdapter(dataList,this);
db = FirebaseFirestore.getInstance();
mAuth= FirebaseAuth.getInstance();
String currentUserId = mAuth.getCurrentUser().getUid();
db.collection("user").document(currentUserId).collection("AddBlog").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
for (DocumentSnapshot d : list) {
Model model = d.toObject(Model.class);
dataList.add(model);
}
myAdapter.notifyDataSetChanged();
}
});
}
}
code of adpater class name MyAdapter.java
package com.example.talkvirtual;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
public MyAdapter(ArrayList<Model> listblogProfile, Context context) {
this.ListblogProfile = listblogProfile;
this.context = context;
}
private ArrayList<Model> ListblogProfile;
private Context context;
// private ShowActivity activity;
#NonNull
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.container_blog, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyAdapter.MyViewHolder holder, int position) {
Model model = ListblogProfile.get(position);
holder.blogTitleTv.setText(model.getBlogTitle());
holder.blogContentTv.setText(model.getBlogContent());
}
#Override
public int getItemCount() {
return ListblogProfile.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private TextView blogTitleTv, blogContentTv;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
blogContentTv = itemView.findViewById(R.id.blogContentContainer);
blogTitleTv = itemView.findViewById(R.id.getTitleContainer);
}
}
}
code of my cardView xml file
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/layoutNote"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:foreground="?attr/selectableItemBackgroundBorderless"
app:cardElevation="8dp"
android:layout_margin="10dp"
android:background="#color/light_dark">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/getTitleContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Title"
android:textColor="#color/textColor"
android:textSize="24dp"
android:textStyle="bold"
android:padding="10dp"
/>
<TextView
android:id="#+id/blogContentContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxHeight="100dp"
android:textColor="#color/textColor"
android:hint="Blog Content"
android:textColorHint="#color/gray"
android:textSize="20dp"
android:padding="10dp"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
code of model class
package com.example.talkvirtual;
public class Model {
String blogTitle;
String blogContent;
String id;
public Model(){}//empty constructor is neccessary firebase
public Model(String blogTitle, String blogContent, String id) {
this.blogTitle = blogTitle;
this.blogContent = blogContent;
this.id = id;
}
public String getBlogTitle() {
return blogTitle;
}
public void setBlogTitle(String blogTitle) {
this.blogTitle = blogTitle;
}
public String getBlogContent() {
return blogContent;
}
public void setBlogContent(String blogContent) {
this.blogContent = blogContent;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
I think There are two mistake
1.Your adapter does not have the valid value
when you set it for the recyclerview
2.Your data is null because you don't add any member to it as well as the adapter.
db.collection("user").document(currentUserId).collection("AddBlog").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
for (DocumentSnapshot d : list) {
Model model = d.toObject(Model.class);
dataList.add(model);
}
myAdapter.notifyDataSetChanged();
}
});
myAdapter = new MyAdapter(dataList,this);
recyclerView.setAdapter(myAdapter);
I guess this should be work.

Reason of RecyclerView Not Loading Data

I tried to create a List with RecyclerView in Android. However, I don't understand why the RecyclerView could not load data properly. I tried to compare my codes with the example available online and I could not tell what is the difference between example codes and my codes.
Can anyone help to point out what is missing or what is wrong with my code?
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
tools:context="daozui.assignment3_task3.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/RecyclerView"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
contact_arrangement.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/contactIcon_ID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/man"
android:layout_margin="10dp"/>
<TextView
android:id="#+id/contactName_ID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="30sp"
android:text="Name"
android:layout_toEndOf="#id/contactIcon_ID"
android:layout_marginTop="25dp"
android:layout_marginStart="25dp"/>
<TextView
android:id="#+id/contactRelationship_ID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFBEB9B9"
android:textSize="20sp"
android:text="Relationship"
android:layout_alignStart="#id/contactName_ID"
android:layout_below="#id/contactName_ID"/>
</RelativeLayout>
MainActivity.Java
package daozui.assignment3_task3;
import android.app.ListFragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
RecyclerView theRecyclerView;
List<Contact> contactList;
ContactAdapter theAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createList();
theRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView);
theRecyclerView.setLayoutManager(new LinearLayoutManager(this));
theAdapter = new ContactAdapter(contactList);
theRecyclerView.setAdapter(theAdapter);
}
private void createList() {
contactList = new ArrayList<Contact>();
contactList.add(new Contact("Alex", "male", "Friends", "0123456789"));
contactList.add(new Contact("Mona", "female", "Friends", "9876543210"));
}
}
ContactAdapter.Java
package daozui.assignment3_task3;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.theViewHolder> {
private List<Contact> contacList;
public ContactAdapter(List<Contact> ContactList) {
this.contacList = ContactList;
}
#Override
public ContactAdapter.theViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.contact_arrangement, parent, false);
return new theViewHolder(itemView);
}
#Override
public void onBindViewHolder(theViewHolder holder, int position) {
Contact contact = contacList.get(position);
holder.contactName.setText(contact.getName());
holder.contactRelationship.setText(contact.getRelationship());
if (contact.getGender().equals("male")) {
holder.contactIcon.setImageResource(R.drawable.man);
} else {
holder.contactIcon.setImageResource(R.drawable.woman);
}
}
#Override
public int getItemCount() {
return 0;
}
public static class theViewHolder extends RecyclerView.ViewHolder {
public TextView contactName, contactRelationship;
public ImageView contactIcon;
public theViewHolder(View itemView) {
super(itemView);
contactIcon = (ImageView) itemView.findViewById(R.id.contactIcon_ID);
contactName = (TextView) itemView.findViewById(R.id.contactName_ID);
contactRelationship = (TextView) itemView.findViewById(R.id.contactRelationship_ID);
// itemView.setOnClickListener(this);
}
// #Override
// public void onClick(View view)
// {
// int pos= getAdapterPosition();
// Toast.makeText(itemView.getContext(),contacList.get(pos).getContactNumber(),Toast.LENGTH_LONG);
// }
}
}
Contact.Java
package daozui.assignment3_task3;
public class Contact {
private String name;
private String gender;
private String relationship;
private String contactNumber;
public Contact(String Name, String Gender, String Relationship, String ContactNumber) {
this.name = Name;
this.gender = Gender;
this.relationship = Relationship;
this.contactNumber = ContactNumber;
}
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public String getRelationship() {
return relationship;
}
public String getContactNumber() {
return contactNumber;
}
}
The problem is here:
#Override
public int getItemCount() {
return 0;
}
You should return the size of your list:
#Override
public int getItemCount() {
return contactList.size();
}
You should return the size of your collection here:
#Override
public void getItemCount(){
return contactList.size();
}
getItemCount() Returns the total number of items in the data set held by the adapter.
The int value that getItemCount() returns is the number of times the RecyclerView is going to look for data from your collection to bind.
notify your adapter that data is updated.!
notifyDataSetChanged();
#Override
public int getItemCount() {
return contactList.size();
}
In the event the list is null, use this simple ternary to avoid a null pointer exception;
#Override
public int getItemCount() {
return contactList == null ? 0 : contactList.size();
}

click on textview on listview on fragment

click on textview on listview on fragment
TextView On category_row.xml textViewCategoryName
onclick SetText this textViewCategoryName ok!
CategoriesFragment.java
package com.example;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.example.adapter.CategoryArrayAdapter;
import com.example.model.CategoryDataModel;
import com.example.parser.JSONParser;
import com.example.utils.Keys;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class CategoriesFragment extends Fragment {
private ListView listView;
private ArrayList<CategoryDataModel> list;
private CategoryArrayAdapter adapter;
private TextView categoryCurrent;
public CategoriesFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_categories, null);
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
/**
* Array List for Binding Data from JSON to this List
*/
list = new ArrayList<>();
adapter = new CategoryArrayAdapter(getActivity(), list);
/**
* Getting List and Setting List Adapter
*/
listView = (ListView) getActivity().findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Snackbar.make(getActivity().findViewById(R.id.parentLayout), list.get(position).getCategoryName(), Snackbar.LENGTH_LONG).show();
}
});
/**
* Check internet connection
*/
//if (InternetConnection.checkConnection(getApplicationContext())) {
new GetDataCategories().execute();
//} else {
//Snackbar.make(getActivity().findViewById(R.id.parentLayout), "اتصال به اینترنت برقرار نیست", Snackbar.LENGTH_LONG).show();
//}
}
/**
* Creating Get Data Task for Getting Data From Web
*/
class GetDataCategories extends AsyncTask<Void, Void, Void> {
ContentLoadingProgressBar progressBar;
#Override
protected void onPreExecute() {
super.onPreExecute();
/**
* Progress Bar for User Interaction
*/
progressBar = (ContentLoadingProgressBar) getActivity().findViewById(R.id.progress);
progressBar.show();
}
#Nullable
#Override
protected Void doInBackground(Void... params) {
/**
* Getting JSON Object from Web Using okHttp
*/
JSONObject jsonObject = JSONParser.getDataFromWeb("http://example.com/api-service/v1/platform_categories/");
try {
/**
* Check Whether Its NULL???
*/
if (jsonObject != null) {
/**
* Check Length...
*/
if(jsonObject.length() > 0) {
/**
* Getting Array named "Categories" From MAIN Json Object
*/
JSONArray array = jsonObject.getJSONArray(Keys.KEY_CATEGORIES);
/**
* Check Length of Array...
*/
int lenArray = array.length();
if(lenArray > 0) {
for(int jIndex = 0; jIndex < lenArray; jIndex++) {
/**
* Creating Every time New Object
* and
* Adding into List
*/
CategoryDataModel model = new CategoryDataModel();
/**
* Getting Inner Object from contacts array...
* and
* From that We will get Name of that Contact
*
*/
JSONObject innerObject = array.getJSONObject(jIndex);
String category_name = innerObject.getString(Keys.KEY_CATEGORY_NAME);
String category_link = innerObject.getString(Keys.KEY_CATEGORY_LINK);
/**
* Getting Object from Object "other"
*/
//JSONObject otherObject = innerObject.getJSONObject(Keys.KEY_NAME);
//String other = otherObject.getString(Keys.KEY_NAME_SUB);
model.setCategoryName(category_name);
model.setCategoryLink(category_link);
/**
* Adding data in List...
*/
list.add(model);
}
}
}
} else {
}
} catch (JSONException je) {
Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
/**
* Progress Bar for User Interaction
*/
progressBar.hide();
/**
* Checking if List size if more than zero then
* Update ListView
*/
if(list.size() > 0) {
adapter.notifyDataSetChanged();
} else {
Snackbar.make(getActivity().findViewById(R.id.parentLayout), "مشکلی در اتصال به سرورهای سخنک رخ داده است!", Snackbar.LENGTH_LONG).show();
}
}
}
}
CategoryArrayAdapter.java
package com.example.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.example.R;
import com.example.model.CategoryDataModel;
import java.util.List;
public class CategoryArrayAdapter extends ArrayAdapter<CategoryDataModel> {
List<CategoryDataModel> modelList;
Context context;
private LayoutInflater mInflater;
// Constructors
public CategoryArrayAdapter(Context context, List<CategoryDataModel> objects) {
super(context, 0, objects);
this.context = context;
this.mInflater = LayoutInflater.from(context);
modelList = objects;
}
#Override
public CategoryDataModel getItem(int position) {
return modelList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder vh;
if (convertView == null) {
View view = mInflater.inflate(R.layout.category_row, parent, false);
vh = ViewHolder.create((RelativeLayout) view);
view.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
CategoryDataModel item = getItem(position);
vh.textViewCategoryName.setText(item.getCategoryName());
return vh.rootView;
}
private static class ViewHolder {
public final RelativeLayout rootView;
public final TextView textViewCategoryName;
private ViewHolder(RelativeLayout rootView, TextView textViewCategoryName) {
this.rootView = rootView;
this.textViewCategoryName = textViewCategoryName;
}
public static ViewHolder create(RelativeLayout rootView) {
TextView textViewCategoryName = (TextView) rootView.findViewById(R.id.textViewCategoryName);
return new ViewHolder(rootView, textViewCategoryName);
}
}
}
fragment_categories.xml
<?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:id="#+id/parentLayout"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.v4.widget.ContentLoadingProgressBar
android:id="#+id/progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:visibility="visible" />
<ListView app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:id="#+id/listView"
android:layout_width="fill_parent"
android:layout_height="match_parent" />
</android.support.design.widget.CoordinatorLayout>
category_row.xml
<?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="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_centerVertical="true"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/imageViewProfilePhoto">
<TextView
android:id="#+id/textViewCategoryName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:textAppearanceSmall"
android:textIsSelectable="true"
tools:text="Quote Content" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
</LinearLayout>
</LinearLayout>
</RelativeLayout>
You have to set an onClickListener to your TextView in your ViewHolder.
private static class ViewHolder {
public final RelativeLayout rootView;
public final TextView textViewCategoryName;
private ViewHolder(RelativeLayout rootView, TextView textViewCategoryName) {
this.rootView = rootView;
this.textViewCategoryName = textViewCategoryName;
}
public static ViewHolder create(RelativeLayout rootView) {
TextView textViewCategoryName = (TextView) rootView.findViewById(R.id.textViewCategoryName);
textViewCategoryName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Do whatever you want
}
});
return new ViewHolder(rootView, textViewCategoryName);
}
}

Date picker from SwipeStackAdapter adapter

I have googled alot. But i did't get the solution.
My issue is i have one fragment. In the fragment i am inflating some cards ie the swipe cards. for that swipe cards layout im using SwipeStackAdapter to inflate the view xml.
The in one of my xml view im trying to implement the datepicker.
TaskCardListShow.java fragment code
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v7.app.AppCompatActivity;
import com.jmedeisis.draglinearlayout.DragLinearLayout;
import java.util.ArrayList;
import java.util.List;
import link.fls.swipestack.SwipeStack;
public class TaskCardListShow extends Fragment implements SwipeStack.SwipeStackListener, View.OnClickListener {
private ArrayList<String> mData;
private ArrayList<String> LayOutData;
private SwipeStack mSwipeStack;
private SwipeStackAdapter mAdapter;
public int cardCounter;
Context context;
AutoCompleteTextView autoTextView;
public TaskCardListShow() {
}
public static TaskCardListShow newInstance() {
TaskCardListShow _TaskCardListShow = new TaskCardListShow();
return _TaskCardListShow;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.task_card_list_show, container, false);
mSwipeStack = (SwipeStack) view.findViewById(R.id.swipeStack);
mData = new ArrayList<>();
LayOutData = new ArrayList<>();
mAdapter = new SwipeStackAdapter(mData,LayOutData);
mSwipeStack.setAdapter(mAdapter);
mSwipeStack.setListener(this);
context=getActivity().getApplicationContext();
cardCounter=7;// write function for getting card count.
fillStackCard();
return view;
}
private void fillStackCard() {
for (int x = 0; x <cardCounter; x++) {
mData.add(getString(R.string.dummy_text) + " " + (x + 1));
LayOutData.add(getString(R.string.str_card)+ (x + 1));
}
}
#Override
public void onClick(View v) {
}
#Override
public void onViewSwipedToRight(int position) {
String swipedElement = mAdapter.getItem(position);
}
#Override
public void onViewSwipedToLeft(int position) {
String swipedElement = mAdapter.getItem(position);
}
#Override
public void onStackEmpty() {
removeTaskCardFragment();
}
public void removeTaskCardFragment(){
FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction mFragmentTransaction = manager.beginTransaction();
TaskCardListShow _TaskCardListShowFragment = new TaskCardListShow();
mFragmentTransaction.remove(_TaskCardListShowFragment);
mFragmentTransaction.commit();
manager.popBackStack();
}
public class SwipeStackAdapter extends BaseAdapter {
private List<String> mData;
private List<String> LayOutData;
DragLinearLayout dragDropAndroidLinearLayout;
public SwipeStackAdapter(List<String> data,List<String> Ldata) {
this.mData = data;
this.LayOutData = Ldata;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public String getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
String LName=LayOutData.get(position);
try {
int id = getActivity().getApplicationContext().getResources().
getIdentifier(LName, "layout", getActivity().getPackageName());
convertView = getActivity().getLayoutInflater().inflate(id, parent, false);
if(position==4){ // my date picker layout will come this postion.
}
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
}
card_4.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:layout_width="match_parent"
card_view:cardCornerRadius="#dimen/card_corner_radius"
card_view:cardElevation="#dimen/elevation_large"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center"
android:id="#+id/TxtQuestion">
<TextView
android:id="#+id/textViewCard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="top"
android:textColor="#color/colorAccent"
android:textStyle="bold|italic"
android:textSize="20sp"
android:padding="30dp"
android:layout_gravity="top|center_horizontal|center_vertical"
android:text="Date picker template"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_below="#+id/TxtQuestion"
android:layout_centerInParent="true"
android:id="#+id/linearLayout">
<DatePicker
android:id="#+id/dpResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
Can you please guide me to do this. I have tried lots of method but it is not working i my case
I have solved my problem by,
in my adapter
final TextView _dpResult=(TextView)convertView.findViewById(R.id.dpResult);
_dpResult.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
DialogFragment newFragment = new SelectDateFragment( );
newFragment.show(getFragmentManager(), "DatePicker");
}
});
SelectDateFragment
public class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, yy, mm, dd);
}
public void onDateSet(DatePicker view, int yy, int mm, int dd) {
populateSetDate(yy, mm+1, dd);
}
public void populateSetDate(int year, int month, int day) {
TextView dpResult= (TextView)getActivity().findViewById(R.id.dpResult);
dpResult.setText(year+"-"+month+"-"+day);
}
}
The xml coding for the date picker is
<TextView
android:id="#+id/dpResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="yyyy-mm-dd" />
Now i am able see the date-picker on my card. Thanks

RecyclerView Issue

MainActivity.java
its my main java class
package com.example.shikhu.newpractice;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,DisplayList.class));
}
});
}
}
DisplayList.java
package com.example.shikhu.newpractice;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class DisplayList extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dsiplay_list);
BackgroundTask backgroundTask = new BackgroundTask(DisplayList.this);
backgroundTask.execute();
}
}
BackgroundTask.java
package com.example.shikhu.newpractice;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
public class BackgroundTask extends AsyncTask<Void,Fruit,Void> {
String json_string = "http://192.168.1.18:8081/fruitinfo/get_fruit_details.php";
Context ctx;
Activity activity;
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<Fruit> arrayList = new ArrayList<>();
public BackgroundTask(Context ctx)
{
this.ctx=ctx;
activity = (Activity)ctx;
}
#Override
protected void onPreExecute() {
recyclerView = (RecyclerView)activity.findViewById(R.id.recyclerview);
layoutManager = new LinearLayoutManager(ctx);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerAdapter(arrayList);
recyclerView.setAdapter(adapter);
}
#Override
protected Void doInBackground(Void... params) {
try{
URL url = new URL(json_string);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while((line=bufferedReader.readLine())!=null)
{
stringBuilder.append(line + "\n");
}
httpURLConnection.disconnect();
String json_string = stringBuilder.toString().trim();
JSONObject jsonObject = new JSONObject(json_string);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while (count<jsonArray.length())
{
JSONObject JO = jsonArray.getJSONObject(count);
count++;
Fruit fruit = new Fruit(JO.getString("name"),JO.getInt("calories"),JO.getDouble("fat"));
publishProgress(fruit);
}
Log.d("JSON STRING",json_string);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Fruit... values) {
arrayList.add(values[0]);
adapter.notifyDataSetChanged();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
RecyclerAdapter.java
package com.example.shikhu.newpractice;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerViewHolder> {
private static final int TYPE_HEAD = 0;
private static final int TYPE_LIST = 1;
ArrayList<Fruit> arrayList = new ArrayList<>();
public RecyclerAdapter(ArrayList<Fruit> arrayList)
{
this.arrayList =arrayList;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_HEAD)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.header_layout,parent,false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view,viewType);
return recyclerViewHolder;
}
else if (viewType == TYPE_LIST)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout,parent,false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view,viewType);
return recyclerViewHolder;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
if (holder.viewType == TYPE_LIST) {
Fruit fruit = arrayList.get(position);
holder.Name.setText(fruit.getName());
holder.Calories.setText(Integer.toString(fruit.getCalories()));
holder.Fat.setText(Double.toString(fruit.getFat()));
}
}
#Override
public int getItemCount() {
return arrayList.size();
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder
{
TextView Name,Calories,Fat;
int viewType;
public RecyclerViewHolder(View v,int viewType)
{
super(v);
if (viewType == TYPE_LIST) {
Name = (TextView) v.findViewById(R.id.name);
Calories = (TextView) v.findViewById(R.id.calories);
Fat = (TextView) v.findViewById(R.id.fat);
this.viewType = TYPE_LIST;
}else if (viewType == TYPE_HEAD)
{
this.viewType = TYPE_HEAD;
}
}
public int getItemViewType(int position)
{
if (position==0)
return TYPE_HEAD;
return TYPE_LIST;
}
}
}
Fruit.java
package com.example.shikhu.newpractice;
public class Fruit {
private String name;
private int calories;
private Double fat;
public Fruit(String name,int calories,Double fat)
{
this.setName(name);
this.setCalories(calories);
this.setFat(fat);
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name=name;
}
public int getCalories()
{
return calories;
}
public void setCalories(int calories)
{
this.calories=calories;
}
public Double getFat()
{
return fat;
}
public void setFat(Double fat)
{
this.fat=fat;
}
}
Row_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="75dp"
android:layout_marginRight="15dp"
android:layout_marginLeft="15dp"
android:weightSum="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:textStyle="bold"
android:textSize="20dp"
android:text="Name"
android:id="#+id/name"
android:layout_weight="0.39" />
<TextView
android:layout_width="79dp"
android:layout_height="match_parent"
android:text="Calorie"
android:gravity="center_vertical"
android:textSize="20dp"
android:textStyle="bold"
android:id="#+id/calories"
android:layout_marginLeft="40dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="Fat"
android:gravity="center_vertical"
android:textSize="20dp"
android:textStyle="bold"
android:id="#+id/fat"
android:layout_weight="0.15"
android:layout_marginLeft="60dp" />
</LinearLayout>
Header_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="65dp"
android:background="?attr/colorPrimary">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:textStyle="bold"
android:textSize="20dp"
android:text="Name"
android:id="#+id/name1"
android:layout_weight="0.20"
android:textColor="#ffffff"
android:layout_marginLeft="10dp" />
<TextView
android:layout_width="79dp"
android:layout_height="match_parent"
android:text="Calorie"
android:gravity="center_vertical"
android:textSize="20dp"
android:textStyle="bold"
android:id="#+id/calories1"
android:layout_marginLeft="10dp"
android:textColor="#ffffff"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="Fat"
android:gravity="center_vertical"
android:textSize="20dp"
android:textStyle="bold"
android:id="#+id/fat1"
android:layout_weight="0.15"
android:layout_marginLeft="60dp"
android:textColor="#ffffff"/>
</LinearLayout>
activity_display_list.xml
<?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"
tools:context=".DisplayList">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recyclerview"></android.support.v7.widget.RecyclerView>
</RelativeLayout>
activity_main.xml
<?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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.shikhu.newpractice.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Display List"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
My Output
i dont know why it is showing text of textview rather the data fetched from database
enter image description here
PhpScript
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "fruit";
$con = mysqli_connect($host,$user,$pass,$db);
$query= "select * from fruit_details;";
$result = mysqli_query($con,$query);
$response = array();
while($row = mysqli_fetch_array($result))
{
array_push($response,array('name'=>$row[0],'calories'=>$row[1],'fat'=>$row[2 ]));
}
mysqli_close($con);
echo json_encode(array('server_response'=>$response));
?>
Your Adapter always return TYPE_HEAD i think this is wrong.
#Override
public int getItemViewType(int position) {
if (position == 0) {
return TYPE_HEAD;
} else {
return TYPE_LIST;
}
}
BackgroundTask.Java
package com.example.shikhu.newpractice;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
public class BackgroundTask extends AsyncTask<Void,Fruit,Void> {
String json_string = "http://127.0.0.1:8081/fruitinfo/get_fruit_details.php";
Context ctx;
Activity activity;
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<Fruit> arrayList = new ArrayList<>();
public BackgroundTask(Context ctx)
{
this.ctx=ctx;
activity = (Activity)ctx;
}
#Override
protected void onPreExecute() {
recyclerView = (RecyclerView)activity.findViewById(R.id.recyclerview);
layoutManager = new LinearLayoutManager(ctx);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerAdapter(arrayList);
recyclerView.setAdapter(adapter);
}
#Override
protected Void doInBackground(Void... params) {
try{
URL url = new URL(json_string);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while((line=bufferedReader.readLine())!=null)
{
stringBuilder.append(line + "\n");
}
httpURLConnection.disconnect();
String json_string = stringBuilder.toString().trim();
JSONObject jsonObject = new JSONObject(json_string);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while (count<jsonArray.length())
{
JSONObject JO = jsonArray.getJSONObject(count);
count++;
Fruit fruit = new Fruit(JO.getString("name"),JO.getInt("calorie"),JO.getDouble("fat"));
publishProgress(fruit);
}
Log.d("JSON STRING",json_string);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Fruit... values) {
arrayList.add(values[0]);
adapter.notifyDataSetChanged();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
RecyclerAdapter.java
package com.example.shikhu.newpractice;
import android.support.annotation.IdRes;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerViewHolder> {
private static final int TYPE_HEAD = 0;
private static final int TYPE_LIST = 1;
ArrayList<Fruit> arrayList = new ArrayList<>();
public RecyclerAdapter(ArrayList<Fruit> arrayList)
{
this.arrayList =arrayList;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_HEAD)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.header_layout,parent,false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view,viewType);
return recyclerViewHolder;
}
else if (viewType == TYPE_LIST)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout,parent,false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view,viewType);
return recyclerViewHolder;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
if (holder.viewType == TYPE_LIST) {
Fruit fruit = arrayList.get(position-1);
holder.Name.setText(fruit.getName());
holder.Calories.setText(Integer.toString(fruit.getCalories()));
holder.Fat.setText(Double.toString(fruit.getFat()));
}
}
#Override
public int getItemCount() {
return arrayList.size()+1;
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder
{
TextView Name,Calories,Fat;
int viewType;
public RecyclerViewHolder(View v,int viewType)
{
super(v);
if (viewType == TYPE_LIST) {
Name = (TextView) v.findViewById(R.id.name);
Calories = (TextView) v.findViewById(R.id.calories);
Fat = (TextView) v.findViewById(R.id.fat);
this.viewType = TYPE_LIST;
}else if (viewType == TYPE_HEAD)
{
this.viewType = TYPE_HEAD;
}
}
}
#Override
public int getItemViewType(int position) {
if (position==0)
return TYPE_HEAD;
else
return TYPE_LIST;
}
}
I think you are not managing views for header in your view holder and from bind view holder it is everytime getting only header view in return; SO just debug your code and let me know that are you getting TYPE_LIST data view or not. Also make references for header view in View holder and set text to it also.
I found your problem.
Your method getItemViewType is inside your ViewHolder class. It needs to be moved to be inside your adapter class. Right now, since your adapter has no getItemViewType method, it assumes all view types are 0 (HEADER), and so nothing is being bound.
Move this method to your adapter class and all will work :)
Edit
Another option which should work for you is to stop using viewTypes all together. Since you're using the same viewHolder anyway, when you bind the view, instead of checking the viewType, check the position:
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout,parent,false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view, TYPE_LIST);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
if (position > 0) {
Fruit fruit = arrayList.get(position-1);
holder.Name.setText(fruit.getName());
holder.Calories.setText(Integer.toString(fruit.getCalories()));
holder.Fat.setText(Double.toString(fruit.getFat()));
} else {
holder.Name.setText("Name");
holder.Calories.setText("Calories");
holder.Fat.setText("Fat");
}
}
So now, all your view types will be of type list. This is fine, because the layout is basically identical, only the values of the TextViews changes. Instead of using viewType, simply use the position. If the position is 0, set the header fields, otherwise, use the Fruit data.
I know this is not the solution you wanted - I can't seem to find why the viewType implementation doesn't work, however, this solution should give you the result you wanted.
Hope this helps!

Categories